FuzzTest 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. #!/usr/bin/env python
  2. """
  3. This is a generic fuzz testing tool, see --help for more information.
  4. """
  5. import os
  6. import sys
  7. import random
  8. import subprocess
  9. import itertools
  10. class TestGenerator:
  11. def __init__(self, inputs, delete, insert, replace,
  12. insert_strings, pick_input):
  13. self.inputs = [(s, open(s).read()) for s in inputs]
  14. self.delete = bool(delete)
  15. self.insert = bool(insert)
  16. self.replace = bool(replace)
  17. self.pick_input = bool(pick_input)
  18. self.insert_strings = list(insert_strings)
  19. self.num_positions = sum([len(d) for _,d in self.inputs])
  20. self.num_insert_strings = len(insert_strings)
  21. self.num_tests = ((delete + (insert + replace)*self.num_insert_strings)
  22. * self.num_positions)
  23. self.num_tests += 1
  24. if self.pick_input:
  25. self.num_tests *= self.num_positions
  26. def position_to_source_index(self, position):
  27. for i,(s,d) in enumerate(self.inputs):
  28. n = len(d)
  29. if position < n:
  30. return (i,position)
  31. position -= n
  32. raise ValueError,'Invalid position.'
  33. def get_test(self, index):
  34. assert 0 <= index < self.num_tests
  35. picked_position = None
  36. if self.pick_input:
  37. index,picked_position = divmod(index, self.num_positions)
  38. picked_position = self.position_to_source_index(picked_position)
  39. if index == 0:
  40. return ('nothing', None, None, picked_position)
  41. index -= 1
  42. index,position = divmod(index, self.num_positions)
  43. position = self.position_to_source_index(position)
  44. if self.delete:
  45. if index == 0:
  46. return ('delete', position, None, picked_position)
  47. index -= 1
  48. index,insert_index = divmod(index, self.num_insert_strings)
  49. insert_str = self.insert_strings[insert_index]
  50. if self.insert:
  51. if index == 0:
  52. return ('insert', position, insert_str, picked_position)
  53. index -= 1
  54. assert self.replace
  55. assert index == 0
  56. return ('replace', position, insert_str, picked_position)
  57. class TestApplication:
  58. def __init__(self, tg, test):
  59. self.tg = tg
  60. self.test = test
  61. def apply(self):
  62. if self.test[0] == 'nothing':
  63. pass
  64. else:
  65. i,j = self.test[1]
  66. name,data = self.tg.inputs[i]
  67. if self.test[0] == 'delete':
  68. data = data[:j] + data[j+1:]
  69. elif self.test[0] == 'insert':
  70. data = data[:j] + self.test[2] + data[j:]
  71. elif self.test[0] == 'replace':
  72. data = data[:j] + self.test[2] + data[j+1:]
  73. else:
  74. raise ValueError,'Invalid test %r' % self.test
  75. open(name,'wb').write(data)
  76. def revert(self):
  77. if self.test[0] != 'nothing':
  78. i,j = self.test[1]
  79. name,data = self.tg.inputs[i]
  80. open(name,'wb').write(data)
  81. def quote(str):
  82. return '"' + str + '"'
  83. def run_one_test(test_application, index, input_files, args):
  84. test = test_application.test
  85. # Interpolate arguments.
  86. options = { 'index' : index,
  87. 'inputs' : ' '.join(quote(f) for f in input_files) }
  88. # Add picked input interpolation arguments, if used.
  89. if test[3] is not None:
  90. pos = test[3][1]
  91. options['picked_input'] = input_files[test[3][0]]
  92. options['picked_input_pos'] = pos
  93. # Compute the line and column.
  94. file_data = test_application.tg.inputs[test[3][0]][1]
  95. line = column = 1
  96. for i in range(pos):
  97. c = file_data[i]
  98. if c == '\n':
  99. line += 1
  100. column = 1
  101. else:
  102. column += 1
  103. options['picked_input_line'] = line
  104. options['picked_input_col'] = column
  105. test_args = [a % options for a in args]
  106. if opts.verbose:
  107. print '%s: note: executing %r' % (sys.argv[0], test_args)
  108. stdout = None
  109. stderr = None
  110. if opts.log_dir:
  111. stdout_log_path = os.path.join(opts.log_dir, '%s.out' % index)
  112. stderr_log_path = os.path.join(opts.log_dir, '%s.err' % index)
  113. stdout = open(stdout_log_path, 'wb')
  114. stderr = open(stderr_log_path, 'wb')
  115. else:
  116. sys.stdout.flush()
  117. p = subprocess.Popen(test_args, stdout=stdout, stderr=stderr)
  118. p.communicate()
  119. exit_code = p.wait()
  120. test_result = (exit_code == opts.expected_exit_code or
  121. exit_code in opts.extra_exit_codes)
  122. if stdout is not None:
  123. stdout.close()
  124. stderr.close()
  125. # Remove the logs for passes, unless logging all results.
  126. if not opts.log_all and test_result:
  127. os.remove(stdout_log_path)
  128. os.remove(stderr_log_path)
  129. if not test_result:
  130. print 'FAIL: %d' % index
  131. elif not opts.succinct:
  132. print 'PASS: %d' % index
  133. return test_result
  134. def main():
  135. global opts
  136. from optparse import OptionParser, OptionGroup
  137. parser = OptionParser("""%prog [options] ... test command args ...
  138. %prog is a tool for fuzzing inputs and testing them.
  139. The most basic usage is something like:
  140. $ %prog --file foo.txt ./test.sh
  141. which will run a default list of fuzzing strategies on the input. For each
  142. fuzzed input, it will overwrite the input files (in place), run the test script,
  143. then restore the files back to their original contents.
  144. NOTE: You should make sure you have a backup copy of your inputs, in case
  145. something goes wrong!!!
  146. You can cause the fuzzing to not restore the original files with
  147. '--no-revert'. Generally this is used with '--test <index>' to run one failing
  148. test and then leave the fuzzed inputs in place to examine the failure.
  149. For each fuzzed input, %prog will run the test command given on the command
  150. line. Each argument in the command is subject to string interpolation before
  151. being executed. The syntax is "%(VARIABLE)FORMAT" where FORMAT is a standard
  152. printf format, and VARIABLE is one of:
  153. 'index' - the test index being run
  154. 'inputs' - the full list of test inputs
  155. 'picked_input' - (with --pick-input) the selected input file
  156. 'picked_input_pos' - (with --pick-input) the selected input position
  157. 'picked_input_line' - (with --pick-input) the selected input line
  158. 'picked_input_col' - (with --pick-input) the selected input column
  159. By default, the script will run forever continually picking new tests to
  160. run. You can limit the number of tests that are run with '--max-tests <number>',
  161. and you can run a particular test with '--test <index>'.
  162. You can specify '--stop-on-fail' to stop the script on the first failure
  163. without reverting the changes.
  164. """)
  165. parser.add_option("-v", "--verbose", help="Show more output",
  166. action='store_true', dest="verbose", default=False)
  167. parser.add_option("-s", "--succinct", help="Reduce amount of output",
  168. action="store_true", dest="succinct", default=False)
  169. group = OptionGroup(parser, "Test Execution")
  170. group.add_option("", "--expected-exit-code", help="Set expected exit code",
  171. type=int, dest="expected_exit_code",
  172. default=0)
  173. group.add_option("", "--extra-exit-code",
  174. help="Set additional expected exit code",
  175. type=int, action="append", dest="extra_exit_codes",
  176. default=[])
  177. group.add_option("", "--log-dir",
  178. help="Capture test logs to an output directory",
  179. type=str, dest="log_dir",
  180. default=None)
  181. group.add_option("", "--log-all",
  182. help="Log all outputs (not just failures)",
  183. action="store_true", dest="log_all", default=False)
  184. parser.add_option_group(group)
  185. group = OptionGroup(parser, "Input Files")
  186. group.add_option("", "--file", metavar="PATH",
  187. help="Add an input file to fuzz",
  188. type=str, action="append", dest="input_files", default=[])
  189. group.add_option("", "--filelist", metavar="LIST",
  190. help="Add a list of inputs files to fuzz (one per line)",
  191. type=str, action="append", dest="filelists", default=[])
  192. parser.add_option_group(group)
  193. group = OptionGroup(parser, "Fuzz Options")
  194. group.add_option("", "--replacement-chars", dest="replacement_chars",
  195. help="Characters to insert/replace",
  196. default="0{}[]<>\;@#$^%& ")
  197. group.add_option("", "--replacement-string", dest="replacement_strings",
  198. action="append", help="Add a replacement string to use",
  199. default=[])
  200. group.add_option("", "--replacement-list", dest="replacement_lists",
  201. help="Add a list of replacement strings (one per line)",
  202. action="append", default=[])
  203. group.add_option("", "--no-delete", help="Don't delete characters",
  204. action='store_false', dest="enable_delete", default=True)
  205. group.add_option("", "--no-insert", help="Don't insert strings",
  206. action='store_false', dest="enable_insert", default=True)
  207. group.add_option("", "--no-replace", help="Don't replace strings",
  208. action='store_false', dest="enable_replace", default=True)
  209. group.add_option("", "--no-revert", help="Don't revert changes",
  210. action='store_false', dest="revert", default=True)
  211. group.add_option("", "--stop-on-fail", help="Stop on first failure",
  212. action='store_true', dest="stop_on_fail", default=False)
  213. parser.add_option_group(group)
  214. group = OptionGroup(parser, "Test Selection")
  215. group.add_option("", "--test", help="Run a particular test",
  216. type=int, dest="test", default=None, metavar="INDEX")
  217. group.add_option("", "--max-tests", help="Maximum number of tests",
  218. type=int, dest="max_tests", default=None, metavar="COUNT")
  219. group.add_option("", "--pick-input",
  220. help="Randomly select an input byte as well as fuzzing",
  221. action='store_true', dest="pick_input", default=False)
  222. parser.add_option_group(group)
  223. parser.disable_interspersed_args()
  224. (opts, args) = parser.parse_args()
  225. if not args:
  226. parser.error("Invalid number of arguments")
  227. # Collect the list of inputs.
  228. input_files = list(opts.input_files)
  229. for filelist in opts.filelists:
  230. f = open(filelist)
  231. try:
  232. for ln in f:
  233. ln = ln.strip()
  234. if ln:
  235. input_files.append(ln)
  236. finally:
  237. f.close()
  238. input_files.sort()
  239. if not input_files:
  240. parser.error("No input files!")
  241. print '%s: note: fuzzing %d files.' % (sys.argv[0], len(input_files))
  242. # Make sure the log directory exists if used.
  243. if opts.log_dir:
  244. if not os.path.exists(opts.log_dir):
  245. try:
  246. os.mkdir(opts.log_dir)
  247. except OSError:
  248. print "%s: error: log directory couldn't be created!" % (
  249. sys.argv[0],)
  250. raise SystemExit,1
  251. # Get the list if insert/replacement strings.
  252. replacements = list(opts.replacement_chars)
  253. replacements.extend(opts.replacement_strings)
  254. for replacement_list in opts.replacement_lists:
  255. f = open(replacement_list)
  256. try:
  257. for ln in f:
  258. ln = ln[:-1]
  259. if ln:
  260. replacements.append(ln)
  261. finally:
  262. f.close()
  263. # Unique and order the replacement list.
  264. replacements = list(set(replacements))
  265. replacements.sort()
  266. # Create the test generator.
  267. tg = TestGenerator(input_files, opts.enable_delete, opts.enable_insert,
  268. opts.enable_replace, replacements, opts.pick_input)
  269. print '%s: note: %d input bytes.' % (sys.argv[0], tg.num_positions)
  270. print '%s: note: %d total tests.' % (sys.argv[0], tg.num_tests)
  271. if opts.test is not None:
  272. it = [opts.test]
  273. elif opts.max_tests is not None:
  274. it = itertools.imap(random.randrange,
  275. itertools.repeat(tg.num_tests, opts.max_tests))
  276. else:
  277. it = itertools.imap(random.randrange, itertools.repeat(tg.num_tests))
  278. for test in it:
  279. t = tg.get_test(test)
  280. if opts.verbose:
  281. print '%s: note: running test %d: %r' % (sys.argv[0], test, t)
  282. ta = TestApplication(tg, t)
  283. try:
  284. ta.apply()
  285. test_result = run_one_test(ta, test, input_files, args)
  286. if not test_result and opts.stop_on_fail:
  287. opts.revert = False
  288. sys.exit(1)
  289. finally:
  290. if opts.revert:
  291. ta.revert()
  292. sys.stdout.flush()
  293. if __name__ == '__main__':
  294. main()