#!/usr/bin/env python3
"""
PDF Fuzzer using JRSFuzz
by Javantea
Oct 29, 2015
DNS Fuzzer using JRSFuzz
by Javantea
Oct 11, 2015
Based on SMTP Fuzzer using JRSFuzz
by Javantea
Oct 11, 2015
Based on SMTP Grammar Fuzzer
by Javantea
Sept 14, 2015

A very reasonable dumb fuzzer for PDF. It's a mutation fuzzer.
Provide the following values to fuzz a binary file you have captured:
python3 pdf_jrsfuzz1.py filename

TODO:
Handle errors returned by the executable.
Monitors with GDB and ASAN integration.
"""
import jrsfuzz
import sys
import debug1
import time
import tempfile

def main():
	# This works on any DNS server but it won't work on certain types
	data = b'%'
	if len(sys.argv) > 1:
		filename = sys.argv[1]
		data = open(filename, 'rb').read()
	#end if
	lines_output = len(data) * 256
	print("%i outputs, %3.3f MB" % (lines_output, lines_output*len(data)/(1<<20)), file=sys.stderr)
	start, end = 0, lines_output
	if len(sys.argv) > 2:
		start = int(sys.argv[2])
	#end if
	if len(sys.argv) > 3:
		end = int(sys.argv[3])
	#end if
	if start > lines_output: start = lines_output-1
	if end > lines_output: end = lines_output
	outfile = tempfile.NamedTemporaryFile(suffix='.pdf', prefix='fuzzfile', dir='.', delete=False)
	filename_out = outfile.name

	#prevResp = None
	for i in range(start, end):
		x = jrsfuzz.JRSFuzz(data, i)
		outfile.seek(0)
		outfile.write(x)
		outfile.flush()
		print(i)
		start = time.time()
		r = debug1.fork_exec('/usr/bin/pdftotext', ['pdftotext', '-q', filename_out, '/dev/null'])
		end = time.time()
		if r == None:
			print("Failed to execute apparently.")
			continue
		#end if
		pid, sts = r
		print("Now I have control again.", (pid, sts))
		if sts == 11:
			print("Segmentation fault on iteration {}".format(i))
		#end if
		if (end-start) >= 3:
			print("Slow execution on iteration {}".format(i))
		#end if
	#next i
#end def main()

if __name__ == '__main__':
	main()
#end if