pax_global_header 0000666 0000000 0000000 00000000064 12544406306 0014516 g ustar 00root root 0000000 0000000 52 comment=5d9dc9d3ae145ecb596a8571cfadc0d5896336c0
afl-cov-0.3/ 0000775 0000000 0000000 00000000000 12544406306 0012707 5 ustar 00root root 0000000 0000000 afl-cov-0.3/COPYING 0000777 0000000 0000000 00000000000 12544406306 0014742 2LICENSE ustar 00root root 0000000 0000000 afl-cov-0.3/CREDITS 0000664 0000000 0000000 00000000226 12544406306 0013727 0 ustar 00root root 0000000 0000000
Michal Zalewski
- Made the original suggestion of sending afl-fuzz test cases back through
a project with gcov profiling support built-in.
afl-cov-0.3/ChangeLog 0000664 0000000 0000000 00000004331 12544406306 0014462 0 ustar 00root root 0000000 0000000 afl-cov-0.3 (06/29/2015):
- Add --background mode to facilitate clean integration with afl-fuzz
wrapper scripts. In this mode, afl-cov will wait for afl-fuzz to start,
produce coverage results while afl-fuzz is running, and then exit
automatically when finished. Here is an example of a wrapper script from
the fwknop project that combines afl-cov in --background mode with
afl-fuzz:
https://github.com/mrash/fwknop/blob/master/test/afl/fuzzing-wrappers/client-rc.sh
- Add fuzzing-dir/cov/afl-cov.log file to track verbose run time
information.
- Add fuzzing-dir/cov/afl-cov-status file to track the current PID, argv,
and afl-cov version.
afl-cov-0.2 (05/28/2015):
- Add the fuzzing-dir/cov/id-delta-cov file which lists all functions and
(and optionally lines) that are executed by the first "id:000000*" test
case, and then lists all new functions/lines executed in subsequent test
cases. In --func-search or --line-search modes, the id-delta-cov file is
parsed directly instead of parsing cov/diff/ file output. Here is an
example of what the contents of this file looks like:
# id:NNNNNN*_file, cycle, src_file, coverage_type, fcn/line
id:000000,orig:access.conf, 0, proj/log_msg.c, function, free_logging()
id:000000,orig:access.conf, 0, proj/log_msg.c, function, init_logging()
id:000000,orig:access.conf, 0, proj/log_msg.c, function, log_msg()
- Replace the fuzzing-dir/cov/zero-cov/ directory with a single file
at the same path fuzzing-dir/cov/zero-cov that lists all
functions/lines that are never executed by any AFL test case.
- Add the fuzzing-dir/cov/pos-cov file that lists all functions/lines
that are executed at least once by an AFL test case.
- Use the 'fuzzer_stats' file for acquiring the afl-fuzz PID in --live
mode. This closes issue #4 on github.
- Default to not preserving all lcov files - just keep the final one that
contains all cumulative coverage results. This behavior can be changed
with the --preserve-all-lcov-files argument.
- Track and display the AFL cycle number for each queue/id:NNNNNN* file.
afl-cov-0.1 (05/09/2015):
- Initial release
afl-cov-0.3/LICENSE 0000664 0000000 0000000 00000043177 12544406306 0013730 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
afl-cov-0.3/README 0000777 0000000 0000000 00000000000 12544406306 0015041 2README.md ustar 00root root 0000000 0000000 afl-cov-0.3/README.md 0000664 0000000 0000000 00000036010 12544406306 0014166 0 ustar 00root root 0000000 0000000 # afl-cov - AFL Fuzzing Code Coverage
## Introduction
`afl-cov` uses test case files produced by the AFL fuzzer (see:
[http://lcamtuf.coredump.cx/afl/](http://lcamtuf.coredump.cx/afl/) to produce
gcov code coverage results of the targeted binary. Code coverage is
interpreted from one case to the next by `afl-cov` in order to determine which
new functions and lines are hit by AFL with each new test case. Further,
`afl-cov` allows for specific lines or functions to be searched for within
coverage results, and when a match is found the corresponding test case file is
displayed. This allows the user to discover which AFL test case is the first to
exercise a particular function. In addition, `afl-cov` produces a "zero
coverage" report of functions and lines that were never executed during an AFL
fuzzing run.
Although of no use to AFL itself, the main application of `afl-cov` is to wrap
some automation around gcov and thereby provide data on how to maximize code
coverage with AFL fuzzing runs. Manual interpretation of cumulative gcov
results from AFL test cases is usually still required, but the "fiddly" steps
of iterating over all test cases and generating code coverage reports (along
with the "zero coverage" report) is automated by `afl-cov`.
Producing code coverage data for AFL test cases is an important step to try
and maximize code coverage, and thereby help to maximize the effectiveness of
AFL. For example, some binaries have code that is reachable only after a
complicated (or even cryptographic) test is passed, and AFL may not be able to
exercise this code without taking special measures. These measures commonly
include patching the project code to bypass such tests. (For example, there is
a patch to solve this problem for a CRC test in libpng included in the AFL
sources at `experimental/libpng_no_checksum/libpng-nocrc.patch`.)
When a project implements a patch to assist AFL in reaching code that would
otherwise be inaccessible, a natural question to ask is whether the patch is
effective. Code coverage results can help to verify this.
## Prerequisites
`afl-cov` requires the following software:
* afl-fuzz
* python
* gcov, lcov, genhtml
Note that `afl-cov` can parse files created by `afl-fuzz` from a different
system, so technically `afl-fuzz` does not need to be installed on the same
system as `afl-cov`. This supports scenarios where fuzzing output is collected,
say, within a git repository on one system, and coverage results are produced
on a different system. However, most workflows typically focus on producing
`afl-cov` results quickly for current fuzzing runs on the same system.
## Workflow
At a high level, the general workflow for `afl-cov` is:
1. Create a spare copy of the project sources compiled with gcov profiling support.
2. Run `afl-cov` while `afl-fuzz` is building test cases.
3. Review the cumulative code coverage results in the final web report.
Now, in more detail:
* Copy the project sources to two different directories
`/path/to/afl-fuzz-output/` and `/path/to/project-gcov/`. The first
will contain the project binaries compiled for AFL fuzzing, and the second will
contain the project binaries compiled for gcov profiling support
(gcc `-fprofile-arcs -ftest-coverage`).
* Start up `afl-cov` in `--live` mode before also starting the `afl-fuzz`
fuzzing cycle. The command line arguments to `afl-cov` must specify the path to
the output directory used by `afl-fuzz`, and the command to execute along with
associated arguments. This command and arguments should closely resemble the
manner in which `afl-fuzz` executes the targeted binary during the fuzzing
cycle. Note that if there is already an existing directory of AFL fuzzing
results, then just omit the `--live` argument to process these results. Here
is an example:
```bash
$ cd /path/to/project-gcov/
$ afl-cov -d /path/to/afl-fuzz-output/ --live --coverage-cmd \
"cat AFL_FILE | LD_LIBRARY_PATH=./lib/.libs ./bin/.libs/somebin -a -b -c" \
--code-dir .
```
Note the `AFL_FILE` string above refers to the test case file that AFL will
build in the `queue/` directory under `/path/to/project-fuzz`. Just leave this
string as-is - `afl-cov` will automatically substitute it with each AFL
`queue/id:NNNNNN*` in succession as is builds the code coverage reports.
Also, in the above command, this handles the case where the AFL fuzzing cycle
is fuzzing the targeted binary via stdin. This explains the
`cat AFL_FILE | ... ./bin/.lib/somebin ...` invocation. For the other style of
fuzzing with AFL where a file is read from the filesystem, here is an example:
```bash
$ cd /path/to/project-gcov/
$ afl-cov -d /path/to/afl-fuzz-output/ --live --coverage-cmd \
"LD_LIBRARY_PATH=./lib/.libs ./bin/.libs/somebin -f AFL_FILE -a -b -c" \
--code-dir .
```
* With `afl-cov` running, open a separate terminal/shell, and launch
`afl-fuzz`:
```bash
$ cd /path/to/project-fuzzing/
$ LD_LIBRARY_PATH=./lib/.libs afl-fuzz -T somebin -t 1000 -i ./test-cases/ \
-o /path/to/afl-fuzz-output/ ./bin/.libs/somebin -a -b -c
```
The familiar AFL status screen will be displayed, and `afl-cov` will start
generating code coverage data.
![alt text][AFL-status-screen]
[AFL-status-screen]: /doc/AFL_status_screen.png "AFL Fuzzing Cycle"
Here is a sample of what the `afl-cov` output looks like:
```bash
$ afl-cov -d /path/to/afl-fuzz-output/ --live --coverage-cmd \
"LD_LIBRARY_PATH=./lib/.libs ./bin/.libs/somebin -f AFL_FILE -a -b -c" --code-dir .
[+] Imported 184 files from: /path/to/afl-fuzz-output/queue
[+] AFL file: id:000000,orig:somestr.start (1 / 184), cycle: 0
lines......: 18.6% (1122 of 6032 lines)
functions..: 30.7% (100 of 326 functions)
branches...: 14.0% (570 of 4065 branches)
[+] AFL file: id:000001,orig:somestr256.start (2 / 184), cycle: 2
lines......: 18.7% (1127 of 6032 lines)
functions..: 30.7% (100 of 326 functions)
branches...: 14.1% (572 of 4065 branches)
[+] Coverage diff id:000000,orig:somestr.start id:000001,orig:somestr256.start
Src file: /path/to/project-gcov/lib/proj_decode.c
New 'line' coverage: 140
New 'line' coverage: 141
New 'line' coverage: 142
Src file: /path/to/project-gcov/lib/proj_util.c
New 'line' coverage: 217
New 'line' coverage: 218
[+] AFL file: id:000002,orig:somestr384.start (3 / 184), cycle: 10
lines......: 18.8% (1132 of 6032 lines)
functions..: 30.7% (100 of 326 functions)
branches...: 14.1% (574 of 4065 branches)
[+] Coverage diff id:000001,orig:somestr256.start id:000002,orig:somestr384.start
Src file: /path/to/project-gcov/lib/proj_decode.c
New 'line' coverage: 145
New 'line' coverage: 146
New 'line' coverage: 147
Src file: /path/to/project-gcov/lib/proj_util.c
New 'line' coverage: 220
New 'line' coverage: 221
[+] AFL file: id:000003,orig:somestr.start (4 / 184), cycle: 5
lines......: 18.9% (1141 of 6032 lines)
functions..: 31.0% (101 of 326 functions)
branches...: 14.3% (581 of 4065 branches)
[+] Coverage diff id:000002,orig:somestr384.start id:000003,orig:somestr.start
Src file: /path/to/project-gcov/lib/proj_message.c
New 'function' coverage: validate_cmd_msg()
New 'line' coverage: 244
New 'line' coverage: 247
New 'line' coverage: 248
New 'line' coverage: 250
New 'line' coverage: 255
New 'line' coverage: 262
New 'line' coverage: 263
New 'line' coverage: 266
.
.
.
[+] Coverage diff id:000182,src:000000,op:havoc,rep:64 id:000184,src:000000,op:havoc,rep:4
[+] Processed 184 / 184 files
[+] Final zero coverage report: /path/to/afl-fuzz-output/cov/zero-cov
[+] Final positive coverage report: /path/to/afl-fuzz-output/cov/pos-cov
[+] Final lcov web report: /path/to/afl-fuzz-output/cov/web/lcov-web-final.html
```
In the last few lines above, the locations of the final web coverage and zero
coverage reports are shown. The zero coverage reports contains function names
that were never executed across the entire `afl-fuzz` run.
The code coverage results in `/path/to/afl-fuzz-output/cov/web/lcov-web-final`
represent cumulative code coverage across all AFL test cases. This data can then
be reviewed to ensure that all expected functions are indeed exercised by AFL -
just point a web browser at `/path/to/afl-fuzz-output/cov/web/lcov-web-final.html`.
Below is a sample of what this report looks like for a cumulative AFL fuzzing
run - this is against the fwknop project, and the full report is
[available here](https://www.cipherdyne.org/fwknop/2.6.7-afl-lcov-results/).
Note that even though fwknop has a dedicated set of
[AFL wrappers](https://github.com/mrash/fwknop/tree/master/test/afl), it is still
difficult to achieve high percentages of code coverage. This provides evidence
that measuring code coverage under AFL fuzzing runs is an important aspect of
trying to achieve maximal fuzzing results. Every branch/line/function that is
not exercised by AFL represents a location for which AFL has not been given the
opportunity to find bugs.
![alt text][AFL-lcov-web-report]
[AFL-lcov-web-report]: /doc/AFL_lcov_web_report.png "AFL lcov web report"
### Other Examples
The workflow above is probably the main strategy for using `afl-cov`. However,
additional use cases are supported such as:
1. Suppose there are a set of wrapper scripts around `afl-fuzz` to run fuzzing
cycles against various aspects of a project. By building a set of corresponding
`afl-cov` wrappers, and then using the `--disable-coverage-init` option on all
but the first of these wrappers, it is possible to generate code coverage results
across the entire set of `afl-fuzz` fuzzing runs. (By default, `afl-cov` resets
gcov counters to zero at start time, but the `--disable-coverage-init` stops this
behavior.) The end result is a global picture of code coverage across all
invocations of `afl-fuzz`.
2. Specific functions can be searched for in the code coverage results, and
`afl-cov` will return the first `afl-fuzz` test case where a given function is
executed. This allows `afl-cov` to be used as a validation tool by other scripts
and testing infrastructure. For example, a test case could be written around
whether an important function is executed by `afl-fuzz` to validate a patching
strategy mentioned in the introduction.
Here is an example where the first test case that executes the function
`validate_cmd_msg()` is returned (this is after all `afl-cov` results have been
produced in the main workflow above):
```bash
$ ./afl-cov -d /path/to/afl-fuzz-output --func-search "validate_cmd_msg"
[+] Function 'validate_cmd_mag()' executed by: id:000002,orig:somestr384.start
```
An equivalent way of searching the coverage results is to just `grep` the function
from the `cov/id-delta-cov` file described below. Note the number _"3"_ in the output
below is the AFL cycle number where the function is first executed:
```bash
$ grep validate_cmd_msg /path/to/afl-fuzz-output/cov/id-delta-cov
id:000002,orig:somestr384.start, 3, /path/to/project-gcov/file.c, function, validate_cmd_msg()
```
## Directory / File Structure
`afl-cov` creates a few files and directories for coverage results within the
specified `afl-fuzz` directory (`-d`). These files and directories are
displayed below, and all are contained within the main
`/path/to/afl-fuzz-output/cov/` directory:
* `cov/diff/` - contains new code coverage results when `queue/id:NNNNNN*` file
causes `afl-fuzz` to execute new code.
* `cov/lcov/` - contains raw code coverage data produced by the lcov front-end to gcov.
* `cov/web/` - contains code coverage results in web format produced by `genhtml`.
* `cov/zero-cov` - file that lists all functions (and optionally lines) that are never
executed by any `afl-fuzz` test case.
* `cov/pos-cov` - file that lists all functions (and optionally lines) that are
executed at least once by an `afl-fuzz` test case.
* `cov/id-delta-cov` - lists the functions (and optionally lines) that are executed by
the first `id:000000*` test case, and then lists all new
functions/lines executed in subsequent test cases.
## Usage Information
Basic `--help` output appears below:
usage: afl-cov [-h] [-e COVERAGE_CMD] [-d AFL_FUZZING_DIR] [-c CODE_DIR] [-O]
[--disable-cmd-redirection] [--disable-lcov-web]
[--disable-coverage-init] [--coverage-include-lines] [--live]
[--sleep SLEEP] [--lcov-web-all] [--func-search FUNC_SEARCH]
[--line-search LINE_SEARCH] [--src-file SRC_FILE]
[--afl-queue-id-limit AFL_QUEUE_ID_LIMIT] [-v] [-V] [-q]
optional arguments:
-h, --help show this help message and exit
-e COVERAGE_CMD, --coverage-cmd COVERAGE_CMD
set command to exec (including args, and assumes code
coverage support)
-d AFL_FUZZING_DIR, --afl-fuzzing-dir AFL_FUZZING_DIR
top level AFL fuzzing directory
-c CODE_DIR, --code-dir CODE_DIR
directory where the code lives (compiled with code
coverage support)
-O, --overwrite overwrite existing coverage results
--disable-cmd-redirection
disable redirection of command results to /dev/null
--disable-lcov-web disable generation of all lcov web code coverage
reports
--disable-coverage-init
disable initialization of code coverage counters at
afl-cov startup
--coverage-include-lines
include lines in zero-coverage status files
--live process a live AFL directory, and afl-cov will exit
when it appears afl-fuzz has been stopped
--sleep SLEEP In --live mode, # of seconds to sleep between checking
for new queue files
--lcov-web-all generate lcov web reports for all id:NNNNNN* files
instead of just the last one
--func-search FUNC_SEARCH
search for coverage of a specific function
--line-search LINE_SEARCH
search for coverage of a specific line number
(requires --src-file)
--src-file SRC_FILE restrict function or line search to a specific source
file
--afl-queue-id-limit AFL_QUEUE_ID_LIMIT
limit the number of id:NNNNNN* files processed in the
AFL queue/ directory
-v, --verbose verbose mode
-V, --version print version and exit
-q, --quiet quiet mode
## License
`afl-cov` is released as open source software under the terms of
the **GNU General Public License (GPL v2)**. The latest release can be found
at [https://github.com/mrash/afl-cov/releases](https://github.com/mrash/afl-cov/releases)
## Contact
All feature requests and bug fixes are managed through github issues tracking.
However, you can email me (michael.rash_AT_gmail.com), or reach me through
Twitter ([@michaelrash](https://twitter.com/michaelrash)).
afl-cov-0.3/VERSION 0000664 0000000 0000000 00000000004 12544406306 0013751 0 ustar 00root root 0000000 0000000 0.3
afl-cov-0.3/afl-cov 0000775 0000000 0000000 00000061445 12544406306 0014176 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
#
# File: afl-cov
#
# Version: 0.3
#
# Purpose: Perform lcov coverage diff's against each AFL queue file to see
# new functions and line coverage evolve from an AFL fuzzing cycle.
#
# Copyright (C) 2015 Michael Rash (mbr@cipherdyne.org)
#
# License (GNU General Public License):
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#
from shutil import rmtree
from sys import argv
import errno
import re
import subprocess
import glob
import string
import argparse
import time
import sys, os
__version__ = '0.3'
WANT_OUTPUT = 1
NO_OUTPUT = 0
def main():
exit_success = 0
exit_failure = 1
cargs = handle_cmdline()
if cargs.version:
print "afl-cov-" + __version__
return exit_success
(gpaths, rv) = get_paths(cargs)
if not rv:
return exit_failure
if not validate_args(gpaths, cargs):
return exit_failure
if cargs.background:
run_in_background()
init_dir(gpaths, cargs)
write_status(cargs)
return not process_afl_test_cases(gpaths, cargs)
def run_in_background():
### could use the python 'daemon' module, but it isn't always
### installed, and we just need a basic backgrounding
### capability anyway
pid = os.fork()
if (pid < 0):
print "[*] fork() error, exiting."
os._exit()
elif (pid > 0):
os._exit(0)
else:
os.setsid()
return
def process_afl_test_cases(gpaths, cargs):
found = 0
afl_files = []
prev_file = ''
cov_paths = {}
gcov = {}
zero_cov = {}
file_num = 0
rv = 1
while True:
new_files = []
tmp_files = import_dir(cargs.afl_fuzzing_dir + '/queue')
for f in tmp_files:
if f not in afl_files:
afl_files.append(f)
new_files.append(f)
if cargs.live:
if is_afl_fuzz_running(cargs):
if not len(new_files):
logr("[-] No new AFL test cases, sleeping for %d seconds" \
% cargs.sleep, cargs)
time.sleep(cargs.sleep)
continue
else:
logr("[+] afl-fuzz appears to be stopped...", cargs)
break
logr("\n*** Imported %d new test cases from: %s\n" \
% (len(new_files), (cargs.afl_fuzzing_dir + '/queue')), cargs)
for f in new_files:
curr_cycle = get_cycle_num(file_num, cargs)
logr("[+] AFL test case: %s (%d / %d), cycle: %d" \
% (os.path.basename(f), file_num, len(afl_files),
curr_cycle), cargs)
cov_paths = gen_paths(prev_file, f, gpaths, cargs)
if cargs.coverage_cmd:
### execute the command to generate code coverage stats
### for the current AFL queue file
run_cmd(cargs.coverage_cmd.replace('AFL_FILE', f), \
cargs, NO_OUTPUT)
### collect the code coverage stats
gen_coverage(gpaths, cov_paths, f, cargs)
### extract and write out the coverage result for this
### id:NNNNNN* test case
append_id_delta_cov(gcov, curr_cycle, cov_paths, gpaths, cargs)
### diff to the previous code coverage and look for
### new lines/functions
if file_num > 0:
zero_cov = coverage_diff(cov_paths, gpaths, prev_file, f, cargs)
if not cargs.disable_lcov_web and cargs.lcov_web_all:
gen_web_cov_report(gpaths, cov_paths, cargs)
prev_file = f
file_num += 1
if cargs.func_search or cargs.line_search:
if not found:
found = search_cov(gpaths, cargs)
if found and not cargs.live:
break
if cargs.afl_queue_id_limit and file_num > cargs.afl_queue_id_limit:
logr("[+] queue/ id limit of %d reached..." \
% cargs.afl_queue_id_limit, cargs)
break
if not cargs.live:
break
logr("[+] Processed id:%d / %d test cases.\n" \
% (file_num-1, len(afl_files)), cargs)
### write the final zero coverage and positive coverage reports
write_zero_cov(gpaths['zero_cov'], zero_cov, cargs)
write_pos_cov(gpaths['pos_cov'], gcov, cargs)
if not cargs.disable_lcov_web:
gen_web_cov_report(gpaths, cov_paths, cargs)
logr("[+] Final lcov web report: %s" \
% gpaths['web_dir'] + '/lcov-web-final.html', cargs)
os.symlink(cov_paths['lcov_web_dir'] + '/index.html',
gpaths['web_dir'] + '/lcov-web-final.html')
if not found:
if cargs.func_search:
logr("[-] Function '%s' not found..." % cargs.func_search, cargs)
rv = 0
elif cargs.line_search:
logr("[-] Line %s not found..." % cargs.line_search, cargs)
rv = 0
return rv
def coverage_diff(cov_paths, gpaths, a, b, cargs):
(old_zero_cov, old_pos_cov) \
= extract_coverage(cov_paths['prev_lcov_info_final'], cargs)
### with the coverage from the previous lcov results extracted,
### we remove associated files unless instructed to keep them
if not cargs.preserve_all_lcov_files:
rm_prev_cov_files(cov_paths)
(new_zero_cov, new_pos_cov) \
= extract_coverage(cov_paths['lcov_info_final'], cargs)
### diff the two dictionaries
printed_diff_header = 0
for f in old_zero_cov:
printed_file = 0
if f in new_zero_cov:
for ctype in old_zero_cov[f]:
for val in sorted(old_zero_cov[f][ctype]):
if val not in new_zero_cov[f][ctype]:
if not printed_diff_header:
logr("\n Coverage diff %s %s" \
% (os.path.basename(a),
os.path.basename(b)), cargs)
pstr = "diff %s -> %s" % (os.path.basename(a),
os.path.basename(b))
logr(pstr, cargs)
append_file(pstr, cov_paths['diff'])
printed_diff_header = 1
if not printed_file:
pstr = "Src file: " + f
logr(pstr, cargs)
append_file(pstr, cov_paths['diff'])
printed_file = 1
pstr = " New '" + ctype + "' coverage: " + val
logr(pstr, cargs)
append_file(pstr, cov_paths['diff'])
if printed_diff_header:
logr("", cargs)
return new_zero_cov
def write_zero_cov(cpath, zero_cov, cargs):
logr("[+] Final zero coverage report: %s" % cpath, cargs)
cfile = open(cpath, 'w')
cfile.write("# All functions / lines in this file were never executed by any\n")
cfile.write("# AFL test case.\n")
cfile.close()
write_cov(cpath, zero_cov, cargs)
return
def write_pos_cov(cpath, gcov, cargs):
logr("[+] Final positive coverage report: %s" % cpath, cargs)
cfile = open(cpath, 'w')
cfile.write("# All functions / lines in this file were executed by at\n")
cfile.write("# least one AFL test case. See the cov/id-delta-cov file\n")
cfile.write("# for more information.\n")
cfile.close()
write_cov(cpath, gcov, cargs)
return
def write_cov(cpath, cov, cargs):
cfile = open(cpath, 'a')
for f in cov:
cfile.write("File: %s\n" % f)
for ctype in sorted(cov[f]):
if ctype == 'function':
for val in sorted(cov[f][ctype]):
cfile.write(" %s: %s\n" % (ctype, val))
elif ctype == 'line':
if cargs.coverage_include_lines:
for val in sorted(cov[f][ctype], key=int):
cfile.write(" %s: %s\n" % (ctype, val))
cfile.close()
return
def rm_prev_cov_files(cov_paths):
os.remove(cov_paths['prev_lcov_base'])
os.remove(cov_paths['prev_lcov_info'])
os.remove(cov_paths['prev_lcov_info_final'])
return
def write_status(cargs):
f = open(cargs.afl_fuzzing_dir + '/cov/afl-cov-status', 'w')
f.write("afl_cov_pid : %d\n" % os.getpid())
f.write("afl_cov_version : %s\n" % __version__)
f.write("command_line : %s\n" % ' '.join(argv))
f.close()
return
def append_file(pstr, path):
f = open(path, 'a')
f.write("%s\n" % pstr)
f.close()
return
def append_id_delta_cov(gcov, curr_cycle, cov_paths, gpaths, cargs):
pos_cov = extract_coverage(cov_paths['lcov_info_final'], cargs)[1]
cfile = open(gpaths['id_delta_cov'], 'a')
for f in pos_cov:
if f not in gcov:
cov_init(f, gcov)
for ctype in sorted(pos_cov[f]):
if ctype == 'function':
for val in sorted(pos_cov[f][ctype]):
if val not in gcov[f][ctype]:
gcov[f][ctype][val] = ''
cfile.write("%s, %s, %s, %s, %s\n" \
% (cov_paths['id_file'],
curr_cycle, f, ctype, val))
elif ctype == 'line':
if cargs.coverage_include_lines:
for val in sorted(pos_cov[f][ctype], key=int):
if val not in gcov[f][ctype]:
gcov[f][ctype][val] = ''
cfile.write("%s, %s, %s, %s, %s\n" \
% (cov_paths['id_file'],
curr_cycle, f, ctype, val))
cfile.close()
return
def cov_init(cfile, cov):
cov[cfile] = {}
cov[cfile]['function'] = {}
cov[cfile]['line'] = {}
return
def extract_coverage(lcov_file, cargs):
search_rv = 0
zero_cov = {}
pos_cov = {}
### populate old lcov output for functions/lines that were called
### zero times
with open(lcov_file, 'r') as f:
current_file = ''
for line in f:
line = line.strip()
m = re.search('SF:(\S+)', line)
if m and m.group(1):
current_file = m.group(1)
cov_init(current_file, zero_cov)
cov_init(current_file, pos_cov)
continue
if current_file:
m = re.search('^FNDA:(\d+),(\S+)', line)
if m and m.group(2):
fcn = m.group(2) + '()'
if m.group(1) == '0':
### the function was never called
zero_cov[current_file]['function'][fcn] = ''
else:
pos_cov[current_file]['function'][fcn] = ''
continue
### look for lines that were never called
m = re.search('^DA:(\d+),(\d+)', line)
if m and m.group(1):
lnum = m.group(1)
if m.group(2) == '0':
### the line was never executed
zero_cov[current_file]['line'][lnum] = ''
else:
pos_cov[current_file]['line'][lnum] = ''
return zero_cov, pos_cov
def search_cov(gpaths, cargs):
search_rv = 0
with open(gpaths['id_delta_cov'], 'r') as f:
for line in f:
line = line.strip()
### id:NNNNNN*_file, cycle, src_file, cov_type, fcn/line\n")
[id_file, cycle_num, src_file, cov_type, val] = line.split(', ')
if cargs.func_search and cov_type == 'function' and val == cargs.func_search:
if cargs.src_file:
if cargs.src_file == src_file:
logr("[+] Function '%s' in file: '%s' executed by: '%s', cycle: %s" \
% (val, current_file, id_file, cycle_num), cargs)
search_rv = 1
else:
logr("[+] Function '%s' executed by: '%s', cycle: %s" \
% (val, id_file, cycle_num), cargs)
search_rv = 1
if cargs.src_file == src_file \
and cargs.line_search and val == cargs.line_search:
if cargs.src_file == src_file:
logr("[+] Line '%s' in file: '%s' executed by: '%s', cycle: %s" \
% (val, current_file, id_file, cycle_num), cargs)
search_rv = 1
return search_rv
def get_cycle_num(id_num, cargs):
### default cycle
cycle_num = 0
if not os.path.exists(cargs.afl_fuzzing_dir + '/plot_data'):
return cycle_num
with open(cargs.afl_fuzzing_dir + '/plot_data') as f:
for line in f:
### unix_time, cycles_done, cur_path, paths_total, pending_total,...
### 1427742641, 11, 54, 419, 45, 0, 2.70%, 0, 0, 9, 1645.47
vals = line.split(', ')
### test the id number against the current path
if vals[2] == str(id_num):
cycle_num = int(vals[1])
break
return cycle_num
def gen_coverage(gpaths, cov_paths, afl_file, cargs):
run_cmd("lcov --rc lcov_branch_coverage=1" \
+ " --no-checksum --capture --initial" \
+ " --directory " + cargs.code_dir \
+ " --output-file " \
+ cov_paths['lcov_base'], \
cargs, NO_OUTPUT)
run_cmd("lcov --rc lcov_branch_coverage=1" \
+ " --no-checksum --capture --directory " \
+ cargs.code_dir + " --output-file " \
+ cov_paths['lcov_info'], \
cargs, NO_OUTPUT)
run_cmd("lcov --rc lcov_branch_coverage=1" \
+ " --no-checksum -a " + cov_paths['lcov_base'] \
+ " -a " + cov_paths['lcov_info'] \
+ " --output-file " + cov_paths['lcov_info_final'], \
cargs, NO_OUTPUT)
out = run_cmd("lcov --rc lcov_branch_coverage=1" \
+ " --no-checksum -r " + cov_paths['lcov_info'] \
+ " /usr/include/* --output-file " \
+ cov_paths['lcov_info_final'], cargs, WANT_OUTPUT)
for line in out.splitlines():
m = re.search('^\s+(lines\.\..*\:\s.*)', line)
if m and m.group(1):
logr(" " + m.group(1), cargs)
else:
m = re.search('^\s+(functions\.\..*\:\s.*)', line)
if m and m.group(1):
logr(" " + m.group(1), cargs)
else:
m = re.search('^\s+(branches\.\..*\:\s.*)', line)
if m and m.group(1):
logr(" " + m.group(1), cargs)
return
def gen_web_cov_report(gpaths, cov_paths, cargs):
os.mkdir(cov_paths['lcov_web_dir'])
run_cmd("genhtml --branch-coverage --output-directory " \
+ cov_paths['lcov_web_dir'] + " " \
+ cov_paths['lcov_info_final'], \
cargs, NO_OUTPUT)
return
def is_afl_fuzz_running(cargs):
found = 0
with open(cargs.afl_fuzzing_dir + '/fuzzer_stats', 'r') as f:
for line in f:
line = line.strip()
### fuzzer_pid : 13238
m = re.search('fuzzer_pid\s+\:\s+(\d+)', line)
if m and m.group(1):
pid = int(m.group(1))
try:
os.kill(pid, 0)
except OSError as e:
if e.errno == errno.EPERM:
found = 1
else:
found = 1
break
return found
def gen_paths(prev_afl_file, afl_file, gpaths, cargs):
cov_paths = {}
basename = os.path.basename(afl_file)
### coverage diffs from one ID file to the next
cov_paths['diff'] = gpaths['diff_dir'] + '/' + basename
### current id:NNNNNN* test case file
cov_paths['id_file'] = basename
### web files
cov_paths['lcov_web_dir'] = gpaths['web_dir'] + '/' + basename
### raw lcov files
cov_paths['lcov_base'] = gpaths['lcov_dir'] + '/' + basename + '.lcov_base'
cov_paths['lcov_info'] = gpaths['lcov_dir'] + '/' + basename + '.lcov_info'
cov_paths['lcov_info_final'] = gpaths['lcov_dir'] + '/' \
+ basename + '.lcov_info_final'
if prev_afl_file:
cov_paths['prev_lcov_base'] = gpaths['lcov_dir'] + '/' \
+ os.path.basename(prev_afl_file) + '.lcov_base'
cov_paths['prev_lcov_info'] = gpaths['lcov_dir'] + '/' \
+ os.path.basename(prev_afl_file) + '.lcov_info'
cov_paths['prev_lcov_info_final'] = gpaths['lcov_dir'] + \
'/' + os.path.basename(prev_afl_file) + '.lcov_info_final'
return cov_paths
def run_cmd(cmd, cargs, collect):
out = ''
if cargs.verbose:
logr(" CMD: %s" % cmd, cargs)
fh = None
if not cargs.disable_cmd_redirection:
fh = open(os.devnull, 'w')
if collect == WANT_OUTPUT:
out = subprocess.check_output(cmd.split())
else:
subprocess.call(cmd, stdin=None,
stdout=fh, stderr=subprocess.STDOUT, shell=True)
if not cargs.disable_cmd_redirection:
fh.close()
return out
def import_dir(qdir):
return sorted(glob.glob(qdir + "/id:*"))
def get_paths(cargs):
gpaths = {}
if not cargs.afl_fuzzing_dir:
print "[*] Must specify AFL fuzzing dir with --afl-fuzzing-dir or -d"
return gpaths, 0
gpaths['top_dir'] = cargs.afl_fuzzing_dir + '/cov'
gpaths['web_dir'] = gpaths['top_dir'] + '/web'
gpaths['lcov_dir'] = gpaths['top_dir'] + '/lcov'
gpaths['diff_dir'] = gpaths['top_dir'] + '/diff'
### summary coverage results
gpaths['id_delta_cov'] = gpaths['top_dir'] + '/id-delta-cov'
gpaths['zero_cov'] = gpaths['top_dir'] + '/zero-cov'
gpaths['pos_cov'] = gpaths['top_dir'] + '/pos-cov'
return gpaths, 1
def validate_args(gpaths, cargs):
if cargs.coverage_cmd:
if 'AFL_FILE' not in cargs.coverage_cmd:
print "[*] --coverage-cmd must contain AFL_FILE"
return 0
else:
if not cargs.func_search and not cargs.line_search:
print "[*] Must set --coverage-cmd or --func-search/--line-search"
return 0
if cargs.code_dir:
if not os.path.exists(cargs.code_dir):
print "[*] --code-dir path does not exist"
return 0
else:
if not cargs.func_search and not cargs.line_search:
print "[*] Must set --code-dir unless using --func-search " \
"against existing afl-cov directory"
return 0
if cargs.func_search or cargs.line_search:
if cargs.func_search and '()' not in cargs.func_search:
cargs.func_search += '()'
if not cargs.verbose and not cargs.coverage_cmd:
cargs.quiet = 1
if cargs.line_search and not cargs.src_file:
print "[*] Must set --src-file in --line-search mode"
return 0
if not cargs.live and not fuzzing_dir_exists(cargs):
print "[*] It doesn't look like directory '%s' exists" \
% (cargs.afl_fuzzing_dir + '/queue')
return 0
if os.path.exists(gpaths['top_dir']):
if not cargs.overwrite:
if not cargs.func_search and not cargs.line_search:
print "[*] Existing coverage dir found, use --overwrite to " \
"re-calculate coverage"
return 0
return 1
def init_dir(gpaths, cargs):
if cargs.live:
while not fuzzing_dir_exists(cargs):
if not cargs.background:
print "[-] Sleep for %d seconds for AFL fuzzing directory to be created..." \
% cargs.sleep
time.sleep(cargs.sleep)
### if we make it here then afl-fuzz is presumably running
while not is_afl_fuzz_running(cargs):
if not cargs.background:
print "[-] Sleep for %d seconds waiting for afl-fuzz to be started...." \
% cargs.sleep
time.sleep(cargs.sleep)
create_cov_dirs = 0
if os.path.exists(gpaths['top_dir']):
if cargs.overwrite:
rmtree(gpaths['top_dir'])
create_cov_dirs = 1
else:
create_cov_dirs = 1
if create_cov_dirs:
for k in ['top_dir', 'web_dir', 'lcov_dir', 'diff_dir']:
os.mkdir(gpaths[k])
### write coverage results in the following format
cfile = open(gpaths['id_delta_cov'], 'w')
cfile.write("# id:NNNNNN*_file, cycle, src_file, coverage_type, fcn/line\n")
cfile.close()
if not cargs.disable_coverage_init \
and create_cov_dirs and cargs.coverage_cmd:
### reset code coverage counters
run_cmd("lcov --rc lcov_branch_coverage=1 " \
+ "--no-checksum --zerocounters --directory " \
+ cargs.code_dir, cargs, NO_OUTPUT)
return 1
def fuzzing_dir_exists(cargs):
if not os.path.exists(cargs.afl_fuzzing_dir):
return 0
if not os.path.exists(cargs.afl_fuzzing_dir + '/queue'):
return 0
return 1
def logr(pstr, cargs):
if not cargs.background and not cargs.quiet:
print " " + pstr
append_file(pstr, cargs.afl_fuzzing_dir + '/cov/afl-cov.log')
return
def handle_cmdline():
p = argparse.ArgumentParser()
p.add_argument("-e", "--coverage-cmd", type=str,
help="set command to exec (including args, and assumes code coverage support)")
p.add_argument("-d", "--afl-fuzzing-dir", type=str,
help="top level AFL fuzzing directory")
p.add_argument("-c", "--code-dir", type=str,
help="directory where the code lives (compiled with code coverage support)")
p.add_argument("-O", "--overwrite", action='store_true',
help="overwrite existing coverage results", default=False)
p.add_argument("--disable-cmd-redirection", action='store_true',
help="disable redirection of command results to /dev/null",
default=False)
p.add_argument("--disable-lcov-web", action='store_true',
help="disable generation of all lcov web code coverage reports",
default=False)
p.add_argument("--disable-coverage-init", action='store_true',
help="disable initialization of code coverage counters at afl-cov startup",
default=False)
p.add_argument("--coverage-include-lines", action='store_true',
help="include lines in zero-coverage status files",
default=False)
p.add_argument("--live", action='store_true',
help="process a live AFL directory, and afl-cov will exit when it appears afl-fuzz has been stopped",
default=False)
p.add_argument("--sleep", type=int,
help="In --live mode, # of seconds to sleep between checking for new queue files",
default=60)
p.add_argument("--background", action='store_true',
help="background mode - if also in --live mode, will exit when the alf-fuzz process is finished",
default=False)
p.add_argument("--lcov-web-all", action='store_true',
help="generate lcov web reports for all id:NNNNNN* files instead of just the last one",
default=False)
p.add_argument("--preserve-all-lcov-files", action='store_true',
help="Keep all lcov files (not usually necessary)",
default=False)
p.add_argument("--func-search", type=str,
help="search for coverage of a specific function")
p.add_argument("--line-search", type=str,
help="search for coverage of a specific line number (requires --src-file)")
p.add_argument("--src-file", type=str,
help="restrict function or line search to a specfic source file")
p.add_argument("--afl-queue-id-limit", type=int,
help="limit the number of id:NNNNNN* files processed in the AFL queue/ directory",
default=0)
p.add_argument("-v", "--verbose", action='store_true',
help="verbose mode", default=False)
p.add_argument("-V", "--version", action='store_true',
help="print version and exit", default=False)
p.add_argument("-q", "--quiet", action='store_true',
help="quiet mode", default=False)
return p.parse_args()
if __name__ == "__main__":
sys.exit(main())
afl-cov-0.3/doc/ 0000775 0000000 0000000 00000000000 12544406306 0013454 5 ustar 00root root 0000000 0000000 afl-cov-0.3/doc/AFL_lcov_web_report.png 0000664 0000000 0000000 00000466313 12544406306 0020054 0 ustar 00root root 0000000 0000000 PNG
IHDR p P f* iCCPICC Profile HWXS[R -)7Az;FHB ؑEׂVtD ذ7uADEY6T$~{9Νo y[@* F{1?
P,v3""\7g*n. $dN.; l0 B; DJ'K&:b TK
8>3
sx|CNcq xRVV6To1cXXD>\A&kY-Y1ta "9údd1䎴!V#{iQv7` 'bXK!ʈ,ڣaQ,̎ss}p70d4r~fޚ4pAZt'z&Q
ҼlH1g}ߥ"6jVX^%
G^ZtƇqp}|03+rԷX1jmfGJ͏ʃLZq:+(B{/ȋrq`l ^@ T棚18I>@".rA>J Eқ/ O!q7OجqGȉ)?6*їC My!LNcMB7.\!b .>2$6¸]s Lcp) uzoZH/P<\j@c5. A `>XA)X6J
5`?8@+8ˠ/ x!!4!ڈbX#⋄ H"|DG"HR@jߑ)"҉Ez~
P*jdDhth
@}h#z
Dї0Y`#捅cX
&b%X9Vc-__ǺN873 x_W5x#~7A0#8 TlB1pp>{" L W'^DR#\I$)TLDG:A">edk9'{]gagp\2dZdS)FWJ4%RA<Օu*˓],[!{@l'ՔMNQWQPORRh4C-G[E=}YqU5uɽ7)_ _.HKaBQ
CtE+p,ŕ{/*>W")**qv*Vct=7M_JE?KS&*)*+*WnWTQRUURrL1LjA- <'p'P?kՉ\՛jjjk՚SgoU?>0QyDĒ'@5L5"5iԸ1)ܤyZs@塕^V6]M^
ӓɬ`ahtv6>ԣ9k՟_@ `yFq=0W0!8dl10EMLLLff<-f&'UOmN5473`XXZ4Y?9q'̴eyJ*ȪЪꍵ5ۺ
fMk[3[V;vtPevmv_In;*;F8tDprZ9...{]O1kJ+uk-m[;˽c3Ot},^G>x;{/>*V>K26vf ;6p0!hAЙ`jpTpeaHK(.AA?)aTԈUSFZEΏ<E7}W11X鱵|'/KhN$%&N;môvӋߚa4cΌ3gf<6K~k֡$BR\ޤ/pV5k(90ys ۛYr˸R\SRKOsO+Oy*yҷؓ1ِEJ:Wgdke 99rݹHw40J/~Om68HI#8q)9hѶ#XUʱ)Nj(81tRprTYmOǟqfg/;w\/^tx㥦]9rvkך;:Z:tr:u7.y+֝owy~7{/~@xPPa#Gm}ǧ{ٽ/>W[;^L{Rrx/ſ62~uoy=lߵ
E=z~CG5?//_M|`$kdD$G64%7{ %Q/ ;;D@b Be+lS[| xki,*>W ٻ ̑Bg,ks# pHYs % %IR$ iTXtXML:com.adobe.xmp
1648
592
v @ IDATx
|T՝7🕔@X% 4 4 2ll+cku>>n|V6lu]&V
-RؠeBID1QML5>gf23wf$@~'ΝrιsϹ2I(@
P (@
P (@
PĨ) B
P (@
P (@
P (`
(@
P (@
P (@
2pFY8 (@
P (@
P (@
P
P (@
P (@
P (0eP (@
P (@
P (@p(@
P (@
P (@
P(` gUC
P (@
P (@
P a (@
P (@
P (@
PLQV!,(@
P (@
P (@
P` m (@
P (@
P (@
2pFY8 (@
P (@
P (@
P
P (@
P (@
P (0eP (@
P (@
P (@p(@
P (@
P (@
P(` gUC
P (@
P (@
P a (@
P (@
P (@
PL`(+C
PXxc`@ i )@
P (@
Pr). (zgZ#Ų g篻7321)5Q_