diff options
-rw-r--r-- | AUTHORS | 5 | ||||
-rw-r--r-- | LICENSE | 202 | ||||
-rw-r--r-- | Makefile | 35 | ||||
-rw-r--r-- | README.md | 79 | ||||
-rw-r--r-- | afl-dyninst.cpp | 369 | ||||
-rw-r--r-- | libAflDyninst.cpp | 83 |
6 files changed, 772 insertions, 1 deletions
diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..8870664 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,5 @@ +This code was developed as part of a project with the Cisco Talos VULNDEV Team + +Authors: + Aleksandar Nikolic <anikolich@sourcefire.com> + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..7646251 --- /dev/null +++ b/Makefile @@ -0,0 +1,35 @@ +# path to dyninst binaries +DYNINST_ROOT = /usr/local + +# path to afl src +AFL_ROOT = ./afl + +# path to libelf and libdwarf +DEPS_ROOT = /usr/local + +CXX = g++ +CXXFLAGS = -g -Wall -O3 +LIBFLAGS = -fpic -shared + +CC = gcc +CFLAGS = -Wall -pedantic -g -std=gnu99 + + +all: afl-dyninst libAflDyninst.so + +afl-dyninst: afl-dyninst.o + $(CXX) $(CXXFLAGS) -L$(DYNINST_ROOT)/lib \ + -L$(DEPS_ROOT)/lib \ + -o afl-dyninst afl-dyninst.o \ + -lcommon \ + -liberty \ + -ldyninstAPI + +libAflDyninst.so: libAflDyninst.cpp + $(CXX) $(CXXFLAGS) $(LIBFLAGS) -I$(AFL_ROOT) -I$(DEPS_ROOT)/include libAflDyninst.cpp -o libAflDyninst.so + +afl-dyninst.o: afl-dyninst.cpp + $(CXX) $(CXXFLAGS) -I$(DEPS_ROOT)/include -I$(DYNINST_ROOT)/include -c afl-dyninst.cpp + +clean: + rm -f afl-dyninst *.so *.o diff --git a/README.md b/README.md index 18425ac..6f5764a 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,79 @@ -# afl-dyninst American Fuzzy Lop + Dyninst == AFL Fuzzing blackbox binaries + +The tool has two parts. The instrumentation tool and the instrumentation +library. Instrumentation library has an initialization callback and basic +block callback functions which are designed to emulate what AFL is doing +with afl-gcc/afl-g++/afl-as. +Instrumentation tool (afl-dyninst) instruments the supplied binary by +inserting callbacks for each basic block and an initialization +callback either at _init or at specified entry point. + +Usage: ./afl-dyninst -i <binary> -o <binary> -l <library> -e <address> -s <number> + -i: Input binary + -o: Output binary + -l: Library to instrument (repeat for more than one) + -e: Entry point address to patch (required for stripped binaries) + -r: Runtime library to instrument (path to, repeat for more than one) + -s: Number of basic blocks to skip + -v: Verbose output + +Switch -l is used to supply the names of the libraries that should +be instrumented along the binary. Instrumented libraries will be copied +to the current working directory. This option can be repeated as many times +as needed. Depending on the environment, the LD_LIBRARY_PATH should be set +to point to instrumented libraries while fuzzing. + +Switch -e is used to manualy specify the entry point where initialization +callback is to be inserted. For unstipped binaries, afl-dyninst defaults +to using _init of the binary as an entry point. In case of stripped binaries +this option is required and is best set to the address of main which +can easily be determined by disassembling the binary and looking for an +argument to __libc_start_main. + +Switch -s instructs afl-dyninst to skip the first <number> of basic +blocks. Currently, it is used to work around a bug in Dyninst +but doubles as an optimization option, as skipping the basic blocks +of the initialization rutines makes things run faster. If the instrumented +binary is crashing by itself, try skiping a number of blocks. + +Switch -r allows you to specify a path to the library that is loaded +via dlopen() at runtime. Instrumented runtime libraries will be +written to the same location with a ".ins" suffix as not to overwrite +the original ones. Make sure to backup the originals and then rename the +instrumented ones to original name. + +The instrumentation library "libDyninst.so" must be available in the current working +directory as that is where the instrumented binary will be looking for it. + +Compiling: + +1. Edit the Makefile and set DYNINST_ROOT and AFL_ROOT to appropriate paths. +2. make + +Example of running the tool: + +Dyninst requires DYNINSTAPI_RT_LIB environment variable to point to the location +of libdyninstAPI_RT.so. + +$ export DYNINSTAPI_RT_LIB=/usr/local/lib/libdyninstAPI_RT.so +$ ./afl-dyninst -i ./rar -o ./rar_ins -e 0x4034c0 -s 100 +Skipping library: libAflDyninst.so +Instrumenting module: DEFAULT_MODULE +Inserting init callback. +Saving the instrumented binary to ./rar_ins... +All done! Happy fuzzing! + +Here we are instrumenting the rar binary with entrypoint at 0x4034c0 +(manualy found address of main), skipping the first 100 basic blocks +and outputing to rar_ins. + +Running AFL on instrumented binary + +Since AFL checks if the binary has been instrumented by afl-gcc,AFL_SKIP_BIN_CHECK environment +variable needs to be set. No modifications to AFL it self is needed. +$ export AFL_SKIP_BIN_CHECK=1 +Then, AFL can be run as usual: +$ afl-fuzz -i testcases/archives/common/gzip/ -o test_gzip -- ./gzip_ins -d -c + + + diff --git a/afl-dyninst.cpp b/afl-dyninst.cpp new file mode 100644 index 0000000..0ec9bab --- /dev/null +++ b/afl-dyninst.cpp @@ -0,0 +1,369 @@ +#include <cstdlib> +#include <iostream> +#include <vector> +#include <string> +#include <stdlib.h> +#include <sstream> +#include <climits> +using namespace std; + +// Command line parsing +#include <getopt.h> + +// DyninstAPI includes +#include "BPatch.h" +#include "BPatch_binaryEdit.h" +#include "BPatch_flowGraph.h" +#include "BPatch_function.h" +#include "BPatch_point.h" + +using namespace Dyninst; + +//cmd line options +char *originalBinary; +char *instrumentedBinary; +bool verbose = false; +Dyninst::Address entryPoint; +set<string> instrumentLibraries; +set<string> runtimeLibraries; +int bbSkip = 0; +bool skipMainModule = false; + +const char *instLibrary = "./libAflDyninst.so"; + +static const char *OPT_STR = "i:o:l:e:vs:dr:"; +static const char *USAGE = " -i <binary> -o <binary> -l <library> -e <address> -s <number>\n \ + -i: Input binary \n \ + -o: Output binary\n \ + -d: Don't instrument the binary, only supplied libraries\n \ + -l: Linked library to instrument (repeat for more than one)\n \ + -r: Runtime library to instrument (path to, repeat for more than one)\n \ + -e: Entry point address to patch (required for stripped binaries)\n \ + -s: Number of basic blocks to skip\n \ + -v: Verbose output\n"; + +bool parseOptions(int argc, char **argv) +{ + + int c; + while ((c = getopt (argc, argv, OPT_STR)) != -1) { + switch ((char) c) { + case 'e': + entryPoint = strtoul(optarg, NULL, 16);; + break; + case 'i': + originalBinary = optarg; + instrumentLibraries.insert(optarg); + break; + case 'o': + instrumentedBinary = optarg; + break; + case 'l': + instrumentLibraries.insert(optarg); + break; + case 'r': + runtimeLibraries.insert(optarg); + break; + case 's': + bbSkip = atoi(optarg); + break; + case 'd': + skipMainModule = true; + break; + case 'v': + verbose = true; + break; + default: + cerr << "Usage: " << argv[0] << USAGE; + return false; + } + } + + if(originalBinary == NULL) { + cerr << "Input binary is required!"<< endl; + cerr << "Usage: " << argv[0] << USAGE; + return false; + } + + if(instrumentedBinary == NULL) { + cerr << "Output binary is required!" << endl; + cerr << "Usage: " << argv[0] << USAGE; + return false; + } + + if(skipMainModule && instrumentLibraries.empty()) { + cerr << "If using option -d , option -l is required." << endl; + cerr << "Usage: " << argv[0] << USAGE; + return false; + } + + return true; +} + +BPatch_function *findFuncByName (BPatch_image * appImage, char *funcName) +{ + BPatch_Vector < BPatch_function * >funcs; + + if (NULL == appImage->findFunction (funcName, funcs) || !funcs.size () + || NULL == funcs[0]) { + cerr << "Failed to find " << funcName << " function." << endl; + return NULL; + } + + return funcs[0]; +} + +// insert callback to initialization function in the instrumentation library +// either at _init or at manualy specified entry point. +bool insertCallToInit(BPatch_binaryEdit * appBin, BPatch_function * instIncFunc,BPatch_module * module, BPatch_function *funcInit) +{ + + /* Find the instrumentation points */ + vector<BPatch_point *> points; + vector < BPatch_point * >*funcEntry = funcInit->findPoint (BPatch_entry); + + // rar main @ 0x4034c0 + // readpng main @ 0x400e0b + + if (NULL == funcEntry) { + cerr << "Failed to find entry for function. " << endl; + return false; + } + + cout << "Inserting init callback." << endl; + BPatch_Vector < BPatch_snippet * >instArgs; // init has no args + BPatch_funcCallExpr instIncExpr (*instIncFunc, instArgs); + + /* Insert the snippet at function entry */ + BPatchSnippetHandle *handle = + appBin->insertSnippet (instIncExpr, *funcEntry, BPatch_callBefore, + BPatch_lastSnippet); + if (!handle) { + cerr << "Failed to insert init callback." << endl; + return false; + } + return true; +} + +// inserts a callback for each basic block assigning it an instrumentation +// time 16bit random ID just as afl +bool insertBBCallback(BPatch_binaryEdit * appBin, BPatch_function * curFunc, + char *funcName, BPatch_function * instBBIncFunc,int *bbIndex) +{ + + BPatch_flowGraph *appCFG = curFunc->getCFG (); + unsigned short randID; + + if (!appCFG) { + cerr << "Failed to find CFG for function " << funcName << endl; + return false; + } + + BPatch_Set < BPatch_basicBlock * >allBlocks; + if (!appCFG->getAllBasicBlocks (allBlocks)) { + cerr << "Failed to find basic blocks for function " << funcName << endl; + return false; + } else if (allBlocks.size () == 0) { + cerr << "No basic blocks for function " << funcName << endl; + return false; + } + + BPatch_Set < BPatch_basicBlock * >::iterator iter; + for (iter = allBlocks.begin (); iter != allBlocks.end (); iter++) { + if(*bbIndex < bbSkip) { // skip over first bbSkip bbs + (*bbIndex)++; + continue; + + } + unsigned long address = (*iter)->getStartAddress (); + randID = rand() % USHRT_MAX; + if(verbose) { + cout << "Instrumenting Basic Block 0x" << hex << address << " of " << + funcName << " with random id " << randID << endl; + } + + BPatch_Vector < BPatch_snippet * >instArgs; + BPatch_constExpr bbId (randID); + instArgs.push_back (&bbId); + BPatch_point *bbEntry = (*iter)->findEntryPoint (); + if (NULL == bbEntry) { + // warn the user, but continue + cerr << "Failed to find entry for basic block at 0x" << hex << address + << endl; + (*bbIndex)++; + continue; + } + BPatch_funcCallExpr instIncExpr (*instBBIncFunc, instArgs); + BPatchSnippetHandle *handle = + appBin->insertSnippet (instIncExpr, *bbEntry, BPatch_callBefore, + BPatch_lastSnippet); + if (!handle) { + // warn the user, but continue to next bb + cerr << "Failed to insert instrumention in basic block at 0x" << hex << + address << endl; + (*bbIndex)++; + continue; + } + + (*bbIndex)++; + } + + return true; + +} + +int main (int argc, char **argv) +{ + + if(!parseOptions(argc,argv)) { + return EXIT_FAILURE; + } + + BPatch bpatch; + + BPatch_binaryEdit *appBin = bpatch.openBinary (originalBinary, !instrumentLibraries.empty()); + if (appBin == NULL) { + cerr << "Failed to open binary" << endl; + return EXIT_FAILURE; + } + + if (!appBin->loadLibrary (instLibrary)) { + cerr << "Failed to open instrumentation library." << endl; + cerr << "It needs to be located in the current working directory." << endl; + return EXIT_FAILURE; + } + + BPatch_image *appImage = appBin->getImage (); + + /* Find code coverage functions in the instrumentation library */ + BPatch_function *initAflForkServer = + findFuncByName (appImage, (char *) "initAflForkServer"); + BPatch_function *bbCallback = + findFuncByName (appImage, (char *) "bbCallback"); + if (!initAflForkServer || !bbCallback ) { + cerr << "Instrumentation library lacks callbacks!" << endl; + return EXIT_FAILURE; + } + + //get and iterate over all modules, instrumenting only the default and manualy specified ones + vector < BPatch_module * >*modules = appImage->getModules (); + vector < BPatch_module * >::iterator moduleIter; + BPatch_module *defaultModule = NULL; + string defaultModuleName; + for (moduleIter = modules->begin (); moduleIter != modules->end (); ++moduleIter) { + //find default module name + char moduleName[1024]; + (*moduleIter)->getName (moduleName, 1024); + if (string (moduleName).find ("DEFAULT_MODULE") != string::npos) { + defaultModuleName = "DEFAULT_MODULE"; + } + } + if(defaultModuleName.empty()) + defaultModuleName = string(originalBinary).substr(string(originalBinary).find_last_of("\\/")+1); + int bbIndex = 0; + for (moduleIter = modules->begin (); moduleIter != modules->end (); ++moduleIter) { + char moduleName[1024]; + (*moduleIter)->getName (moduleName, 1024); + + if ((*moduleIter)->isSharedLib ()) { + if (instrumentLibraries.find (moduleName) == instrumentLibraries.end ()) { + cout << "Skipping library: " << moduleName << endl; + continue; + } + } + + if (string (moduleName).find (defaultModuleName) != string::npos) { + defaultModule = (*moduleIter); + if(skipMainModule) continue; + } + cout << "Instrumenting module: " << moduleName << endl; + vector < BPatch_function * >*allFunctions = + (*moduleIter)->getProcedures (); + vector < BPatch_function * >::iterator funcIter; + + // iterate over all functions in the module + for (funcIter = allFunctions->begin (); funcIter != allFunctions->end (); + ++funcIter) { + BPatch_function *curFunc = *funcIter; + char funcName[1024]; + curFunc->getName (funcName, 1024); + if(string (funcName) == string("_start")) continue; // here's a bug on hlt + insertBBCallback (appBin, curFunc, funcName, bbCallback, &bbIndex); + } + + } + + //if entrypoint set ,find function , else find _init + BPatch_function *funcToPatch = NULL; + if(!entryPoint) { + BPatch_Vector<BPatch_function*> funcs; + defaultModule->findFunction("_init", funcs); + if(!funcs.size()) { + cerr << "Couldn't locate _init, specify entry point manualy. "<< endl; + return EXIT_FAILURE; + } + // there should really be only one + funcToPatch = funcs[0]; + } else { + funcToPatch = defaultModule->findFunctionByEntry(entryPoint); + } + if(!funcToPatch) { + cerr << "Couldn't locate function at given entry point. "<< endl; + return EXIT_FAILURE; + } + if(!insertCallToInit (appBin, initAflForkServer,defaultModule,funcToPatch)){ + cerr << "Could not insert init callback at given entry point." << endl; + return EXIT_FAILURE; + } + + cout << "Saving the instrumented binary to " << instrumentedBinary << "..." << endl; + // Output the instrumented binary + if (!appBin->writeFile (instrumentedBinary)) { + cerr << "Failed to write output file: " << instrumentedBinary << endl; + return EXIT_FAILURE; + } + + if(!runtimeLibraries.empty()) { + cout << "Instrumenting runtime libraries." << endl; + set<string>::iterator rtLibIter ; + for(rtLibIter = runtimeLibraries.begin(); rtLibIter != runtimeLibraries.end(); rtLibIter++) { + BPatch_binaryEdit *libBin = bpatch.openBinary ((*rtLibIter).c_str(), false); + if (libBin == NULL) { + cerr << "Failed to open binary "<< *rtLibIter << endl; + return EXIT_FAILURE; + } + libBin->loadLibrary (instLibrary); + BPatch_image *libImg = libBin->getImage (); + vector < BPatch_module * >*modules = libImg->getModules (); + moduleIter = modules->begin (); + ++moduleIter; + for ( ; moduleIter != modules->end (); ++moduleIter) { + char moduleName[1024]; + (*moduleIter)->getName (moduleName, 1024); + cout << "Instrumenting module: " << moduleName << endl; + vector < BPatch_function * >*allFunctions = + (*moduleIter)->getProcedures (); + vector < BPatch_function * >::iterator funcIter; + // iterate over all functions in the module + for (funcIter = allFunctions->begin (); funcIter != allFunctions->end (); + ++funcIter) { + BPatch_function *curFunc = *funcIter; + char funcName[1024]; + curFunc->getName (funcName, 1024); + if(string (funcName) == string("_start")) continue; + insertBBCallback (libBin, curFunc, funcName, bbCallback, &bbIndex); + } + } + if (!libBin->writeFile ((*rtLibIter + ".ins").c_str())) { + cerr << "Failed to write output file: " <<(*rtLibIter + ".ins").c_str() << endl; + return EXIT_FAILURE; + } else { + cout << "Saved the instrumented library to " << (*rtLibIter + ".ins").c_str() << "." << endl; + } + } + } + + cout << "All done! Happy fuzzing!" << endl; + return EXIT_SUCCESS; + +} diff --git a/libAflDyninst.cpp b/libAflDyninst.cpp new file mode 100644 index 0000000..514144f --- /dev/null +++ b/libAflDyninst.cpp @@ -0,0 +1,83 @@ +#include <cstdlib> +#include <cstdio> +#include <iostream> +#include <cstring> +#include <vector> +#include <algorithm> +#include "config.h" +#include <sys/types.h> +#include <sys/shm.h> +#include <unistd.h> +#include <sys/wait.h> +#include <sys/stat.h> +#include <fcntl.h> + +using namespace std; + + +static u8* trace_bits; +static s32 shm_id; /* ID of the SHM region */ +static int __afl_temp_data; +static pid_t __afl_fork_pid; +static unsigned short prev_id; + + +void initAflForkServer() +{ + char *shm_env_var = getenv(SHM_ENV_VAR); + if(!shm_env_var) { + printf("Error getting shm\n"); + return; + } + shm_id = atoi(shm_env_var); + trace_bits = (u8*)shmat(shm_id, NULL, 0); + if(trace_bits == (u8*)-1) { + perror("shmat"); + return; + } + + // enter fork() server thyme! + int n = write(FORKSRV_FD+1, &__afl_temp_data,4); + if( n!=4 ) { + printf("Error writting fork server\n"); + return; + } + while(1) { + n = read(FORKSRV_FD,&__afl_temp_data,4); + if(n != 4) { + printf("Error reading fork server %x\n",__afl_temp_data); + return; + } + + __afl_fork_pid = fork(); + if(__afl_fork_pid < 0) { + printf("Error on fork()\n"); + return; + } + if(__afl_fork_pid == 0) { + close(FORKSRV_FD); + close(FORKSRV_FD+1); + break; + } else { + // parrent stuff + n = write(FORKSRV_FD+1,&__afl_fork_pid, 4); + pid_t temp_pid = waitpid(__afl_fork_pid,&__afl_temp_data,2); + if(temp_pid == 0) { + return; + } + n = write(FORKSRV_FD+1,&__afl_temp_data,4); + } + + } + +} + + +// Should be called on basic block entry +void bbCallback(unsigned short id) +{ + if(trace_bits) { + trace_bits[prev_id ^ id]++; + prev_id = id >> 1; + } +} |