├── AflCrashAnalyzer.py
├── LICENSE
├── README
├── modules
├── CrashAnalysisConfig.py
├── ExploitableGdbPlugin.py
├── FeelingLuckyExploiter.py
├── FileDuplicateFinder.py
├── FilesizeFinder.py
├── InputMinimizer.py
├── OutputFinder.py
├── SignalFinder.py
└── __init__.py
├── testcases
├── clamav
│ └── install.sh
├── ffmpeg
│ ├── Config.py
│ └── install.sh
└── gm
│ ├── Config.py
│ └── install.sh
└── utilities
├── Executer.py
├── Logger.py
├── OutputUtility.py
└── __init__.py
/AflCrashAnalyzer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 | '''
3 | AFL crash analyzer, crash triage for the American Fuzzy Lop fuzzer
4 | Copyright (C) 2015 floyd
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | Created on Apr 13, 2015
20 | @author: floyd, http://floyd.ch, @floyd_ch
21 | '''
22 |
23 | from modules.FileDuplicateFinder import FileDuplicateFinder
24 | from modules.SignalFinder import SignalFinder
25 | from modules.OutputFinder import OutputFinder
26 | from modules.InputMinimizer import InputMinimizer
27 | from modules.FeelingLuckyExploiter import FeelingLuckyExploiter
28 | from modules.ExploitableGdbPlugin import ExploitableGdbPlugin
29 | from utilities.Logger import Logger
30 | import os
31 | import glob
32 |
33 |
34 | def analyze_output_and_exploitability(config, signal_finder, uninteresting_signals, message_prefix=""):
35 | for signal, signal_folder in signal_finder.get_folder_paths_for_signals_if_exist(uninteresting_signals):
36 | skip = False
37 | for cat in ExploitableGdbPlugin.get_classifications():
38 | if os.path.exists(os.path.join(signal_folder, cat)):
39 | Logger.warning("Seems like there are already exploitability analysis results, skipping. If you want to rerun: rm -r %s" % os.path.join(signal_folder, cat))
40 | skip = True
41 | if not skip:
42 | Logger.info(message_prefix, "Discover stdout, stderr, gdb and ASAN output (signal %s)" % signal)
43 | wildcard_for_run_output_files = os.path.join(signal_folder, "*" + config.run_extension)
44 | if glob.glob(wildcard_for_run_output_files):
45 | Logger.warning("Seems like there are already results from running the binaries, skipping. If you want to rerun: rm", wildcard_for_run_output_files)
46 | else:
47 | of = OutputFinder(config, signal_folder)
48 | of.do_sane_output_runs()
49 |
50 | Logger.info(message_prefix, "Analyzing exploitability (signal %s)" % signal)
51 | egp = ExploitableGdbPlugin(config, signal_folder)
52 | egp.divide_by_exploitability()
53 |
54 | def main():
55 | # Read the README before you start.
56 |
57 | Logger.info("Setting up configuration")
58 |
59 | gdb_script_64bit = r"""printf "[+] Disabling verbose and complaints\n"
60 | set verbose off
61 | set complaints 0
62 | printf "[+] Backtrace:\n"
63 | bt
64 | printf "[+] info reg:\n"
65 | info reg
66 | printf "[+] exploitable:\n"
67 | exploitable
68 | printf "[+] disassemble $rip, $rip+16:\n"
69 | disassemble $rip, $rip+16
70 | printf "[+] list\n"
71 | list
72 | """
73 | gdb_script_32bit = r"""printf "[+] Disabling verbose and complaints\n"
74 | set verbose off
75 | set complaints 0
76 | printf "[+] Backtrace:\n"
77 | bt
78 | printf "[+] info reg:\n"
79 | info reg
80 | printf "[+] exploitable:\n"
81 | exploitable
82 | printf "[+] disassemble $eip, $eip+16:\n"
83 | disassemble $eip, $eip+16
84 | printf "[+] list\n"
85 | list
86 | """
87 |
88 | # TODO: Make sure gdb script doesn't abort on error
89 | # ignoring errors in gdb scripts: http://stackoverflow.com/questions/17923865/gdb-stops-in-a-command-file-if-there-is-an-error-how-to-continue-despite-the-er
90 | gdb_script_32bit_noerror = r"""python
91 | def my_ignore_errors(arg):
92 | try:
93 | gdb.execute("print \"" + "Executing command: " + arg + "\"")
94 | gdb.execute (arg)
95 | except:
96 | gdb.execute("print \"" + "ERROR: " + arg + "\"")
97 |
98 | my_ignore_errors("p p")
99 | my_ignore_errors("p p->v1")
100 | gdb.execute("quit")
101 | """
102 |
103 | where_this_python_script_lives = os.path.dirname(os.path.realpath(__file__))
104 |
105 | gdb_command = "/usr/bin/gdb"
106 | #gdb_command_osx = "/opt/local/bin/gdb-apple"
107 |
108 | #TODO: For some reason the ASAN environment variables are not correctly set when given to the subprocess module... so let's just set it in parent process already:
109 | os.environ['ASAN_SYMBOLIZER_PATH'] = "/usr/bin/llvm-symbolizer-3.4"
110 | os.environ['ASAN_OPTIONS'] = "symbolize=1:redzone=512:quarantine_size=512Mb:exitcode=1:abort_on_error=1"
111 | env={"ASAN_SYMBOLIZER_PATH": "/usr/bin/llvm-symbolizer-3.4", "ASAN_OPTIONS": "symbolize=1:redzone=512:quarantine_size=512Mb:exitcode=1:abort_on_error=1"}
112 |
113 | ###
114 | # This import decides which testcase/binary we want to run!
115 | ###
116 | from testcases.ffmpeg.Config import create_config
117 | #from testcases.ffmpeg.Config import create_config
118 | #see CrashAnalysisConfig for more options that get passed on by create_config
119 | chosen_config = create_config(where_this_python_script_lives, env=env, gdb_script=gdb_script_32bit, gdb_binary=gdb_command)
120 | chosen_config.sanity_check()
121 |
122 | #
123 | Logger.info("Input crashes directory operations")
124 | #
125 |
126 | Logger.info("Removing README.txt files")
127 | fdf = FileDuplicateFinder(chosen_config, chosen_config.original_crashes_directory)
128 | fdf.remove_readmes()
129 |
130 | Logger.info("Removing duplicates from original crashes folder (same file size + MD5)")
131 | fdf.delete_duplicates_recursively()
132 |
133 | Logger.info("Renaming files from original crashes folder so that the filename is a unique identifier. This allows us to copy all crash files into one directory (eg. for tmin output) if necessary, without name collisions")
134 | fdf.rename_same_name_files()
135 | #OR:
136 | #Logger.info("Renaming all files to numeric values, as some programs prefer no special chars in filenames and might require a specific file extension")
137 | #fdf.rename_all_files(".png")
138 |
139 | #
140 | Logger.info("Finding interesting signals (all crashes)")
141 | #
142 | sf_all_crashes = SignalFinder(chosen_config)
143 | if os.path.exists(chosen_config.default_signal_directory):
144 | Logger.warning("Seems like all crashes were already categorized by signal, skipping. If you want to rerun: rm -r", chosen_config.default_signal_directory)
145 | else:
146 | Logger.debug("Dividing files to output folder according to their signal")
147 | sf_all_crashes.divide_by_signal()
148 |
149 | #Interestings signals: negative on OSX, 129 and above sometimes for Linux on the shell (depending on used mechanism)
150 | #Uninteresting signals: We usually don't care about signals 0, 1, 2, etc. up to 128
151 | uninteresting_signals = range(0, 129)
152 |
153 | analyze_output_and_exploitability(chosen_config, sf_all_crashes, uninteresting_signals, message_prefix="Interesting signals /")
154 |
155 | Logger.info("Interesting signals / Minimizing input (afl-tmin)")
156 | if os.path.exists(chosen_config.default_minimized_crashes_directory):
157 | Logger.warning("Seems like crashes were already minimized, skipping. If you want to rerun: rm -r", chosen_config.default_minimized_crashes_directory)
158 | else:
159 | for signal, signal_folder in sf_all_crashes.get_folder_paths_for_signals_if_exist(uninteresting_signals):
160 | Logger.debug("Minimizing inputs resulting in signal %i" % signal)
161 | im = InputMinimizer(chosen_config, signal_folder)
162 | im.minimize_testcases()
163 |
164 | Logger.info("Interesting signals / Minimized inputs / Deduplication")
165 | fdf_minimized = FileDuplicateFinder(chosen_config, chosen_config.default_minimized_crashes_directory)
166 | fdf_minimized.delete_duplicates_recursively()
167 |
168 | #
169 | Logger.info("Interesting signals / Minimized inputs / Finding interesting signals")
170 | #
171 | sf_minimized_crashes = SignalFinder(chosen_config, chosen_config.default_minimized_crashes_directory, os.path.join(chosen_config.output_dir, "minimized-per-signal"))
172 | if os.path.exists(sf_minimized_crashes.output_dir):
173 | Logger.warning("Seems like minimized crashes were already categorized by signal, skipping. If you want to rerun: rm -r", sf_minimized_crashes.output_dir)
174 | else:
175 | os.mkdir(sf_minimized_crashes.output_dir)
176 | Logger.info("Dividing files to output folder according to their signal")
177 | sf_minimized_crashes.divide_by_signal(0)
178 |
179 |
180 | analyze_output_and_exploitability(chosen_config, sf_minimized_crashes, uninteresting_signals, message_prefix="Interesting signals / Minimized inputs /")
181 |
182 | #TODO:
183 | #- Make (some) modules work as standalone applications with command line parsing
184 | #- The FeelingLuckyExplotier thing. Need to get a small test sample where I know it should work.
185 | # # If you are in the mood to waste a little CPU time, run this
186 | # Logger.info("Found interesting_signals (interesting interesting_signals) / Minimized inputs (interested interesting_signals) / Feeling lucky auto exploitation")
187 | # #
188 | # fle = FeelingLuckyExploiter(chosen_config, sf_minimized_crashes.output_dir)
189 | # #os.mkdir(fle.output_dir)
190 | # fle.run_forest_run()
191 |
192 |
193 | cleanup(chosen_config)
194 |
195 |
196 | def cleanup(config):
197 | for path, _, files in os.walk(config.tmp_dir):
198 | for filename in files:
199 | os.remove(os.path.join(path, filename))
200 |
201 | if __name__ == "__main__":
202 | main()
203 |
204 |
205 |
206 |
207 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README:
--------------------------------------------------------------------------------
1 | afl crash analyzer: Another crash analysis and triage tool for American Fuzzy Lop (AFL) results.
2 |
3 | Goals of this project:
4 | - Simple, flexible python scripts for crash analysis, if dependencies allow it the scripts are standalone tools as well (see FileDuplicateFinder.py)
5 | - Everything file based (no database)
6 | - There is no command line argument parsing planned (except for the standalone tools), but you have to modify the main python script to your preferences
7 |
8 | Features:
9 | 1. Crash input file deduplication (on filesize + md5), renaming of duplicate names (or all files), removing README.txt files. This part is now additionally a standalone command line tool (FileDuplicateFinder.py) that can be used independently from the project
10 | 2. Running binary with each crash input file and divide the input file into folders for each signal
11 | 3. For crash input files that create signals you are interested in you can:
12 | 4. Run the binary and put stdout/stderr into a .txt file next to the crash input file
13 | 5. The same for ASAN enabled binaries to get ASAN output
14 | 6. Run the binary with gdb in batch mode and a configurable gdb script (for example including the "exploitable" gdb script). Remember: the exploitable gdb plugin lies *a lot*.
15 | 7. If you run the exploitable gdb plugin you can divide into subfolders again (EXPLOITABLE, PROBABLY_EXPLOITABLE, etc.)
16 | 8. Minimize input crashes with afl-tmin, deduplication on the results and the same procedure again as described in 4.-7.
17 |
18 | Installation:
19 | 0. Install AFL
20 | 1. Prepare your linux box, do whatever makes sense for a fuzzing machine, for example:
21 | a) sudo apt-get remove whoopsie
22 | 2. Install exploitable gdb script if you want to use it
23 | 3. Compile binaries (one plain, one ASAN, one instrumented is recommended) if you haven't already (see install.sh files in testcases folder for examples)
24 | 4. Start with reading AflCrashAnalyzer.py and configure the CrashAnalysisConfig object in there (examples included and the config has a lot of additional named arguments)
25 | 5. Start AflCrashAnalyzer.py with python 2.7
26 |
27 | A couple of notes:
28 | - If AFL binaries are not /usr/local/bin, configure the path as a named argument to CrashAnalysisConfig
29 | - The target binary is started as: /opt/binary-instrumented args_before input-file args_after, no stdin supported at the moment (sorry for that, will do as soon as I get crashes for the first stdin target)
30 | - You might want to update the code for all your binaries to the newest developer version before compilation (even if you fuzzed on older version), so you filter out crashes that were fixed by the maintainer in the meantime. Check testcases folder (install.sh) for examples.
31 | - You *do* want to run "peruvian were rabbit" on all your crashes (I guess at least one cycle) *before* you feed it into this program. That will help you a lot to determine exploitability.
32 | - afl instrumented binary is the minimum, recommend is to also set at least one of the following binaries
33 | - target_binary_plain (non-instrumented, with symbols, no ASAN)
34 | - target_binary_asan (non-instrumented, with symbols, with ASAN)
35 | - To get line numbers for files when running gdb, use clang's ASAN and specify ASAN_SYMBOLIZER_PATH (env configuration option, see AflCrashAnalyzer.py), see https://code.google.com/p/address-sanitizer/wiki/Flags
36 | - When you configure the gdb script, DON'T add the "run" command at the beginning and the "quit" command at the end
37 | - Again: Don't fully rely on the results of the exploitable gdb plugin. It lies.
38 | - The main python file has code that shows how *I* like to run stuff, maybe you have other preferences
39 | - Just because you get minimized crash files out of this it doesn't mean you shouldn't check their original version. You might judge differently about their exploitability.
40 |
41 | Bugs and todo's:
42 | - see "TODO" in code
43 |
44 | License:
45 | - GPL version 3
46 |
--------------------------------------------------------------------------------
/modules/CrashAnalysisConfig.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 | '''
3 | AFL crash analyzer, crash triage for the American Fuzzy Lop fuzzer
4 | Copyright (C) 2015 floyd
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | Created on Apr 13, 2015
20 | @author: floyd, http://floyd.ch, @floyd_ch
21 | '''
22 | import os
23 | from utilities.Logger import Logger
24 | from utilities.OutputUtility import get_new_output_file_name
25 |
26 |
27 | class CrashAnalysisConfig:
28 | def __init__(self, main_dir, target_binary_instrumented, args_before, args_after,
29 | target_binary_plain=None, target_binary_asan=None, crash_dir=None, is_stdin_binary=False, tmin_args=[],
30 | run_timeout=15, max_digets=4, env={}, output_dir=None, gdb_script=None, gdb_binary="gdb",
31 | afl_binaries_location="/usr/local/bin"):
32 |
33 | #Main directory where these scripts live, all other directories will be derived relatively from here
34 | self.main_dir = main_dir
35 |
36 | #Where you stored the crash files AFL produced
37 | if crash_dir is None:
38 | self.original_crashes_directory = os.path.join(self.main_dir, "crashes")
39 | else:
40 | self.original_crashes_directory = crash_dir
41 |
42 | #Where we will store the output of all the stuff we run.
43 | if output_dir is None:
44 | self.output_dir = os.path.join(self.main_dir, "output")
45 | else:
46 | self.output_dir = output_dir
47 |
48 | #a tmp directory, where they should put it:
49 | self.tmp_dir = os.path.join(self.output_dir, "tmp")
50 |
51 | #When we categorize crashes by signals and no directory for output is given, this one will be used
52 | self.default_signal_directory = os.path.join(self.output_dir, "per-signal")
53 |
54 | #When we minimize crashes and no directory for output is given, this one will be used
55 | self.default_minimized_crashes_directory = os.path.join(self.output_dir, "minimized-inputs")
56 |
57 | #Make sure this binary is instrumented (meaning compiled with afl-gcc or afl-clang), so that it can be used
58 | #with afl binaries (eg. afl-tmin). This is the "minimum" target binary you need.
59 | #Full path necessary
60 | self.target_binary_instrumented = target_binary_instrumented
61 |
62 | #After finding crashes, we want to categorize crashes without any involvement of AFL.
63 | #Only use the instrumented binary if you are 100% sure the AFL compilation didn't introduce any bugs.
64 | #So best would be if this is a regular gcc compile, WITH symbols BUT WITHOUT ASAN, just clean.
65 | #For example the binary from your OS repository
66 | #If you don't have such a binary, leave it as None
67 | #Full path necessary
68 | self.target_binary_plain = target_binary_plain
69 |
70 | #Same as target_binary_plain but with ASAN enabled
71 | #If you don't have such a binary, leave it as None
72 | #Full path necessary
73 | self.target_binary_asan = target_binary_asan
74 |
75 | #Any arguments for binary which should be put in front of the input file parameter @@
76 | self.args_before = args_before
77 |
78 | #Any arguments for binary which should be put after the input file parameter @@
79 | self.args_after = args_after
80 |
81 | #How many digets, especially for file names. For example 6 means file will be named 000001 to 999999
82 | #and the scripts will crash if you have more than 999999 files
83 | self.max_digets = max_digets
84 |
85 | #usually output filess have naming convention: fileName-binaryName-outputPrefix-gdbPrefix-runExtension
86 | #Prefixes for binary type
87 | self.output_prefix_plain = "-plain"
88 | self.output_prefix_instrumented = "-instrumented"
89 | self.output_prefix_asan = "-asan"
90 | #Prefix if run with gdb
91 | self.gdb_prefix = "-gdb"
92 | #The file extension for *ALL* output files (for runs, eg. stdout/stderr or with gdb)
93 | self.run_extension = "_run.txt"
94 |
95 | #environment variables used whenever anything is executed in a shell
96 | self.env = env
97 |
98 | #gdb script
99 | self.gdb_script = gdb_script
100 |
101 | #where we write the gdb script to disc
102 | self.gdb_script_path = os.path.join(self.tmp_dir, "gdb_script.txt")
103 | self.gdb_binary = gdb_binary
104 | self.gdb_args = ["-q", "--batch"]
105 |
106 | #AFL binaries location
107 | self.afl_binaries_location = afl_binaries_location
108 |
109 | #tmin args
110 | self.tmin_args = tmin_args
111 |
112 | #How long we execute binaries until we kill them. This is for a "regular" run with an input file in seconds
113 | self.run_timeout = run_timeout
114 |
115 | #How long we run afl-tmin on one input file until we kill it. What we do in seconds for a single run, we do in minutes for tmin.
116 | self.run_timeout_tmin = self.run_timeout*60
117 |
118 | #True if this binary is not reading from a file but is reading stdin
119 | self.is_stdin_binary = is_stdin_binary
120 |
121 |
122 | def sanity_check(self):
123 | ##
124 | # Sanity checks and initial setup
125 | ##
126 | if not os.access(self.target_binary_instrumented, os.R_OK):
127 | Logger.fatal("AFL target binary not accessible:", self.target_binary_instrumented+". Did you configure the CrashAnalysisConfig class?")
128 | if not self.target_binary_plain is None and not os.access(self.target_binary_plain, os.R_OK):
129 | Logger.fatal("Target binary not accessible:", self.target_binary_plain+". Did you configure the CrashAnalysisConfig class?")
130 | if not self.target_binary_asan is None and not os.access(self.target_binary_asan, os.R_OK):
131 | Logger.fatal("ASAN target binary not accessible:", self.target_binary_asan+". Did you configure the CrashAnalysisConfig class?")
132 | if not os.access(self.main_dir, os.F_OK):
133 | Logger.fatal("Your main_dir doesn't exist:", self.main_dir)
134 | if not os.access(self.original_crashes_directory, os.F_OK):
135 | Logger.fatal("Your original_crashes_directory doesn't exist:", self.original_crashes_directory)
136 |
137 | if os.path.exists(self.output_dir):
138 | Logger.warning("Your output directory already exists, did you want to move it before running?", self.output_dir)
139 | else:
140 | Logger.info("Output folder will be:", self.output_dir)
141 | os.mkdir(self.output_dir)
142 | if not os.path.exists(self.tmp_dir):
143 | os.mkdir(self.tmp_dir)
144 | self.prepare_gdb_script()
145 |
146 | def prepare_gdb_script(self, new_gdb_script=None):
147 | if new_gdb_script is None:
148 | new_gdb_script = self.gdb_script
149 | output_file_path = self.gdb_script_path
150 | else:
151 | output_file_path = os.path.join(self.tmp_dir, get_new_output_file_name(self.tmp_dir, "gdb_script", ".txt", self.max_digets))
152 | #TODO: support stdin
153 | script_content = 'run' + os.linesep
154 | script_content += new_gdb_script + os.linesep
155 | script_content += "quit"
156 | file(output_file_path, "w").write(script_content)
157 | return output_file_path
158 |
159 | def get_command_line(self, binary, filepath):
160 | command = [binary]
161 | if self.args_before:
162 | command.extend(self.args_before)
163 | if filepath: #TODO: support stdin
164 | command.append(filepath)
165 | if self.args_after:
166 | command.extend(self.args_after)
167 | return command
168 |
169 | @DeprecationWarning
170 | def get_command_line_shell_string(self, binary, filepath):
171 | command = '"'+binary+'"'
172 | if self.args_before:
173 | command += " "+self.args_before
174 | if filepath: #TODO: support stdin
175 | command += ' "'+filepath+'"'
176 | if self.args_after:
177 | command += " "+self.args_after
178 | return command
179 |
180 | def get_gdb_command_line(self, binary, filepath, path_to_gdb_script=None):
181 | if path_to_gdb_script is None:
182 | path_to_gdb_script = self.gdb_script_path
183 | command = [self.gdb_binary]
184 | if self.gdb_args:
185 | command.extend(self.gdb_args)
186 | command.extend(['--command='+path_to_gdb_script])
187 | command.extend(['--args'])
188 | command.extend(self.get_command_line(binary, filepath))
189 | return command
190 |
191 | @DeprecationWarning
192 | def get_gdb_command_line_shell_string(self, binary, filepath, path_to_gdb_script=None):
193 | if path_to_gdb_script is None:
194 | path_to_gdb_script = self.gdb_script_path
195 | command = self.gdb_binary
196 | if self.gdb_args:
197 | command += ' '+self.gdb_args
198 | command += ' --command="'+path_to_gdb_script+'"'
199 | command += ' --args '+self.get_command_line(binary, filepath)
200 | return command
201 |
202 | def get_afl_tmin_command_line(self, input_filepath, output_filepath):
203 | command = [os.path.join(self.afl_binaries_location, "afl-tmin")]
204 | if self.tmin_args:
205 | command.extend(self.tmin_args)
206 | command.extend(['-i', input_filepath])
207 | command.extend(['-o', output_filepath])
208 | if self.is_stdin_binary:
209 | command.extend(self.get_command_line(self.target_binary_instrumented, ""))
210 | else:
211 | command.extend(self.get_command_line(self.target_binary_instrumented, "@@"))
212 | return command
213 |
214 | @DeprecationWarning
215 | def get_afl_tmin_command_line_shell_string(self, input_filepath, output_filepath):
216 | command = "afl-tmin"
217 | if self.tmin_args:
218 | command += " "+self.tmin_args
219 | command += ' -i "'+input_filepath+'"'
220 | command += ' -o "'+output_filepath+'"'
221 | if self.is_stdin_binary:
222 | command += ' '+self.get_command_line(self.target_binary_instrumented, "")
223 | else:
224 | command += ' '+self.get_command_line(self.target_binary_instrumented, "@@")
225 | return command
226 |
227 | def get_most_standard_binary(self):
228 | if self.target_binary_plain is not None:
229 | return self.target_binary_plain
230 | elif self.target_binary_asan is not None:
231 | return self.target_binary_asan
232 | elif self.target_binary_instrumented is not None:
233 | return self.target_binary_instrumented
234 |
235 | def get_gdb_exploitable_file_extension(self):
236 | #I guess there is no point in running the "exploitable" gdb plugin over an ASAN binary
237 | if self.target_binary_plain:
238 | return "-"+os.path.basename(self.target_binary_plain)+self.output_prefix_plain+self.gdb_prefix+self.run_extension
239 | else:
240 | return "-"+os.path.basename(self.target_binary_instrumented)+self.output_prefix_instrumented+self.gdb_prefix+self.run_extension
--------------------------------------------------------------------------------
/modules/ExploitableGdbPlugin.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 | '''
3 | AFL crash analyzer, crash triage for the American Fuzzy Lop fuzzer
4 | Copyright (C) 2015 floyd
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | Created on Apr 13, 2015
20 | @author: floyd, http://floyd.ch, @floyd_ch
21 | '''
22 | import shutil
23 | import os
24 | import glob
25 | from utilities.Logger import Logger
26 |
27 |
28 | class ExploitableGdbPlugin:
29 | #If you wrote the gdb output to a different directory than where the input crash file lived,
30 | #I'm sorry, you can not use this class
31 | classifications = ["EXPLOITABLE", "PROBABLY_EXPLOITABLE", "PROBABLY_NOT_EXPLOITABLE", "UNKNOWN" ]
32 |
33 | def __init__(self, config, search_dir, output_dir=None):
34 | self.config = config
35 | self.search_dir = search_dir
36 | #output directory will be just the same place where the input file is if output_dir is None
37 | self.output_dir = output_dir
38 |
39 | @staticmethod
40 | def get_classifications():
41 | return ExploitableGdbPlugin.classifications
42 |
43 | def divide_by_exploitability(self, function=shutil.move):
44 | if self.output_dir is not None and not os.path.exists(self.output_dir):
45 | os.mkdir(self.output_dir)
46 | for path, _, files in os.walk(self.search_dir):
47 | for filename in files:
48 | if filename.endswith(self.config.run_extension):
49 | continue
50 | filepath = os.path.join(path, filename)
51 | gdb_out_filepath = filepath+self.config.get_gdb_exploitable_file_extension()
52 | if os.path.exists(gdb_out_filepath):
53 | file_content = file(gdb_out_filepath, "rb").read()
54 | out_dir_main = self.output_dir
55 | if out_dir_main is None:
56 | out_dir_main = path
57 | out_dir = os.path.join(out_dir_main, "UNCATEGORIZED") + os.path.sep
58 | for classification in self.classifications:
59 | if self._get_search_string_for_classification(classification) in file_content:
60 | out_dir = os.path.join(out_dir_main, classification) + os.path.sep
61 | break
62 | if not os.path.exists(out_dir):
63 | os.mkdir(out_dir)
64 | Logger.debug("Moving", filepath+"* to", out_dir, debug_level=4)
65 | for file_all_extensions in glob.glob(filepath+"*"):
66 | function(file_all_extensions, out_dir)
67 | else:
68 | Logger.warning("Seems like there is no gdb output file %s, can not find exploitability" % gdb_out_filepath)
69 |
70 | def _get_search_string_for_classification(self, classification):
71 | return "Exploitability Classification: "+classification
--------------------------------------------------------------------------------
/modules/FeelingLuckyExploiter.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 | '''
3 | AFL crash analyzer, crash triage for the American Fuzzy Lop fuzzer
4 | Copyright (C) 2015 floyd
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | Created on Apr 13, 2015
20 | @author: floyd, http://floyd.ch, @floyd_ch
21 | '''
22 | from utilities.Logger import Logger
23 | from utilities.Executer import Executer
24 | from utilities.OutputUtility import list_as_intervals
25 | import os
26 | import re
27 |
28 | class FeelingLuckyExploiter:
29 | """
30 | Simple idea:
31 | We replace a couple of bytes in the input file with something else
32 | and check if the crashing eip is changing.
33 | """
34 | def __init__(self, config, search_dir=None, output_dir=None):
35 | self.config = config
36 | self.search_dir = search_dir
37 | if self.search_dir is None:
38 | self.search_dir = self.config.original_crashes_directory
39 | self.output_dir = output_dir
40 | if self.output_dir is None:
41 | self.output_dir = os.path.join(self.config.output_dir, "byte-changing-offsets")
42 | self.lucky_hex_values = "EEDDCCBB".decode("hex")
43 | #self.lucky_hex_values_upper_bound = hex(int(self.lucky_hex_values.encode("hex"),16)+0xFF)[2:].decode("hex")
44 | self.lucky_hex_values_upper_bound = "EEDDCDBB".decode("hex")
45 | self.gdb_script = """info registers eip"""
46 | self.gdb_script_path = self.config.prepare_gdb_script(self.gdb_script)
47 | self.regular_expr = re.compile("eip +(0x[0-9a-fA-F]{8})")
48 | self.executer = Executer(self.config)
49 |
50 | def run_forest_run(self):
51 | if self.output_dir is not None and not os.path.exists(self.output_dir):
52 | os.mkdir(self.output_dir)
53 | new_file_path = os.path.join(self.config.tmp_dir, "feelingLucky.txt")
54 | cmd = self.config.get_gdb_command_line(self.config.get_most_standard_binary(), new_file_path, self.gdb_script_path)
55 | for path, _, files in os.walk(self.search_dir):
56 | for filename in files:
57 | eips = []
58 | indexes = []
59 | if filename.endswith(self.config.run_extension):
60 | continue
61 | Logger.info("Trying my luck with", filename)
62 | filepath = os.path.join(path, filename)
63 | orig_file = file(filepath, "rb").read()
64 | Logger.debug(filepath, debug_level=4)
65 | for index in xrange(0,len(orig_file)-len(self.lucky_hex_values)):
66 | new_file = orig_file[:index] + self.lucky_hex_values + orig_file[index+len(self.lucky_hex_values):]
67 | #Logger.debug(new_file[:100])
68 | file(new_file_path, "w").write(new_file)
69 | crash_eip = self.get_crash_eip(cmd)
70 | if crash_eip:
71 | if not crash_eip in eips:
72 | eips.append(crash_eip)
73 | indexes.append(index)
74 | if self.lucky_hex_values <= crash_eip and crash_eip <= self.lucky_hex_values_upper_bound:
75 | o = os.path.join(self.output_dir, filename)
76 | Logger.info("WTF, we actually were able to control EIP! See file ", o)
77 | file(o, "w").write(new_file)
78 | # else:
79 | # Logger.debug("Binary crashed, but at eip:", hex(crash_eip), "index to put lucky hex value in file:", index, debug_level=7)
80 | Logger.info("Seen the following crashing eips for this file:", list_as_intervals(eips, as_hex=True))
81 | Logger.info("File indexes that lead to different crashes for this file:", list_as_intervals(indexes))
82 |
83 |
84 | def get_crash_eip(self, cmd):
85 | eip = None
86 | Logger.busy()
87 | gdb_output = self.executer.run_command(cmd, env=self.config.env, stdout=self.executer.pipe, stderr=self.executer.pipe)
88 | #Logger.debug("GDB output:", gdb_output)
89 | m = self.regular_expr.search(gdb_output)
90 | if m:
91 | eip = m.group(1)
92 | eip = int(eip, 16)
93 | #if not signal == SignalFinder.TIMEOUT_SIGNAL:
94 | # Logger.error("Minimizing this file took too long, aborted")
95 | return eip
--------------------------------------------------------------------------------
/modules/FileDuplicateFinder.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 | '''
3 | AFL crash analyzer, crash triage for the American Fuzzy Lop fuzzer
4 | Copyright (C) 2015 floyd
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | Created on Apr 13, 2015
20 | @author: floyd, http://floyd.ch, @floyd_ch
21 | '''
22 | import os
23 | import shutil
24 | import sys
25 | from md5 import md5
26 | from argparse import ArgumentParser
27 | from argparse import RawDescriptionHelpFormatter
28 | if __name__ == "__main__":
29 | class Logger:
30 | @staticmethod
31 | def info(*text):
32 | print "[+] "+str(" ".join(str(i) for i in text))
33 | else:
34 | from utilities.Logger import Logger
35 |
36 | class FileDuplicateFinder:
37 | def __init__(self, config, search_dir):
38 | self.config = config
39 | self.search_dir = search_dir
40 |
41 | def find_duplicate_contents(self, rootdir):
42 | """Find duplicate files in directory tree."""
43 | filesizes = {}
44 | # Build up dict with key as filesize and value is list of filenames.
45 | for path, _, files in os.walk(rootdir):
46 | for filename in files:
47 | if filename.endswith(self.config.run_extension):
48 | continue
49 | filepath = os.path.join(path, filename)
50 | filesize = os.stat(filepath).st_size
51 | filesizes.setdefault(filesize, []).append(filepath)
52 | # We are only interested in lists with more than one entry,
53 | # meaning a file can not have the same content if it has a
54 | # different size
55 | for files in [ flist for flist in filesizes.values() if len(flist)>1 ]:
56 | unique = set()
57 | for filepath in files:
58 | with open(filepath) as openfile:
59 | filehash = md5(openfile.read()).hexdigest()
60 | if filehash not in unique:
61 | unique.add(filehash)
62 | else:
63 | yield filepath
64 |
65 | def delete_duplicates_recursively(self):
66 | Logger.info("Removing duplicates in", self.search_dir)
67 | for duplicate in self.find_duplicate_contents(self.search_dir):
68 | if duplicate.endswith(self.config.run_extension):
69 | continue
70 | Logger.info("Deleting the duplicate file:", duplicate)
71 | os.remove(duplicate)
72 |
73 | def remove_readmes(self):
74 | for path, _, files in os.walk(self.search_dir):
75 | for filename in files:
76 | if filename == "README.txt":
77 | filepath = os.path.join(path, filename)
78 | Logger.info("Deleting the file:", filepath)
79 | os.remove(filepath)
80 |
81 | def rename_same_name_files(self):
82 | filenames = []
83 | for path, _, files in os.walk(self.search_dir):
84 | for filename in files:
85 | i = 1
86 | new_filename = filename
87 | name, extension = os.path.splitext(filename)
88 | while new_filename in filenames:
89 | formatstr = "%0"+str(self.config.max_digets)+"d"
90 | new_number = formatstr % i
91 | new_filename = name + "_" + new_number + extension
92 | i += 1
93 | if not new_filename == filename:
94 | Logger.info("Found filename that is already taken, renaming", filename, "to", new_filename)
95 | shutil.move(os.path.join(path, filename), os.path.join(path, new_filename))
96 | filenames.append(new_filename)
97 |
98 | def rename_all_files(self, extension=""):
99 | i = 1
100 | for path, _, files in os.walk(self.search_dir):
101 | for filename in files:
102 | formatstr = "%0"+str(self.config.max_digets+4)+"d"
103 | new_filename = formatstr % i
104 | shutil.move(os.path.join(path, filename), os.path.join(path, new_filename+extension))
105 | i = i+1
106 | Logger.info("Renamed all files starting from 1, last file was named", new_filename+extension)
107 |
108 |
109 |
110 |
111 | def main(argv=None):
112 | if argv is None:
113 | argv = sys.argv
114 | else:
115 | sys.argv.extend(argv)
116 |
117 | # Setup argument parser
118 | parser = ArgumentParser(description="GPLv3 floyd's FileDuplicateFinder (part of AFL crash analyzer)", formatter_class=RawDescriptionHelpFormatter)
119 | parser.add_argument("-s", "--rename-same", dest="same", action="store_true", help="Rename one file if two have the same name")
120 | parser.add_argument("-a", "--rename-all", dest="all", action="store_true", help="Rename all files to a numeric value")
121 | parser.add_argument("-e", "--extension", default=None, dest="extension", help="Extension that is appended to filenames if -a is used")
122 | parser.add_argument("-i", "--ignore-extension", default=None, dest="ignore", metavar="EXTENSION", help="Files with this extension are ignored for -s -a -d and -p (default: None is ignored)")
123 | parser.add_argument("-d", "--delete-duplicates", dest="duplicates", action="store_true", help="Delete all duplicates (file size + MD5)")
124 | parser.add_argument("-r", "--delete-readmes", dest="readmes", action="store_true", help="Delete all files named README.txt")
125 | parser.add_argument("-p", "--print", action="store_true", dest="printdups", help="Print all duplicate files (attention: performance wise you do file size + MD5 again with -d)")
126 | parser.add_argument(dest="path", help="path to folder to search through (mandatory)", nargs=1)
127 |
128 | # Process arguments
129 | args = parser.parse_args()
130 |
131 | #duck type the config
132 | class Config:
133 | run_extension = "WE_DO_NOT_WANT_TO_IGNORE_FILES_THAT_END_WITH_TXT_OR_ANYTHING_SIMILAR"+"A"*20
134 | max_digets = 4
135 |
136 | config = Config()
137 |
138 | if args.ignore:
139 | config.run_extension = args.ignore
140 | fdf = FileDuplicateFinder(config, args.path[0])
141 |
142 | if args.printdups:
143 | for dup in fdf.find_duplicate_contents(args.path[0]):
144 | print "Duplicate:", dup
145 | if args.duplicates:
146 | fdf.delete_duplicates_recursively()
147 | if args.all:
148 | if args.extension:
149 | fdf.rename_all_files(args.extension)
150 | else:
151 | fdf.rename_all_files()
152 | elif args.same:
153 | fdf.rename_same_name_files()
154 | if args.readmes:
155 | fdf.remove_readmes()
156 | return 0
157 |
158 |
159 | if __name__ == "__main__":
160 | sys.exit(main())
161 |
162 |
163 |
--------------------------------------------------------------------------------
/modules/FilesizeFinder.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 | '''
3 | AFL crash analyzer, crash triage for the American Fuzzy Lop fuzzer
4 | Copyright (C) 2015 floyd
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | Created on Apr 13, 2015
20 | @author: floyd, http://floyd.ch, @floyd_ch
21 | '''
22 | import os
23 | import shutil
24 |
25 | class FilesizeFinder:
26 | def __init__(self, config):
27 | self.config = config
28 |
29 | def files_by_file_size(self, dirname, largest_to_smallest=False):
30 | filepaths = []
31 | for path, _, files in os.walk(dirname):
32 | for filename in files:
33 | if filename.endswith(self.config.run_extension):
34 | continue
35 | filepath = os.path.join(path, filename)
36 | filesize = os.stat(filepath).st_size
37 | filepaths.append((path, filename, filesize))
38 | # Sort list by file size
39 | # If reverse=True sort from largest to smallest
40 | # If reverse=False sort from smallest to largest
41 | filepaths.sort(key=lambda f: f[2], reverse=largest_to_smallest)
42 | return filepaths
43 |
44 |
45 | def rename_by_file_size(self, dirname, largest_to_smallest=False, keep_old_file=False, target=None):
46 | new_name = "%"+self.config.max_digets+"d" % 1
47 | for path, filename, _ in self.files_by_file_size(dirname, largest_to_smallest=largest_to_smallest):
48 | if target:
49 | new_name_path = target+os.path.sep+new_name
50 | else:
51 | #default: write it into the same directory where the input file lived
52 | new_name_path = path+os.path.sep+new_name
53 | if keep_old_file:
54 | shutil.copyfile(path+os.path.sep+filename, new_name_path)
55 | else:
56 | shutil.move(path+os.path.sep+filename, new_name_path)
57 | new_name = "%"+self.config.max_digets+"d" % (int(new_name)+1)
58 |
59 |
--------------------------------------------------------------------------------
/modules/InputMinimizer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 | '''
3 | AFL crash analyzer, crash triage for the American Fuzzy Lop fuzzer
4 | Copyright (C) 2015 floyd
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | Created on Apr 13, 2015
20 | @author: floyd, http://floyd.ch, @floyd_ch
21 | '''
22 | from utilities.Logger import Logger
23 | from utilities.Executer import Executer
24 | from modules.SignalFinder import SignalFinder
25 | import os
26 |
27 | class InputMinimizer:
28 | def __init__(self, config, search_dir=None, output_dir=None):
29 | self.config = config
30 | self.search_dir = search_dir
31 | if self.search_dir is None:
32 | self.search_dir = self.config.original_crashes_directory
33 | self.output_dir = output_dir
34 | if self.output_dir is None:
35 | self.output_dir = self.config.default_minimized_crashes_directory
36 |
37 | def minimize_testcases(self):
38 | if self.output_dir is not None and not os.path.exists(self.output_dir):
39 | os.mkdir(self.output_dir)
40 | executer = Executer(self.config)
41 | for path, _, files in os.walk(self.search_dir):
42 | for filename in files:
43 | if filename.endswith(self.config.run_extension):
44 | continue
45 | Logger.info("Minimizing", filename)
46 | filepath = os.path.join(path, filename)
47 | cmd = self.config.get_afl_tmin_command_line(filepath, os.path.join(self.output_dir, filename))
48 | Logger.debug("Executing:", cmd)
49 | Logger.busy()
50 | signal = executer.run_command(cmd, timeout=self.config.run_timeout_tmin, env=self.config.env)
51 | if signal == SignalFinder.TIMEOUT_SIGNAL:
52 | Logger.error("Minimizing this file took too long, aborted")
53 |
--------------------------------------------------------------------------------
/modules/OutputFinder.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 | '''
3 | AFL crash analyzer, crash triage for the American Fuzzy Lop fuzzer
4 | Copyright (C) 2015 floyd
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | Created on Apr 13, 2015
20 | @author: floyd, http://floyd.ch, @floyd_ch
21 | '''
22 | from utilities.Logger import Logger
23 | from utilities.Executer import Executer
24 | from utilities.OutputUtility import get_new_output_file_name
25 | import os
26 |
27 | class OutputFinder:
28 | def __init__(self, config, search_dir=None, output_dir=None):
29 | self.config = config
30 | self.search_dir = search_dir
31 | if self.search_dir is None:
32 | self.search_dir = self.config.original_crashes_directory
33 | #output directory will be just the same place where the input file is if output_dir is None
34 | self.output_dir = output_dir
35 |
36 | def do_sane_output_runs(self):
37 | if self.output_dir is not None and not os.path.exists(self.output_dir):
38 | os.mkdir(self.output_dir)
39 | if self.config.target_binary_plain is None and self.config.target_binary_asan is None:
40 | Logger.warning("You didn't specify any non-instrumented binary, running tests with instrumented binaries")
41 | self.instrumented_combined_stdout_stderr()
42 | self.instrumented_combined_stdout_stderr(gdb_run=True)
43 | else:
44 | Logger.info("Plain run")
45 | self.plain_combined_stdout_stderr()
46 | Logger.info("Plain gdb run")
47 | self.plain_combined_stdout_stderr(gdb_run=True)
48 | Logger.info("ASAN run")
49 | self.asan_combined_stdout_stderr()
50 | #I don't know why we should run this:
51 | #Logger.info("ASAN gdb run")
52 | #self.asan_combined_stdout_stderr(gdb_run=True)
53 |
54 |
55 | def instrumented_combined_stdout_stderr(self, gdb_run=False):
56 | self._combined_stdout_stderr(self.config.target_binary_instrumented, gdb_run, self.config.output_prefix_instrumented)
57 |
58 | def plain_combined_stdout_stderr(self, gdb_run=False):
59 | if not self.config.target_binary_plain:
60 | Logger.warning("You didn't configure a plain binary (recommended: with symbols), therefore skipping run with plain binary.")
61 | else:
62 | self._combined_stdout_stderr(self.config.target_binary_plain, gdb_run, self.config.output_prefix_plain)
63 |
64 | def asan_combined_stdout_stderr(self, gdb_run=False):
65 | if not self.config.target_binary_asan:
66 | Logger.warning("You didn't configure an ASAN enabled binary (recommended: with symbols), therefore skipping run with ASAN binary.")
67 | else:
68 | self._combined_stdout_stderr(self.config.target_binary_asan, gdb_run, self.config.output_prefix_asan)
69 |
70 |
71 | def _combined_stdout_stderr(self, binary, gdb_run, hint):
72 | executer = Executer(self.config)
73 | for path, _, files in os.walk(self.search_dir):
74 | for filename in files:
75 | if filename.endswith(self.config.run_extension):
76 | continue
77 | filepath = os.path.join(path, filename)
78 | if gdb_run:
79 | command = self.config.get_gdb_command_line(binary, filepath)
80 | new_filename = filename+"-"+os.path.basename(binary)+hint+self.config.gdb_prefix
81 | else:
82 | command = self.config.get_command_line(binary, filepath)
83 | new_filename = filename+"-"+os.path.basename(binary)+hint
84 | Logger.debug("Looking for stdout/stderr output:", command, debug_level=4)
85 | if self.output_dir:
86 | output_file_name = get_new_output_file_name(self.output_dir, new_filename, self.config.run_extension, self.config.max_digets)
87 | new_filepath = os.path.join(self.output_dir, output_file_name)
88 | else:
89 | output_file_name = get_new_output_file_name(path, new_filename, self.config.run_extension, self.config.max_digets)
90 | new_filepath = os.path.join(path, output_file_name)
91 | fp = file(new_filepath, "w")
92 | Logger.busy()
93 | executer.run_command(command, env=self.config.env, stdout=fp, stderr=fp)
94 | fp.close()
95 |
96 |
--------------------------------------------------------------------------------
/modules/SignalFinder.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 | '''
3 | AFL crash analyzer, crash triage for the American Fuzzy Lop fuzzer
4 | Copyright (C) 2015 floyd
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | Created on Apr 13, 2015
20 | @author: floyd, http://floyd.ch, @floyd_ch
21 | '''
22 | import os
23 | import shutil
24 | from utilities.Executer import Executer
25 | from utilities.Logger import Logger
26 |
27 | class SignalFinder:
28 |
29 | TIMEOUT_SIGNAL=9998
30 | VARYING_SIGNAL=9999
31 |
32 | def __init__(self, config, search_dir=None, output_dir=None):
33 | self.config = config
34 | self.search_dir = search_dir
35 | if self.search_dir is None:
36 | self.search_dir = self.config.original_crashes_directory
37 | self.output_dir = output_dir
38 | if self.output_dir is None:
39 | self.output_dir = self.config.default_signal_directory
40 | if config.target_binary_plain:
41 | Logger.debug("Using", self.config.target_binary_plain, "for signal run")
42 | self.binary_to_use = self.config.target_binary_plain
43 | elif config.target_binary_asan:
44 | Logger.debug("Using", self.config.target_binary_asan, "for signal run")
45 | self.binary_to_use = self.config.target_binary_asan
46 | else:
47 | Logger.debug("Using", self.config.target_binary_instrumented, "for signal run")
48 | self.binary_to_use = self.config.target_binary_instrumented
49 |
50 |
51 | def divide_by_signal(self, confirmation_loops=0, function=shutil.copyfile):
52 | if self.output_dir is not None and not os.path.exists(self.output_dir):
53 | os.mkdir(self.output_dir)
54 | ex = Executer(self.config)
55 | for path, _, files in os.walk(self.search_dir):
56 | for filename in files:
57 | if filename.endswith(self.config.run_extension):
58 | continue
59 | filepath = os.path.join( path, filename )
60 | command = self.config.get_command_line(self.binary_to_use, filepath)
61 | Logger.debug("Executing:", command, debug_level=4)
62 | Logger.busy()
63 | signal = ex.run_command(command, env=self.config.env)
64 | while confirmation_loops > 0:
65 | Logger.busy()
66 | new_signal = ex.run_command(command, env=self.config.env)
67 | if new_signal == signal:
68 | signal = new_signal
69 | confirmation_loops -= 1
70 | else:
71 | Logger.info("Detected varying return codes for exactly the same run")
72 | signal = SignalFinder.VARYING_SIGNAL
73 | break
74 | Logger.debug("We consider signal %i for input file %s" % (signal, filename), debug_level=5)
75 | destination_dir = self.get_folder_path_for_signal(signal)
76 | if not os.path.exists(destination_dir):
77 | os.mkdir(destination_dir)
78 | function(filepath, os.path.join(destination_dir, filename))
79 |
80 | def get_folder_path_for_signal(self, signal):
81 | signal_folder_name = str(signal)
82 | return os.path.join(self.output_dir, signal_folder_name)
83 |
84 | def get_folder_paths_for_signals_if_exist(self, ignore_signals):
85 | l = list(set(range(-500,500)) - set(ignore_signals))
86 | l.sort()
87 | for signal in l:
88 | signal_folder = self.get_folder_path_for_signal(signal)
89 | if os.path.exists(signal_folder):
90 | yield signal, signal_folder
91 |
--------------------------------------------------------------------------------
/modules/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/floyd-fuh/afl-crash-analyzer/3a50b5ca5cb7542470dc0240ebb88eccc018a9c4/modules/__init__.py
--------------------------------------------------------------------------------
/testcases/clamav/install.sh:
--------------------------------------------------------------------------------
1 | #COMPILER_C=gcc
2 | #COMPILER_CPP=g++
3 | COMPILER_C=clang
4 | COMPILER_CPP=clang++
5 |
6 | #Note: There are more disc space efficient ways, make sure you have enough disc space
7 |
8 | if [ ! -d ./clamav-plain ]; then
9 | sudo apt-get install git
10 | git clone https://github.com/vrtadmin/clamav-devel clamav-plain
11 | cp -r clamav-plain clamav-afl
12 | cp -r clamav-plain clamav-asan
13 | fi
14 |
15 | echo "[+] Updating clamav-plain"
16 | cd clamav-plain
17 | git pull
18 | cd ..
19 | echo "[+] Updating clamav-afl"
20 | cd clamav-afl
21 | git pull
22 | cd ..
23 | echo "[+] Updating clamav-asan"
24 | cd clamav-asan
25 | git pull
26 | cd ..
27 |
28 | echo "[+] Compiling clamav-plain"
29 | cd clamav-plain
30 | mkdir installed
31 | export CFLAGS="-Wall -g" && export CC=$COMPILER_C && export CXX=$COMPILER_CPP && ./configure --prefix="`pwd`/installed/" && make clean && make && make install
32 | mkdir ./installed/share/clamav
33 | cp ./installed/etc/freshclam.conf.sample ./installed/etc/freshclam.conf
34 | sed -i 's/Example//g' ./installed/etc/freshclam.conf
35 | cp ./installed/etc/clamd.conf.sample ./installed/etc/clamd.conf
36 | sed -i 's/Example//g' ./installed/etc/clamd.conf
37 | ./installed/bin/freshclam
38 | cd ..
39 |
40 | echo "[+] Compiling clamav-afl"
41 | cd clamav-afl
42 | mkdir installed
43 | export CFLAGS="-Wall -g" && export CC=afl-$COMPILER_C && export CXX=afl-$COMPILER_CPP && ./configure --prefix="`pwd`/installed/" && make clean && make && make install
44 | cp ./installed/etc/freshclam.conf.sample ./installed/etc/freshclam.conf
45 | sed -i 's/Example//g' ./installed/etc/freshclam.conf
46 | cp ./installed/etc/clamd.conf.sample ./installed/etc/clamd.conf
47 | sed -i 's/Example//g' ./installed/etc/clamd.conf
48 | ./installed/bin/freshclam
49 | cd ..
50 |
51 | echo "[+] Compiling clamav-asan"
52 | cd clamav-asan
53 | mkdir installed
54 | #We're setting -fstack-protector-all as well
55 | #Attention: had issues with ASAN on ARM:
56 | #/usr/bin/ld.bfd.real: cannot find /usr/bin/../lib/clang/3.4/lib/linux/libclang_rt.asan-arm.a: No such file or directory
57 | #too lazy to debug, didn't build with ASAN on ARM
58 | export CFLAGS="-Wall -g -fstack-protector-all -fsanitize=address -fno-omit-frame-pointer" && export CC=$COMPILER_C && export CXX=$COMPILER_CPP && ./configure --prefix="`pwd`/installed/" && make clean && make && make install
59 | cp ./installed/etc/freshclam.conf.sample ./installed/etc/freshclam.conf
60 | sed -i 's/Example//g' ./installed/etc/freshclam.conf
61 | cp ./installed/etc/clamd.conf.sample ./installed/etc/clamd.conf
62 | sed -i 's/Example//g' ./installed/etc/clamd.conf
63 | ./installed/bin/freshclam
64 | cd ..
65 |
--------------------------------------------------------------------------------
/testcases/ffmpeg/Config.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python2.7
2 | # encoding: utf-8
3 |
4 | from modules.CrashAnalysisConfig import CrashAnalysisConfig
5 |
6 | def create_config(main_dir, *args, **kwargs):
7 |
8 | #TODO: fix so that ASAN version of ffmpeg compiles
9 | config = CrashAnalysisConfig(main_dir,
10 | target_binary_instrumented=main_dir+"/testcases/ffmpeg/ffmpeg-afl/ffmpeg",
11 | args_before=["-i"],
12 | args_after=["-loglevel", "quiet"],
13 | target_binary_plain=main_dir+"/testcases/ffmpeg/ffmpeg-plain/ffmpeg",
14 | # target_binary_asan=main_dir+"/testcases/ffmpeg/ffmpeg-asan/ffmpeg",
15 | crash_dir=main_dir+"/testcases/ffmpeg/crashes",
16 | *args,
17 | **kwargs
18 | )
19 | return config
20 |
--------------------------------------------------------------------------------
/testcases/ffmpeg/install.sh:
--------------------------------------------------------------------------------
1 | #COMPILER_C=gcc
2 | #COMPILER_CPP=g++
3 | COMPILER_C=clang
4 | COMPILER_CPP=clang++
5 |
6 | #Note: There are more disc space efficient ways, make sure you have enough disc space
7 |
8 | if [ ! -d ./ffmpeg-plain ]; then
9 | sudo apt-get install git yasm
10 | git clone git://source.ffmpeg.org/ffmpeg.git ffmpeg-plain
11 | cp -r ffmpeg-plain ffmpeg-afl
12 | cp -r ffmpeg-plain ffmpeg-asan
13 | fi
14 |
15 | #Helps for ARM: https://www.bitpi.co/2015/08/19/how-to-compile-ffmpeg-on-a-raspberry-pi/
16 |
17 | echo "[+] Updating ffmpeg-plain"
18 | cd ffmpeg-plain
19 | git pull
20 | cd ..
21 | echo "[+] Updating ffmpeg-afl"
22 | cd ffmpeg-afl
23 | git pull
24 | cd ..
25 | echo "[+] Updating ffmpeg-asan"
26 | cd ffmpeg-asan
27 | git pull
28 | cd ..
29 |
30 | echo "[+] Compiling ffmpeg-plain"
31 | cd ffmpeg-plain
32 | export CFLAGS="-Wall -g" && export CC=$COMPILER_C && export CXX=$COMPILER_CPP && ./configure --disable-pthreads --disable-ffplay --disable-ffprobe --disable-ffserver --disable-doc --disable-stripping --disable-shared --cc=$COMPILER_C --cxx=$COMPILER_CPP && make clean && make
33 | cd ..
34 |
35 | echo "[+] Compiling ffmpeg-afl"
36 | #On ARM on 23. April 2016 git it worked with:
37 | #export CFLAGS="" && export LDFLAGS="-lpthread" && export CC=afl-clang && export CXX=afl-clang++ && ./configure --disable-pthreads --disable-ffplay --disable-ffprobe --disable-ffserver --disable-doc --disable-shared --cc=afl-clang --cxx=afl-clang++ --disable-asm && make
38 | cd ffmpeg-afl
39 | export CFLAGS="-Wall -g" && export CC=afl-$COMPILER_C && export CXX=afl-$COMPILER_CPP && ./configure --disable-pthreads --disable-ffplay --disable-ffprobe --disable-ffserver --disable-doc --disable-shared --cc=afl-$COMPILER_C --cxx=afl-$COMPILER_CPP && make clean && AFL_INST_RATIO=30 make
40 | cd ..
41 |
42 | echo "[+] Compiling ffmpeg-asan"
43 | cd ffmpeg-asan
44 | #This was a torture to get this running, several issues here:
45 | #On x86 on older versions we had to remove -fstack-protector-all as ffmpeg's configure will complain that the compiler is not able to produce binaries, but seems fixed now
46 | #Then I ran into an issue that is a problem in a lot of programs when you try to use a sanitizer: https://savannah.gnu.org/patch/?8775
47 | #It won't build with ASAN when inline assembly is enabled...
48 | #Additionally the LDFLAGS with lpthread are necessary even when you specify --disable-pthreads... well I guess there is somewhere an unconditional import
49 | #Additionally (separate issue): had issues with ASAN on ARM:
50 | #/usr/bin/ld.bfd.real: cannot find /usr/bin/../lib/clang/3.4/lib/linux/libclang_rt.asan-arm.a: No such file or directory
51 | #too lazy to debug, didn't build with ASAN on ARM
52 | export LDFLAGS="-lpthread -fsanitize=address" export CFLAGS="-Wall -g -fsanitize=address -fno-omit-frame-pointer -fstack-protector-all" && export CC=$COMPILER_C && export CXX=$COMPILER_CPP && ./configure --disable-pthreads --disable-ffplay --disable-ffprobe --disable-ffserver --disable-doc --disable-stripping --disable-shared --cc=$COMPILER_C --cxx=$COMPILER_CPP --disable-inline-asm && make clean && make
53 | cd ..
54 |
55 |
--------------------------------------------------------------------------------
/testcases/gm/Config.py:
--------------------------------------------------------------------------------
1 | #!/usr/local/bin/python2.7
2 | # encoding: utf-8
3 |
4 | from modules.CrashAnalysisConfig import CrashAnalysisConfig
5 |
6 | def create_config(main_dir, *args, **kwargs):
7 | config = CrashAnalysisConfig(main_dir,
8 | target_binary_instrumented=main_dir+"/testcases/gm/graphicsmagick-afl/utilities/gm",
9 | args_before=["identify"],
10 | args_after=[],
11 | target_binary_plain=main_dir+"/testcases/gm/graphicsmagick-plain/utilities/gm",
12 | target_binary_asan=main_dir+"/testcases/gm/graphicsmagick-asan/utilities/gm",
13 | #just takes too long if we do all, so we only go through the "new" folder
14 | crash_dir=main_dir+"/testcases/gm/crashes/new",
15 | *args,
16 | **kwargs
17 | )
18 | return config
19 |
--------------------------------------------------------------------------------
/testcases/gm/install.sh:
--------------------------------------------------------------------------------
1 | #COMPILER_C=gcc
2 | #COMPILER_CPP=g++
3 | COMPILER_C=clang
4 | COMPILER_CPP=clang++
5 |
6 | #Note: There are more disc space efficient ways, make sure you have enough disc space
7 |
8 | if [ ! -d ./graphicsmagick-plain ]; then
9 | sudo apt-get install mercurial clang-3.5
10 | sudo apt-get install libpng-dev libpng12-dev libtiff5-dev
11 | hg clone http://hg.code.sf.net/p/graphicsmagick/code graphicsmagick-plain
12 | cp -r graphicsmagick-plain graphicsmagick-afl
13 | cp -r graphicsmagick-plain graphicsmagick-asan
14 | fi
15 |
16 | echo "[+] Updating graphicsmagick-plain"
17 | cd graphicsmagick-plain
18 | hg pull
19 | hg update
20 | cd ..
21 | echo "[+] Updating graphicsmagick-afl"
22 | cd graphicsmagick-afl
23 | hg pull
24 | hg update
25 | cd ..
26 | echo "[+] Updating graphicsmagick-asan"
27 | cd graphicsmagick-asan
28 | hg pull
29 | hg update
30 | cd ..
31 |
32 | echo "[+] Compiling graphicsmagick-plain"
33 | cd graphicsmagick-plain
34 | export CFLAGS="-Wall -g -O0" && export CC=$COMPILER_C && export CXX=$COMPILER_CPP && ./configure --disable-shared && make clean && make
35 | cd ..
36 |
37 | echo "[+] Compiling graphicsmagick-afl"
38 | cd graphicsmagick-afl
39 | export CFLAGS="-Wall -g" && export CC=afl-$COMPILER_C && export CXX=afl-$COMPILER_CPP && ./configure --disable-shared && make clean && make
40 | cd ..
41 |
42 | echo "[+] Compiling graphicsmagick-asan"
43 | cd graphicsmagick-asan
44 | #We're setting -fstack-protector-all as well
45 | #Attention: had issues with ASAN on ARM: checking whether the C compiler works... no
46 | #too lazy to debug, didn't build with ASAN on ARM
47 | export CFLAGS="-Wall -g -fstack-protector-all -fsanitize=address -fno-omit-frame-pointer" && export CC=$COMPILER_C && export CXX=$COMPILER_CPP && ./configure --disable-shared && make clean && make
48 | cd ..
49 |
50 | if [ -d ./graphicsmagick-afl-outchangeabort ]; then
51 | #A version of graphicsmagick that will abort when the output filename is not "tmpOutputFilename"
52 | #cd graphicsmagick-afl
53 | #export CFLAGS="-Wall -g" && export CC=afl-$COMPILER_C && export CXX=afl-$COMPILER_CPP && ./configure --disable-shared && make clean && make
54 | #cd ..
55 | echo 123
56 | fi
57 |
58 |
59 |
--------------------------------------------------------------------------------
/utilities/Executer.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 | '''
3 | AFL crash analyzer, crash triage for the American Fuzzy Lop fuzzer
4 | Copyright (C) 2015 floyd
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | Created on Apr 13, 2015
20 | @author: floyd, http://floyd.ch, @floyd_ch
21 | '''
22 | import subprocess
23 | import signal
24 | import multiprocessing
25 | import Queue
26 | from utilities.Logger import Logger
27 |
28 | class Executer:
29 | #TODO: more jailing of processes, so that they don't go rampage and use up all memory and such things (especially on OSX)
30 | #What we are doing here: http://stackoverflow.com/questions/4033578/how-to-limit-programs-execution-time-when-using-subprocess
31 | #We send a timeout as SIGALRM and when it is reached we simply kill the process.
32 | def __init__(self, config):
33 | self.TIMEOUT_SIGNAL = 9998
34 | self.config = config
35 | self.current_process = None
36 | self.timeout_flag = False
37 | self.sigttou_flag = False
38 |
39 | def _handle_alarm(self, signum, frame):
40 | # If the alarm is triggered, we're still in the communicate()
41 | # call, so use kill() to end the process
42 | self.timeout_flag = True
43 | try:
44 | self.current_process.kill()
45 | except OSError as ose:
46 | Logger.info("Kill failed. Sometimes the process exactly exits before we try to kill it... coward. Nothing to worry about.", ose)
47 |
48 | def _handle_sigttou(self, signum, frame):
49 | #Had some issues that when memory corruptions occured in a subprocess
50 | #(no matter if shielded by multiprocess and subprocess module),
51 | #that a SIGTTOU was sent to the entire Python main process.
52 | #According to https://en.wikipedia.org/wiki/SIGTTOU this
53 | #results in the process being stopped (and it looks like SIGSTP on the cmd):
54 | #[1]+ Stopped ./AflCrashAnalyzer.py
55 | #Of course we don't want that. Debugging was hard but then
56 | #realized after this program was stopped:
57 | #$ echo $?
58 | #150
59 | #So that's SIGTTOU on Linux at least.
60 | #This handler will prevent the process to stop.
61 | self.sigttou_flag = True
62 | try:
63 | self.current_process.kill()
64 | except OSError as ose:
65 | Logger.info("Kill failed. Sometimes the process exactly exits before we try to kill it... coward. Nothing to worry about.", ose)
66 |
67 |
68 | def run_command(self, command, timeout=None, env={}, stdout=file("/dev/null"), stderr=file("/dev/null")):
69 | #TODO: make stdout / stderr configurable
70 | if not timeout:
71 | timeout = self.config.run_timeout
72 | process = subprocess.Popen(command, stdin=None, shell=False, stdout=stdout, stderr=stderr)
73 | self.current_process = process
74 | signal.signal(signal.SIGALRM, self._handle_alarm)
75 | #We also had a problem that memory corruptions...
76 | signal.signal(signal.SIGTTOU, self._handle_sigttou)
77 | signal.alarm(timeout)
78 | self.timeout_flag = False
79 | self.sigttou_flag = False
80 | #TODO: get rid of magic number
81 | ret_signal = self.TIMEOUT_SIGNAL
82 | #blocking call:
83 | process.communicate()
84 | signal.alarm(0)
85 | #This line is reached when timeout_flag was set by _handle_alarm if it was called
86 | if self.timeout_flag:
87 | Logger.debug("Process was killed as it exceeded the time limit", debug_level=3)
88 | ret_signal = self.TIMEOUT_SIGNAL
89 | elif self.sigttou_flag:
90 | Logger.debug("Some memory corruption resulted in a SIGTTOU signal being thrown (usually stops process). We caught it.", debug_level=3)
91 | ret_signal = signal.SIGTTOU
92 | else:
93 | ret_signal = process.returncode
94 | return ret_signal
95 |
--------------------------------------------------------------------------------
/utilities/Logger.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 | '''
3 | AFL crash analyzer, crash triage for the American Fuzzy Lop fuzzer
4 | Copyright (C) 2015 floyd
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | Created on Apr 13, 2015
20 | @author: floyd, http://floyd.ch, @floyd_ch
21 | '''
22 | import sys
23 | class Logger():
24 | #TODO: use curses, use colors, etc.
25 | #min 0, max 10 (only used up to 6 atm)
26 | debug_level = 6
27 | #This is the setting if you want the dots to be printed so you see the program is busy
28 | busy_inform = debug_level <= 3 and False
29 | @staticmethod
30 | def setDebug(level):
31 | Logger.debug_level = level
32 | @staticmethod
33 | def error(*text):
34 | print "[-] Error: "+str(" ".join(str(i) for i in text))
35 | @staticmethod
36 | def warning(*text):
37 | print " [-] Warning: "+str(" ".join(str(i) for i in text))
38 | @staticmethod
39 | def fatal(*text):
40 | print "[-] Fatal Error: "+str(" ".join(str(i) for i in text))
41 | exit()
42 | @staticmethod
43 | def info(*text):
44 | print "[+] "+str(" ".join(str(i) for i in text))
45 | @staticmethod
46 | def debug(*text, **kwargs):
47 | level = 2
48 | if "debug_level" in kwargs:
49 | level = kwargs["debug_level"]
50 | if level <= Logger.debug_level:
51 | print " ["+"+"*level+"] "+str(" ".join(str(i) for i in text))
52 | @staticmethod
53 | def busy():
54 | if Logger.busy_inform:
55 | sys.stdout.write(".")
56 | sys.stdout.flush()
--------------------------------------------------------------------------------
/utilities/OutputUtility.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 | '''
3 | AFL crash analyzer, crash triage for the American Fuzzy Lop fuzzer
4 | Copyright (C) 2015 floyd
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | Created on Apr 13, 2015
20 | @author: floyd, http://floyd.ch, @floyd_ch
21 | '''
22 | import os
23 | def get_new_output_file_name(path, filename, extension, max_digets):
24 | new_filename = filename
25 | i = 1
26 | while os.path.exists(os.path.join(path, new_filename+extension)) and i < 10**max_digets:
27 | formatstr = "%0"+str(max_digets)+"d"
28 | new_number = formatstr % i
29 | new_filename = filename + new_number
30 | i += 1
31 | return new_filename + extension
32 |
33 | def list_as_intervals(li, as_hex=False):
34 | li = list(set(li))
35 | if len(li) == 1:
36 | return str(li[0])
37 | elif len(li) == 0:
38 | return ""
39 | li.sort()
40 | out = []
41 | last = li[0]
42 | start = last
43 | for x in li[1:]:
44 | if not x - last <= 1:
45 | if start == last:
46 | out.append(hex(start) if as_hex else str(start))
47 | else:
48 | val = hex(start) if as_hex else str(start)
49 | val2 = hex(last) if as_hex else str(last)
50 | out.append(val+"-"+str(val2))
51 | start = x
52 | last = x
53 | if start == last:
54 | out.append(hex(start) if as_hex else str(start))
55 | else:
56 | val = hex(start) if as_hex else str(start)
57 | val2 = hex(last) if as_hex else str(last)
58 | out.append(val+"-"+str(val2))
59 | return ", ".join(out)
--------------------------------------------------------------------------------
/utilities/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/floyd-fuh/afl-crash-analyzer/3a50b5ca5cb7542470dc0240ebb88eccc018a9c4/utilities/__init__.py
--------------------------------------------------------------------------------