Joshua Hood | 65ecceb | 2022-03-14 16:18:50 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 2 | # |
Avi Drissman | dfd88085 | 2022-09-15 20:11:09 | [diff] [blame] | 3 | # Copyright 2016 The Chromium Authors |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 4 | # Use of this source code is governed by a BSD-style license that can be |
| 5 | # found in the LICENSE file. |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 6 | """Generate a dictionary for libFuzzer or AFL-based fuzzer. |
| 7 | |
| 8 | Invoked manually using a fuzzer binary and target format/protocol specification. |
| 9 | Works better for text formats or protocols. For binary ones may be useless. |
| 10 | """ |
| 11 | |
| 12 | import argparse |
Brian Sheedy | fe2702e | 2024-12-13 21:48:20 | [diff] [blame] | 13 | # 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. |
| 16 | import HTMLParser # pylint: disable=import-error |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 17 | import logging |
| 18 | import os |
| 19 | import re |
| 20 | import shutil |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 21 | import subprocess |
| 22 | import sys |
| 23 | import tempfile |
| 24 | |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 25 | ENCODING_TYPES = ['ascii', 'utf_16_be', 'utf_16_le', 'utf_32_be', 'utf_32_le'] |
| 26 | MIN_STRING_LENGTH = 4 |
| 27 | |
| 28 | |
| 29 | def 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 | |
| 36 | def EscapeDictionaryElement(element): |
| 37 | """Escape all unprintable and control characters in an element.""" |
mmoroz | a767005 | 2016-07-07 13:03:08 | [diff] [blame] | 38 | element_escaped = element.encode('string_escape') |
| 39 | # Remove escaping for single quote because it breaks libFuzzer. |
Brian Sheedy | 0d2300f3 | 2024-08-13 23:14:41 | [diff] [blame] | 40 | element_escaped = element_escaped.replace("\\'", "'") |
mmoroz | a767005 | 2016-07-07 13:03:08 | [diff] [blame] | 41 | # Add escaping for double quote. |
| 42 | element_escaped = element_escaped.replace('"', '\\"') |
| 43 | return element_escaped |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 44 | |
| 45 | |
| 46 | def 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 | |
| 62 | def 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 | |
| 72 | def 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 | |
| 79 | def 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 Sheedy | 822e0374 | 2024-08-09 18:48:14 | [diff] [blame] | 87 | for i in range(0, len(lines), 1): |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 88 | 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 Pastene | b5c6726 | 2024-05-15 21:24:01 | [diff] [blame] | 97 | current_block = lines[i][n:] |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 98 | elif n == previous_number_of_spaces and current_block: |
| 99 | # Or continuation of a space-indented text block, concatenate lines. |
Ben Pastene | b5c6726 | 2024-05-15 21:24:01 | [diff] [blame] | 100 | current_block += '\n' + lines[i][n:] |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 101 | |
| 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 | |
| 112 | def 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 | |
| 121 | def 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 Sheedy | 0d2300f3 | 2024-08-13 23:14:41 | [diff] [blame] | 125 | logging.error("%s doesn't exist. Exit.", filepath) |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 126 | 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 | |
| 153 | def 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 | |
| 188 | def 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 | |
| 199 | def 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 | |
| 210 | def main(): |
Brian Sheedy | 0d2300f3 | 2024-08-13 23:14:41 | [diff] [blame] | 211 | parser = argparse.ArgumentParser(description='Generate fuzzer dictionary.') |
Ben Pastene | b5c6726 | 2024-05-15 21:24:01 | [diff] [blame] | 212 | parser.add_argument('--fuzzer', |
| 213 | required=True, |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 214 | 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 Pastene | b5c6726 | 2024-05-15 21:24:01 | [diff] [blame] | 218 | parser.add_argument('--spec', |
| 219 | required=True, |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 220 | help='Path to a target specification (in textual form).') |
Ben Pastene | b5c6726 | 2024-05-15 21:24:01 | [diff] [blame] | 221 | parser.add_argument('--html', |
| 222 | default=0, |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 223 | help='Decode HTML [01] (0 is default value): ' |
| 224 | '1 - if specification has HTML entities to be decoded.') |
Ben Pastene | b5c6726 | 2024-05-15 21:24:01 | [diff] [blame] | 225 | parser.add_argument('--out', |
| 226 | required=True, |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 227 | help='Path to a file to write a dictionary into.') |
Ben Pastene | b5c6726 | 2024-05-15 21:24:01 | [diff] [blame] | 228 | parser.add_argument('--strategy', |
| 229 | default='iu', |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 230 | help='Generation strategy [iqu] ("iu" is default value): ' |
| 231 | 'i - intersection, q - quoted, u - uppercase.') |
| 232 | args = parser.parse_args() |
| 233 | |
Ben Pastene | b5c6726 | 2024-05-15 21:24:01 | [diff] [blame] | 234 | dictionary = GenerateDictionary(args.fuzzer, |
| 235 | args.spec, |
| 236 | args.strategy, |
mmoroz | 1a6bef1 | 2016-07-07 12:07:44 | [diff] [blame] | 237 | is_html=bool(args.html)) |
| 238 | WriteDictionary(args.out, dictionary) |
| 239 | |
| 240 | |
| 241 | if __name__ == '__main__': |
| 242 | main() |