blob: f26758ceacbccd900d782a97aff9e3301ce16a16 [file] [log] [blame]
Joshua Hood65ecceb2022-03-14 16:18:501#!/usr/bin/env python3
mmoroz1a6bef12016-07-07 12:07:442#
Avi Drissmandfd880852022-09-15 20:11:093# Copyright 2016 The Chromium Authors
mmoroz1a6bef12016-07-07 12:07:444# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
mmoroz1a6bef12016-07-07 12:07:446"""Generate a dictionary for libFuzzer or AFL-based fuzzer.
7
8Invoked manually using a fuzzer binary and target format/protocol specification.
9Works better for text formats or protocols. For binary ones may be useless.
10"""
11
12import argparse
Brian Sheedyfe2702e2024-12-13 21:48:2013# This is a Python 2-only import despite the file using a Python 3 shebang. This
14# implies that this file has been unused for years and has not been properly
15# converted to Python 3.
16import HTMLParser # pylint: disable=import-error
mmoroz1a6bef12016-07-07 12:07:4417import logging
18import os
19import re
20import shutil
mmoroz1a6bef12016-07-07 12:07:4421import subprocess
22import sys
23import tempfile
24
mmoroz1a6bef12016-07-07 12:07:4425ENCODING_TYPES = ['ascii', 'utf_16_be', 'utf_16_le', 'utf_32_be', 'utf_32_le']
26MIN_STRING_LENGTH = 4
27
28
29def DecodeHTML(html_data):
30 """HTML-decoding of the data."""
31 html_parser = HTMLParser.HTMLParser()
32 data = html_parser.unescape(html_data.decode('ascii', 'ignore'))
33 return data.encode('ascii', 'ignore')
34
35
36def EscapeDictionaryElement(element):
37 """Escape all unprintable and control characters in an element."""
mmoroza7670052016-07-07 13:03:0838 element_escaped = element.encode('string_escape')
39 # Remove escaping for single quote because it breaks libFuzzer.
Brian Sheedy0d2300f32024-08-13 23:14:4140 element_escaped = element_escaped.replace("\\'", "'")
mmoroza7670052016-07-07 13:03:0841 # Add escaping for double quote.
42 element_escaped = element_escaped.replace('"', '\\"')
43 return element_escaped
mmoroz1a6bef12016-07-07 12:07:4444
45
46def ExtractWordsFromBinary(filepath, min_length=MIN_STRING_LENGTH):
47 """Extract words (splitted strings) from a binary executable file."""
48 rodata = PreprocessAndReadRodata(filepath)
49 words = []
50
51 strings_re = re.compile(r'[^\x00-\x1F\x7F-\xFF]{%d,}' % min_length)
52 # Use different encodings for strings extraction.
53 for encoding in ENCODING_TYPES:
54 data = rodata.decode(encoding, 'ignore').encode('ascii', 'ignore')
55 raw_strings = strings_re.findall(data)
56 for splitted_line in map(lambda line: line.split(), raw_strings):
57 words += splitted_line
58
59 return set(words)
60
61
62def ExtractWordsFromLines(lines):
63 """Extract all words from a list of strings."""
64 words = set()
65 for line in lines:
66 for word in line.split():
67 words.add(word)
68
69 return words
70
71
72def ExtractWordsFromSpec(filepath, is_html):
73 """Extract words from a specification."""
74 data = ReadSpecification(filepath, is_html)
75 words = data.split()
76 return set(words)
77
78
79def FindIndentedText(text):
80 """Find space-indented text blocks, e.g. code or data samples in RFCs."""
81 lines = text.split('\n')
82 indented_blocks = []
83 current_block = ''
84 previous_number_of_spaces = 0
85
86 # Go through every line and concatenate space-indented blocks into lines.
Brian Sheedy822e03742024-08-09 18:48:1487 for i in range(0, len(lines), 1):
mmoroz1a6bef12016-07-07 12:07:4488 if not lines[i]:
89 # Ignore empty lines.
90 continue
91
92 # Space-indented text blocks have more leading spaces than regular text.
93 n = FindNumberOfLeadingSpaces(lines[i])
94
95 if n > previous_number_of_spaces:
96 # Beginning of a space-indented text block, start concatenation.
Ben Pasteneb5c67262024-05-15 21:24:0197 current_block = lines[i][n:]
mmoroz1a6bef12016-07-07 12:07:4498 elif n == previous_number_of_spaces and current_block:
99 # Or continuation of a space-indented text block, concatenate lines.
Ben Pasteneb5c67262024-05-15 21:24:01100 current_block += '\n' + lines[i][n:]
mmoroz1a6bef12016-07-07 12:07:44101
102 if n < previous_number_of_spaces and current_block:
103 # Current line is not indented, save previously concatenated lines.
104 indented_blocks.append(current_block)
105 current_block = ''
106
107 previous_number_of_spaces = n
108
109 return indented_blocks
110
111
112def FindNumberOfLeadingSpaces(line):
113 """Calculate number of leading whitespace characters in the string."""
114 n = 0
115 while n < len(line) and line[n].isspace():
116 n += 1
117
118 return n
119
120
121def GenerateDictionary(path_to_binary, path_to_spec, strategy, is_html=False):
122 """Generate a dictionary for given pair of fuzzer binary and specification."""
123 for filepath in [path_to_binary, path_to_spec]:
124 if not os.path.exists(filepath):
Brian Sheedy0d2300f32024-08-13 23:14:41125 logging.error("%s doesn't exist. Exit.", filepath)
mmoroz1a6bef12016-07-07 12:07:44126 sys.exit(1)
127
128 words_from_binary = ExtractWordsFromBinary(path_to_binary)
129 words_from_spec = ExtractWordsFromSpec(path_to_spec, is_html)
130
131 dictionary_words = set()
132
133 if 'i' in strategy:
134 # Strategy i: only words which are common for binary and for specification.
135 dictionary_words = words_from_binary.intersection(words_from_spec)
136
137 if 'q' in strategy:
138 # Strategy q: add words from all quoted strings from specification.
139 # TODO(mmoroz): experimental and very noisy. Not recommended to use.
140 spec_data = ReadSpecification(path_to_spec, is_html)
141 quoted_strings = FindIndentedText(spec_data)
142 quoted_words = ExtractWordsFromLines(quoted_strings)
143 dictionary_words = dictionary_words.union(quoted_words)
144
145 if 'u' in strategy:
146 # Strategy u: add all uppercase words from specification.
147 uppercase_words = set(w for w in words_from_spec if w.isupper())
148 dictionary_words = dictionary_words.union(uppercase_words)
149
150 return dictionary_words
151
152
153def PreprocessAndReadRodata(filepath):
154 """Create a stripped copy of the binary and extract .rodata section."""
155 stripped_file = tempfile.NamedTemporaryFile(prefix='.stripped_')
156 stripped_filepath = stripped_file.name
157 shutil.copyfile(filepath, stripped_filepath)
158
159 # Strip all symbols to reduce amount of redundant strings.
160 strip_cmd = ['strip', '--strip-all', stripped_filepath]
161 result = subprocess.call(strip_cmd)
162 if result:
163 logging.warning('Failed to strip the binary. Using the original version.')
164 stripped_filepath = filepath
165
166 # Extract .rodata section to reduce amount of redundant strings.
167 rodata_file = tempfile.NamedTemporaryFile(prefix='.rodata_')
168 rodata_filepath = rodata_file.name
169 objcopy_cmd = ['objcopy', '-j', '.rodata', stripped_filepath, rodata_filepath]
170
171 # Hide output from stderr since objcopy prints a warning.
172 with open(os.devnull, 'w') as devnull:
173 result = subprocess.call(objcopy_cmd, stderr=devnull)
174
175 if result:
176 logging.warning('Failed to extract .rodata section. Using the whole file.')
177 rodata_filepath = stripped_filepath
178
179 with open(rodata_filepath) as file_handle:
180 data = file_handle.read()
181
182 stripped_file.close()
183 rodata_file.close()
184
185 return data
186
187
188def ReadSpecification(filepath, is_html):
189 """Read a specification file and return its contents."""
190 with open(filepath, 'r') as file_handle:
191 data = file_handle.read()
192
193 if is_html:
194 data = DecodeHTML(data)
195
196 return data
197
198
199def WriteDictionary(dictionary_path, dictionary):
200 """Write given dictionary to a file."""
201 with open(dictionary_path, 'wb') as file_handle:
202 file_handle.write('# This is an automatically generated dictionary.\n')
203 for word in dictionary:
204 if not word:
205 continue
206 line = '"%s"\n' % EscapeDictionaryElement(word)
207 file_handle.write(line)
208
209
210def main():
Brian Sheedy0d2300f32024-08-13 23:14:41211 parser = argparse.ArgumentParser(description='Generate fuzzer dictionary.')
Ben Pasteneb5c67262024-05-15 21:24:01212 parser.add_argument('--fuzzer',
213 required=True,
mmoroz1a6bef12016-07-07 12:07:44214 help='Path to a fuzzer binary executable. It is '
215 'recommended to use a binary built with '
216 '"use_libfuzzer=false is_asan=false" to get a better '
217 'dictionary with fewer number of redundant elements.')
Ben Pasteneb5c67262024-05-15 21:24:01218 parser.add_argument('--spec',
219 required=True,
mmoroz1a6bef12016-07-07 12:07:44220 help='Path to a target specification (in textual form).')
Ben Pasteneb5c67262024-05-15 21:24:01221 parser.add_argument('--html',
222 default=0,
mmoroz1a6bef12016-07-07 12:07:44223 help='Decode HTML [01] (0 is default value): '
224 '1 - if specification has HTML entities to be decoded.')
Ben Pasteneb5c67262024-05-15 21:24:01225 parser.add_argument('--out',
226 required=True,
mmoroz1a6bef12016-07-07 12:07:44227 help='Path to a file to write a dictionary into.')
Ben Pasteneb5c67262024-05-15 21:24:01228 parser.add_argument('--strategy',
229 default='iu',
mmoroz1a6bef12016-07-07 12:07:44230 help='Generation strategy [iqu] ("iu" is default value): '
231 'i - intersection, q - quoted, u - uppercase.')
232 args = parser.parse_args()
233
Ben Pasteneb5c67262024-05-15 21:24:01234 dictionary = GenerateDictionary(args.fuzzer,
235 args.spec,
236 args.strategy,
mmoroz1a6bef12016-07-07 12:07:44237 is_html=bool(args.html))
238 WriteDictionary(args.out, dictionary)
239
240
241if __name__ == '__main__':
242 main()