From c00059a38604e199f5a9eabf0180be2cea3e2f84 Mon Sep 17 00:00:00 2001 From: Jason Hiser <jdhiser@gmail.com> Date: Mon, 18 Feb 2019 13:52:31 -0500 Subject: [PATCH] All useful code in tools moved to more appropriate places. unuseful code moved to deprecated_transforms project Former-commit-id: fdc7813772cc94832ce8036271bfdce226fd1326 --- tools/SConscript | 44 - tools/SConstruct | 7 - tools/absolutify/SConscript | 29 - tools/absolutify/SConstruct | 7 - tools/absolutify/absolutify.cpp | 103 -- tools/absolutify/absolutify.hpp | 23 - tools/absolutify/absolutify_driver.cpp | 89 -- tools/c2e/Makefile.in | 42 - tools/c2e/SConscript | 36 - tools/c2e/SConstruct | 7 - tools/c2e/c2e_driver.cpp | 119 -- tools/c2e/c2e_instr.cpp | 577 ------- tools/c2e/c2e_instr.hpp | 78 - tools/cgc_buffrecv/SConscript | 33 - tools/cgc_buffrecv/SConstruct | 7 - tools/cgc_buffrecv/buffrecv_driver.cpp | 148 -- tools/cgc_buffrecv/buffrecv_instrument.cpp | 179 --- tools/cgc_buffrecv/buffrecv_instrument.hpp | 60 - tools/cgc_hlx/Makefile.in | 41 - tools/cgc_hlx/SConscript | 30 - tools/cgc_hlx/SConstruct | 7 - tools/cgc_hlx/cgc_hlx.cpp | 204 --- tools/cgc_hlx/cgc_hlx.hpp | 70 - tools/cgc_hlx/cgc_hlx_driver.cpp | 172 --- tools/cgc_protect/cgc_protect_one.sh | 75 - tools/cgc_protect/is_new_pov.sh | 77 - tools/cgc_protect/pov_to_cso.sh | 156 -- tools/cgc_rigrandom/Makefile.in | 42 - tools/cgc_rigrandom/SConscript | 32 - tools/cgc_rigrandom/SConstruct | 7 - tools/cgc_rigrandom/rigrandom_driver.cpp | 105 -- tools/cgc_rigrandom/rigrandom_instr.cpp | 170 -- tools/cgc_rigrandom/rigrandom_instr.hpp | 50 - tools/cgclibc/Makefile | 49 - tools/cgclibc/README | 58 - tools/cgclibc/SConscript | 44 - tools/cgclibc/SConstruct | 7 - tools/cgclibc/cgclibc.cpp | 888 ----------- tools/cgclibc/cgclibc.hpp | 83 - tools/cgclibc/cgclibc_driver.cpp | 121 -- tools/cgclibc/display_functions.cpp | 86 -- tools/cgclibc/infer_syscall_wrappers.cpp | 96 -- tools/cinderella/Makefile | 38 - tools/cinderella/SConscript | 32 - tools/cinderella/SConstruct | 7 - tools/cinderella/cinderella_prep.cpp | 122 -- tools/cinderella/cinderella_prep.hpp | 48 - tools/cinderella/cinderella_prep_driver.cpp | 98 -- tools/cookbook/SConscript | 52 - tools/cookbook/SConstruct | 7 - tools/cookbook/checkwhitelist.hpp | 20 - tools/cookbook/checkwhitelistdriver.cpp | 115 -- tools/cookbook/cookbook.hpp | 91 -- tools/cookbook/functioncall.hpp | 20 - tools/cookbook/functioncalldriver.cpp | 115 -- tools/cookbook/instructioncount.hpp | 22 - tools/cookbook/instructioncountdriver.cpp | 114 -- tools/cookbook/logdriver.cpp | 115 -- tools/cookbook/syscall.hpp | 20 - tools/cookbook/syscalldriver.cpp | 114 -- tools/cookbook/whitelist.hpp | 20 - tools/cookbook/whitelistdriver.cpp | 115 -- .../cookbook/x86_64_linux/checkwhitelist.cpp | 79 - tools/cookbook/x86_64_linux/cookbook.cpp | 220 --- tools/cookbook/x86_64_linux/functioncall.cpp | 96 -- .../x86_64_linux/instructioncount.cpp | 145 -- tools/cookbook/x86_64_linux/syscall.cpp | 75 - tools/cookbook/x86_64_linux/whitelist.cpp | 102 -- tools/cover/Makefile.in | 41 - tools/cover/SConscript | 29 - tools/cover/SConstruct | 7 - tools/cover/cover.cpp | 90 -- tools/cover/coverage.cpp | 200 --- tools/cover/coverage.h | 47 - tools/fix_canaries/SConscript | 28 - tools/fix_canaries/SConstruct | 7 - tools/fix_canaries/fix_canaries.cpp | 595 ------- tools/fix_canaries/fix_canaries.hpp | 32 - tools/fix_canaries/fix_canaries_driver.cpp | 123 -- tools/fix_canaries/fix_canaries_xor.cpp | 350 ----- tools/fix_rets/Makefile.in | 42 - tools/fix_rets/SConscript | 30 - tools/fix_rets/SConstruct | 7 - tools/fix_rets/fix_rets.cpp | 107 -- tools/fix_rets/fix_rets.hpp | 35 - tools/fix_rets/fix_rets_driver.cpp | 108 -- tools/hook_dynamic_call/SConscript | 35 - tools/hook_dynamic_call/SConstruct | 7 - .../hook_dynamic_call/hook_dynamic_calls.cpp | 542 ------- .../hook_dynamic_call/hook_dynamic_calls.hpp | 50 - .../hook_dynamic_calls_driver.cpp | 139 -- tools/hook_start/SConscript | 29 - tools/hook_start/SConstruct | 7 - tools/hook_start/hook_start.cpp | 152 -- tools/hook_start/hook_start.hpp | 37 - tools/hook_start/hook_start_driver.cpp | 95 -- tools/ibtcheck/Makefile | 6 - tools/ibtcheck/ibtcheck.py | 135 -- tools/ibtcheck/test_cal.sh | 85 - tools/inferfn/Makefile | 39 - tools/inferfn/SConscript | 30 - tools/inferfn/SConstruct | 7 - tools/inferfn/inferfn.cpp | 123 -- tools/inferfn/inferfn.hpp | 48 - tools/inferfn/inferfn_driver.cpp | 99 -- tools/memcover/General_Utility.cpp | 99 -- tools/memcover/General_Utility.hpp | 44 - tools/memcover/Makefile | 42 - tools/memcover/SConscript | 32 - tools/memcover/SConstruct | 7 - tools/memcover/memcover.cpp | 634 -------- tools/prince/Makefile | 36 - tools/prince/SConscript | 31 - tools/prince/SConstruct | 7 - tools/prince/prince.cpp | 1375 ----------------- tools/prince/prince.sh | 56 - tools/prince/prince_driver.cpp | 101 -- tools/print_cfi_stats/Makefile.in | 42 - tools/print_cfi_stats/SConscript | 29 - tools/print_cfi_stats/SConstruct | 7 - .../print_cfi_stats_driver.cpp | 194 --- tools/ret_shadow_stack/LICENSE.txt | 11 - tools/ret_shadow_stack/Makefile.in | 36 - tools/ret_shadow_stack/SConscript | 28 - tools/ret_shadow_stack/SConstruct | 7 - tools/ret_shadow_stack/rss_driver.cpp | 183 --- tools/ret_shadow_stack/rss_instrument.cpp | 595 ------- tools/ret_shadow_stack/rss_instrument.hpp | 51 - tools/safefn/LICENSE.txt | 11 - tools/safefn/Makefile.in | 26 - tools/safefn/SConscript | 29 - tools/safefn/SConstruct | 7 - tools/safefn/fill_in_safefn.cpp | 161 -- tools/safefr/LICENSE.txt | 11 - tools/safefr/Makefile.in | 26 - tools/safefr/SConscript | 29 - tools/safefr/SConstruct | 7 - tools/safefr/fill_in_safefr.cpp | 162 -- tools/simple_cdi/Makefile.in | 42 - tools/simple_cdi/SConscript | 27 - tools/simple_cdi/SConstruct | 7 - tools/simple_cdi/scdi_driver.cpp | 115 -- tools/simple_cdi/scdi_instr.cpp | 242 --- tools/simple_cdi/scdi_instr.hpp | 64 - tools/spasm/Makefile.in | 21 - tools/spasm/SConscript | 32 - tools/spasm/SConstruct | 7 - tools/spasm/ben_lib.cpp | 59 - tools/spasm/ben_lib.h | 40 - tools/spasm/do_nasm.sh | 4 - tools/spasm/spasm.cpp | 908 ----------- tools/spasm/spasm.h | 60 - tools/spasm/spasm_main.cpp | 99 -- tools/spasm/test.aspri | 29 - tools/spasm/tst.s | 2 - 155 files changed, 15677 deletions(-) delete mode 100644 tools/SConscript delete mode 100644 tools/SConstruct delete mode 100644 tools/absolutify/SConscript delete mode 100644 tools/absolutify/SConstruct delete mode 100644 tools/absolutify/absolutify.cpp delete mode 100644 tools/absolutify/absolutify.hpp delete mode 100644 tools/absolutify/absolutify_driver.cpp delete mode 100644 tools/c2e/Makefile.in delete mode 100644 tools/c2e/SConscript delete mode 100644 tools/c2e/SConstruct delete mode 100644 tools/c2e/c2e_driver.cpp delete mode 100644 tools/c2e/c2e_instr.cpp delete mode 100644 tools/c2e/c2e_instr.hpp delete mode 100644 tools/cgc_buffrecv/SConscript delete mode 100644 tools/cgc_buffrecv/SConstruct delete mode 100644 tools/cgc_buffrecv/buffrecv_driver.cpp delete mode 100644 tools/cgc_buffrecv/buffrecv_instrument.cpp delete mode 100644 tools/cgc_buffrecv/buffrecv_instrument.hpp delete mode 100644 tools/cgc_hlx/Makefile.in delete mode 100644 tools/cgc_hlx/SConscript delete mode 100644 tools/cgc_hlx/SConstruct delete mode 100644 tools/cgc_hlx/cgc_hlx.cpp delete mode 100644 tools/cgc_hlx/cgc_hlx.hpp delete mode 100644 tools/cgc_hlx/cgc_hlx_driver.cpp delete mode 100755 tools/cgc_protect/cgc_protect_one.sh delete mode 100755 tools/cgc_protect/is_new_pov.sh delete mode 100755 tools/cgc_protect/pov_to_cso.sh delete mode 100644 tools/cgc_rigrandom/Makefile.in delete mode 100644 tools/cgc_rigrandom/SConscript delete mode 100644 tools/cgc_rigrandom/SConstruct delete mode 100644 tools/cgc_rigrandom/rigrandom_driver.cpp delete mode 100644 tools/cgc_rigrandom/rigrandom_instr.cpp delete mode 100644 tools/cgc_rigrandom/rigrandom_instr.hpp delete mode 100644 tools/cgclibc/Makefile delete mode 100644 tools/cgclibc/README delete mode 100644 tools/cgclibc/SConscript delete mode 100644 tools/cgclibc/SConstruct delete mode 100644 tools/cgclibc/cgclibc.cpp delete mode 100644 tools/cgclibc/cgclibc.hpp delete mode 100644 tools/cgclibc/cgclibc_driver.cpp delete mode 100644 tools/cgclibc/display_functions.cpp delete mode 100644 tools/cgclibc/infer_syscall_wrappers.cpp delete mode 100644 tools/cinderella/Makefile delete mode 100644 tools/cinderella/SConscript delete mode 100644 tools/cinderella/SConstruct delete mode 100644 tools/cinderella/cinderella_prep.cpp delete mode 100644 tools/cinderella/cinderella_prep.hpp delete mode 100644 tools/cinderella/cinderella_prep_driver.cpp delete mode 100644 tools/cookbook/SConscript delete mode 100644 tools/cookbook/SConstruct delete mode 100644 tools/cookbook/checkwhitelist.hpp delete mode 100644 tools/cookbook/checkwhitelistdriver.cpp delete mode 100644 tools/cookbook/cookbook.hpp delete mode 100644 tools/cookbook/functioncall.hpp delete mode 100644 tools/cookbook/functioncalldriver.cpp delete mode 100644 tools/cookbook/instructioncount.hpp delete mode 100644 tools/cookbook/instructioncountdriver.cpp delete mode 100644 tools/cookbook/logdriver.cpp delete mode 100644 tools/cookbook/syscall.hpp delete mode 100644 tools/cookbook/syscalldriver.cpp delete mode 100644 tools/cookbook/whitelist.hpp delete mode 100644 tools/cookbook/whitelistdriver.cpp delete mode 100644 tools/cookbook/x86_64_linux/checkwhitelist.cpp delete mode 100644 tools/cookbook/x86_64_linux/cookbook.cpp delete mode 100644 tools/cookbook/x86_64_linux/functioncall.cpp delete mode 100644 tools/cookbook/x86_64_linux/instructioncount.cpp delete mode 100644 tools/cookbook/x86_64_linux/syscall.cpp delete mode 100644 tools/cookbook/x86_64_linux/whitelist.cpp delete mode 100644 tools/cover/Makefile.in delete mode 100644 tools/cover/SConscript delete mode 100644 tools/cover/SConstruct delete mode 100644 tools/cover/cover.cpp delete mode 100644 tools/cover/coverage.cpp delete mode 100644 tools/cover/coverage.h delete mode 100644 tools/fix_canaries/SConscript delete mode 100644 tools/fix_canaries/SConstruct delete mode 100644 tools/fix_canaries/fix_canaries.cpp delete mode 100644 tools/fix_canaries/fix_canaries.hpp delete mode 100644 tools/fix_canaries/fix_canaries_driver.cpp delete mode 100644 tools/fix_canaries/fix_canaries_xor.cpp delete mode 100644 tools/fix_rets/Makefile.in delete mode 100644 tools/fix_rets/SConscript delete mode 100644 tools/fix_rets/SConstruct delete mode 100644 tools/fix_rets/fix_rets.cpp delete mode 100644 tools/fix_rets/fix_rets.hpp delete mode 100644 tools/fix_rets/fix_rets_driver.cpp delete mode 100644 tools/hook_dynamic_call/SConscript delete mode 100644 tools/hook_dynamic_call/SConstruct delete mode 100644 tools/hook_dynamic_call/hook_dynamic_calls.cpp delete mode 100644 tools/hook_dynamic_call/hook_dynamic_calls.hpp delete mode 100644 tools/hook_dynamic_call/hook_dynamic_calls_driver.cpp delete mode 100644 tools/hook_start/SConscript delete mode 100644 tools/hook_start/SConstruct delete mode 100644 tools/hook_start/hook_start.cpp delete mode 100644 tools/hook_start/hook_start.hpp delete mode 100644 tools/hook_start/hook_start_driver.cpp delete mode 100644 tools/ibtcheck/Makefile delete mode 100644 tools/ibtcheck/ibtcheck.py delete mode 100755 tools/ibtcheck/test_cal.sh delete mode 100644 tools/inferfn/Makefile delete mode 100644 tools/inferfn/SConscript delete mode 100644 tools/inferfn/SConstruct delete mode 100644 tools/inferfn/inferfn.cpp delete mode 100644 tools/inferfn/inferfn.hpp delete mode 100644 tools/inferfn/inferfn_driver.cpp delete mode 100644 tools/memcover/General_Utility.cpp delete mode 100644 tools/memcover/General_Utility.hpp delete mode 100644 tools/memcover/Makefile delete mode 100644 tools/memcover/SConscript delete mode 100644 tools/memcover/SConstruct delete mode 100644 tools/memcover/memcover.cpp delete mode 100644 tools/prince/Makefile delete mode 100644 tools/prince/SConscript delete mode 100644 tools/prince/SConstruct delete mode 100644 tools/prince/prince.cpp delete mode 100755 tools/prince/prince.sh delete mode 100644 tools/prince/prince_driver.cpp delete mode 100644 tools/print_cfi_stats/Makefile.in delete mode 100644 tools/print_cfi_stats/SConscript delete mode 100644 tools/print_cfi_stats/SConstruct delete mode 100644 tools/print_cfi_stats/print_cfi_stats_driver.cpp delete mode 100644 tools/ret_shadow_stack/LICENSE.txt delete mode 100644 tools/ret_shadow_stack/Makefile.in delete mode 100644 tools/ret_shadow_stack/SConscript delete mode 100644 tools/ret_shadow_stack/SConstruct delete mode 100644 tools/ret_shadow_stack/rss_driver.cpp delete mode 100644 tools/ret_shadow_stack/rss_instrument.cpp delete mode 100644 tools/ret_shadow_stack/rss_instrument.hpp delete mode 100644 tools/safefn/LICENSE.txt delete mode 100644 tools/safefn/Makefile.in delete mode 100644 tools/safefn/SConscript delete mode 100644 tools/safefn/SConstruct delete mode 100644 tools/safefn/fill_in_safefn.cpp delete mode 100644 tools/safefr/LICENSE.txt delete mode 100644 tools/safefr/Makefile.in delete mode 100644 tools/safefr/SConscript delete mode 100644 tools/safefr/SConstruct delete mode 100644 tools/safefr/fill_in_safefr.cpp delete mode 100644 tools/simple_cdi/Makefile.in delete mode 100644 tools/simple_cdi/SConscript delete mode 100644 tools/simple_cdi/SConstruct delete mode 100644 tools/simple_cdi/scdi_driver.cpp delete mode 100644 tools/simple_cdi/scdi_instr.cpp delete mode 100644 tools/simple_cdi/scdi_instr.hpp delete mode 100644 tools/spasm/Makefile.in delete mode 100644 tools/spasm/SConscript delete mode 100644 tools/spasm/SConstruct delete mode 100644 tools/spasm/ben_lib.cpp delete mode 100644 tools/spasm/ben_lib.h delete mode 100755 tools/spasm/do_nasm.sh delete mode 100755 tools/spasm/spasm.cpp delete mode 100644 tools/spasm/spasm.h delete mode 100644 tools/spasm/spasm_main.cpp delete mode 100644 tools/spasm/test.aspri delete mode 100644 tools/spasm/tst.s diff --git a/tools/SConscript b/tools/SConscript deleted file mode 100644 index bfaf22cb6..000000000 --- a/tools/SConscript +++ /dev/null @@ -1,44 +0,0 @@ -import os - -Import('env') - -tools=[] - -dirs=''' - selective_cfi - ''' - -nobuild_dirs=''' - cover - fix_rets - safefr - spasm - hook_start - cookbook - simple_cdi - ret_shadow_stack - print_cfi_stats - memcover - ''' -cgc_dirs=''' - c2e - cgc_hlx - cgclibc - cgc_rigrandom - cinderella - inferfn - prince - ''' - - -for i in Split(dirs): - newtool=SConscript(os.path.join(i,"SConscript")) - tools=tools + newtool - - -if 'build_cgc' in env and int(env['build_cgc']) == 1: - for i in Split(cgc_dirs): - newtool=SConscript(os.path.join(i,"SConscript")) - tools=tools+newtool - -Return('tools') diff --git a/tools/SConstruct b/tools/SConstruct deleted file mode 100644 index b3bd01322..000000000 --- a/tools/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -lib=SConscript("SConscript") -Return('lib') diff --git a/tools/absolutify/SConscript b/tools/absolutify/SConscript deleted file mode 100644 index a2d648e42..000000000 --- a/tools/absolutify/SConscript +++ /dev/null @@ -1,29 +0,0 @@ -import os - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libEXEIO/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - $SECURITY_TRANSFORMS_HOME/xform - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - ''' - -# $SECURITY_TRANSFORMS_HOME/libtransform/include -CPPFLAGS="--std=c++11" -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ "IRDB-core IRDB-cfg IRDB-util pqxx BeaEngine_s_d transform MEDSannotation") - -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -myenv.Append(CPPFLAGS=CPPFLAGS) - -pgm=myenv.Program(target="absolutify.exe", source=Split("absolutify.cpp absolutify_driver.cpp"), LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/plugins_install/", pgm) -Default(install) - -Return('install') diff --git a/tools/absolutify/SConstruct b/tools/absolutify/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/absolutify/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/absolutify/absolutify.cpp b/tools/absolutify/absolutify.cpp deleted file mode 100644 index 9e72c2aea..000000000 --- a/tools/absolutify/absolutify.cpp +++ /dev/null @@ -1,103 +0,0 @@ -#include "absolutify.hpp" - -#include "Rewrite_Utility.hpp" -#include <assert.h> -#include <stdexcept> - -using namespace libTransform; -using namespace ELFIO; -using namespace libIRDB; - -Absolutify::Absolutify(FileIR_t *p_variantIR) : - Transform(NULL, p_variantIR, NULL) -{ - -} - -Absolutify::~Absolutify() -{ -} - -bool arg_has_relative(const ARGTYPE &arg) -{ - /* if it's relative memory, watch out! */ - if(arg.ArgType&MEMORY_TYPE) - if(arg.ArgType&RELATIVE_) - return true; - - return false; -} - -bool arg_has_constant(const ARGTYPE &arg) -{ - /* if it's relative memory, watch out! */ - if(arg.ArgType&CONSTANT_TYPE) - return true; - - return false; -} -int Absolutify::execute() -{ -/* - for( - set<Function_t*>::const_iterator itf=getFileIR()->GetFunctions().begin(); - itf!=getFileIR()->GetFunctions().end(); - ++itf - ) - { - Function_t* func=*itf; -*/ - for( - //set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - set<Instruction_t*>::const_iterator it=getFileIR()->GetInstructions().begin(); - //it!=func->GetInstructions().end(); - it!=getFileIR()->GetInstructions().end(); - ++it) - { - DISASM disasm; - Instruction_t *insn = *it; - ARGTYPE* the_arg=NULL; - string updated_asm; - size_t open_bracket_index = 0; - - insn->Disassemble(disasm); - - int is_rel= arg_has_relative(disasm.Argument1) || - arg_has_relative(disasm.Argument2) || - arg_has_relative(disasm.Argument3); - if (!is_rel) - continue; - - if(arg_has_relative(disasm.Argument1)) - the_arg=&disasm.Argument1; - if(arg_has_relative(disasm.Argument2)) - the_arg=&disasm.Argument2; - if(arg_has_relative(disasm.Argument3)) - the_arg=&disasm.Argument3; - assert(the_arg); - - updated_asm = string(disasm.CompleteInstr); - - cout << "Original Disassembled: " << updated_asm << endl; - - while (string::npos != - (open_bracket_index = updated_asm.find("[", open_bracket_index)) - ) - { - updated_asm.replace(open_bracket_index, 1, "[abs "); - open_bracket_index++; - } - cout << "updated Assembly: " << updated_asm << endl; - - insn->Assemble(updated_asm); - - insn->Disassemble(disasm); - updated_asm = string(disasm.CompleteInstr); - - cout << "Updated Disassembled: " << updated_asm << endl; - } - /* - } - */ - return true; -} diff --git a/tools/absolutify/absolutify.hpp b/tools/absolutify/absolutify.hpp deleted file mode 100644 index 2cc1dcaac..000000000 --- a/tools/absolutify/absolutify.hpp +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef _LIBTRANSFORM_ABSOLUTIFY_H_ -#define _LIBTRANSFORM_ABSOLUTIFY_H_ - -#include "../../libtransform/include/transform.hpp" -#include "../../libMEDSannotation/include/VirtualOffset.hpp" -#include <libIRDB-core.hpp> -#include <libIRDB-cfg.hpp> -#include <libIRDB-syscall.hpp> -#include "elfio/elfio.hpp" - -using namespace std; -using namespace libIRDB; - -class Absolutify : public libTransform::Transform -{ - public: - Absolutify(FileIR_t*p_variantIR); - ~Absolutify(); - int execute(); - std::unique_ptr<ELFIO::elfio> m_elfiop; - std::unique_ptr<pqxx::largeobjectaccess> file_object; -}; -#endif diff --git a/tools/absolutify/absolutify_driver.cpp b/tools/absolutify/absolutify_driver.cpp deleted file mode 100644 index 6320d5196..000000000 --- a/tools/absolutify/absolutify_driver.cpp +++ /dev/null @@ -1,89 +0,0 @@ -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "absolutify.hpp" - -using namespace std; -using namespace libIRDB; - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id>\n"; -} - -int main(int argc, char **argv) -{ - pqxxDB_t pqxx_interface; - VariantID_t *pidp=NULL; - int variantID; - string programName; - - if(argc < 2) - { - usage(argv[0]); - exit(1); - } - - programName = string(argv[0]); - variantID = atoi(argv[1]); - argv+=2; - - /* setup the interface to the sql server */ - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - cout<<"absolutify.exe started\n"; - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - cout<<"Transforming "<<this_file->GetURL()<<endl; - - assert(firp && pidp); - - try - { - Absolutify absolutify(firp); - - int success=absolutify.execute(); - - if (success) - { - cout<<"Writing changes for "<<this_file->GetURL()<<endl; - one_success = true; - firp->WriteToDB(); - delete firp; - } - else - { - cout<<"Skipping (no changes) "<<this_file->GetURL()<<endl; - } - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - // if any integer transforms for any files succeeded, we commit - if (one_success) - { - cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); - } - - return 0; -} diff --git a/tools/c2e/Makefile.in b/tools/c2e/Makefile.in deleted file mode 100644 index 1c1a52406..000000000 --- a/tools/c2e/Makefile.in +++ /dev/null @@ -1,42 +0,0 @@ - - - -CXX=@CXX@ -CXXFLAGS= -INCLUDE=-I. -I../include -I../xform -I../../beaengine/include -I../../libIRDB/include/ -I../../libMEDSannotation/include/ -I../libtransform/include/ -I../transforms -CXXFLAGS= @EXTRA_CXXFLAGS@ $(INCLUDE) -LIBS=-L../../lib -lxform -lIRDB-core -lIRDB-cfg -lBeaEngine_s_d -lpqxx -lMEDSannotation -ltransform ../transforms/Rewrite_Utility.o -lpq - - -OBJS=c2e_driver.o c2e_instr.o -programs=c2e.exe - -.SUFFIXES: .o .c .exe .cpp .hpp - -all: $(programs) - @echo "-----------------------------------" - @echo "- c2e directory -- Build complete -" - @echo "-----------------------------------" - - --include $(OBJS:.o=.d) - -%.o: %.cpp - $(CXX) -c $(CXXFLAGS) $*.cpp - @# - @# build dependencies -- http://scottmcpeak.com/autodepend/autodepend.html - @# - @cpp -MM $(CXXFLAGS) $*.cpp > $*.d 2> /dev/null || true # might fail on solaris with CXX=sun's CC. - @cp -f $*.d $*.d.tmp - @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $*.d - @rm -f $*.d.tmp - -clean: - rm -f *.o core *.exe - -$(programs): ../../lib/*.a - -$(programs): $(OBJS) - $(CXX) $(CXXFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - cp $@ ${SECURITY_TRANSFORMS_HOME}/plugins_install/ - diff --git a/tools/c2e/SConscript b/tools/c2e/SConscript deleted file mode 100644 index 1aba7c556..000000000 --- a/tools/c2e/SConscript +++ /dev/null @@ -1,36 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - -#CFLAGS="-fPIC " - - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - -#print 'and the files are...' -#for file in files: -# print file - -pgm="c2e.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util ") - -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install) - - - -Return('install') diff --git a/tools/c2e/SConstruct b/tools/c2e/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/c2e/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/c2e/c2e_driver.cpp b/tools/c2e/c2e_driver.cpp deleted file mode 100644 index f9f578ebc..000000000 --- a/tools/c2e/c2e_driver.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "c2e_instr.hpp" - -using namespace std; -using namespace libIRDB; - - -#define BINARY_NAME "a.ncexe" -#define SHARED_OBJECTS_DIR "shared_objects" - -// @todo: make these command line options -bool forceExitOnReadEOF = true; // cleanly terminate when EOF encountered -bool forceReadFromStdin = true; // force all reads from fd 0 -bool forceWriteToStdout = true; // force all reads from fd 0 - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id>\n"; -} - -int main(int argc, char **argv) -{ - if(argc != 2) - { - usage(argv[0]); - exit(1); - } - - string programName(argv[0]); - int variantID = atoi(argv[1]); - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - cout<<argv[0]<<" started\n"; - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - cout<<"Transforming "<<this_file->GetURL()<<endl; - - assert(firp && pidp); - - try - { - Cgc2Elf_Instrument c2ei(firp); - c2ei.setForceReadFromStdin(forceReadFromStdin); - c2ei.setForceExitOnReadEOF(forceExitOnReadEOF); - c2ei.setForceWriteToStdout(forceWriteToStdout); - - int success= c2ei.execute(); - - if (success) - { - cout<<"Writing changes for "<<this_file->GetURL()<<endl; - one_success = true; - firp->WriteToDB(); - delete firp; - } - else - { - cout<<"Skipping (no changes) "<<this_file->GetURL()<<endl; - } - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - // if any integer transforms for any files succeeded, we commit - if (one_success) - { - cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); - } - - return 0; -} - diff --git a/tools/c2e/c2e_instr.cpp b/tools/c2e/c2e_instr.cpp deleted file mode 100644 index 5373b6169..000000000 --- a/tools/c2e/c2e_instr.cpp +++ /dev/null @@ -1,577 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - - -#include "utils.hpp" -#include "c2e_instr.hpp" -#include "Rewrite_Utility.hpp" -#include <stdlib.h> - - -// for mmap param -#include <sys/mman.h> -#include <bits/syscall.h> - - - - - -using namespace std; -using namespace libIRDB; - -virtual_offset_t getAvailableAddress(FileIR_t *p_virp) -{ - - static int counter = -16; - counter += 16; - return 0xf0020000 + counter; -} - -template< typename T > -std::string int_to_hex_string( T i ) -{ - std::stringstream stream; - stream << "0x" - << std::hex << i; - return stream.str(); -} - - - - -static Instruction_t* addNewAssembly(FileIR_t* firp, Instruction_t *p_instr, string p_asm) -{ - Instruction_t* newinstr; - if (p_instr) - newinstr = allocateNewInstruction(firp,p_instr->GetAddress()->GetFileID(), p_instr->GetFunction()); - else - newinstr = allocateNewInstruction(firp,BaseObj_t::NOT_IN_DATABASE, NULL); - - firp->RegisterAssembly(newinstr, p_asm); - - if (p_instr) - { - newinstr->SetFallthrough(p_instr->GetFallthrough()); - p_instr->SetFallthrough(newinstr); - } - - return newinstr; -} - - -static Instruction_t* registerCallbackHandler64(FileIR_t* firp, Instruction_t *p_orig, string p_callbackHandler, int p_numArgs) -{ - - Instruction_t *instr; - Instruction_t *first; - char tmpbuf[1024]; - - // save flags and 16 registers (136 bytes) - // call pushes 8 bytes - // Total: 8 * 18 = 144 - first = instr = addNewAssembly(firp,NULL, "push rsp"); - instr = addNewAssembly(firp,instr, "push rbp"); - instr = addNewAssembly(firp,instr, "push rdi"); - instr = addNewAssembly(firp,instr, "push rsi"); - instr = addNewAssembly(firp,instr, "push rdx"); - instr = addNewAssembly(firp,instr, "push rcx"); - instr = addNewAssembly(firp,instr, "push rbx"); - instr = addNewAssembly(firp,instr, "push rax"); - instr = addNewAssembly(firp,instr, "push r8"); - instr = addNewAssembly(firp,instr, "push r9"); - instr = addNewAssembly(firp,instr, "push r10"); - instr = addNewAssembly(firp,instr, "push r11"); - instr = addNewAssembly(firp,instr, "push r12"); - instr = addNewAssembly(firp,instr, "push r13"); - instr = addNewAssembly(firp,instr, "push r14"); - instr = addNewAssembly(firp,instr, "push r15"); - instr = addNewAssembly(firp,instr, "pushf"); - - // handle the arguments (if any): rdi, rsi, rdx, rcx, r8, r9 - // first arg starts at byte +144 - instr = addNewAssembly(firp,instr, "mov rdi, rsp"); - - if (p_numArgs >= 1) - instr = addNewAssembly(firp,instr, "mov rsi, [rsp+144]"); - if (p_numArgs >= 2) - instr = addNewAssembly(firp,instr, "mov rdx, [rsp+152]"); - if (p_numArgs >= 3) - instr = addNewAssembly(firp,instr, "mov rcx, [rsp+160]"); - if (p_numArgs >= 4) - instr = addNewAssembly(firp,instr, "mov r8, [rsp+168]"); - if (p_numArgs > 4) - assert(0); // only handle up to 5 args - - // pin the instruction that follows the callback handler - Instruction_t* postCallback = allocateNewInstruction(firp, BaseObj_t::NOT_IN_DATABASE, NULL); - virtual_offset_t postCallbackReturn = getAvailableAddress(firp); - postCallback->GetAddress()->SetVirtualOffset(postCallbackReturn); - - // push the address to return to once the callback handler is invoked - sprintf(tmpbuf,"mov rax, 0x%x", postCallbackReturn); - instr = addNewAssembly(firp,instr, tmpbuf); - - instr = addNewAssembly(firp,instr, "push rax"); - - // use a nop instruction for the actual callback - instr = addNewAssembly(firp,instr, "nop"); - instr->SetComment(" -- callback: " + p_callbackHandler); - instr->SetCallback(p_callbackHandler); - instr->SetFallthrough(postCallback); - - - // need to make sure the post callback address is pinned - // (so that ILR and other transforms do not relocate it) - AddressID_t *indTarg = new AddressID_t(); - firp->GetAddresses().insert(indTarg); - indTarg->SetVirtualOffset(postCallback->GetAddress()->GetVirtualOffset()); - indTarg->SetFileID(BaseObj_t::NOT_IN_DATABASE); // SPRI global namespace - postCallback->SetIndirectBranchTargetAddress(indTarg); - - // restore registers - firp->RegisterAssembly(postCallback, "popf"); - - - instr = addNewAssembly(firp,postCallback, "pop r15"); - instr = addNewAssembly(firp,instr, "pop r14"); - instr = addNewAssembly(firp,instr, "pop r13"); - instr = addNewAssembly(firp,instr, "pop r12"); - instr = addNewAssembly(firp,instr, "pop r11"); - instr = addNewAssembly(firp,instr, "pop r10"); - instr = addNewAssembly(firp,instr, "pop r9"); - instr = addNewAssembly(firp,instr, "pop r8"); - instr = addNewAssembly(firp,instr, "pop rax"); - instr = addNewAssembly(firp,instr, "pop rbx"); - instr = addNewAssembly(firp,instr, "pop rcx"); - instr = addNewAssembly(firp,instr, "pop rdx"); - instr = addNewAssembly(firp,instr, "pop rsi"); - instr = addNewAssembly(firp,instr, "pop rdi"); - instr = addNewAssembly(firp,instr, "pop rbp"); - instr = addNewAssembly(firp,instr, "lea rsp, [rsp+8]"); - - instr = addNewAssembly(firp,instr, "ret"); - - // return first instruction in the callback handler chain - return first; - -} - - -// x86-64 -// 20140421 -static void ConvertCallToCallbackHandler64(FileIR_t* firp, Instruction_t *p_orig, string p_callbackHandler, int p_numArgs) -{ - static std::map<std::string, Instruction_t*> m_handlerMap; - // nb: if first time, register and cache callback handler sequence - if (m_handlerMap.count(p_callbackHandler) == 0) - { - m_handlerMap[p_callbackHandler] = registerCallbackHandler64(firp,p_orig, p_callbackHandler, p_numArgs); - } - - if (p_orig) - p_orig->SetTarget(m_handlerMap[p_callbackHandler]); -} - - -static Instruction_t* addCallbackHandlerSequence - ( - FileIR_t* firp, - Instruction_t *p_orig, - bool before, - std::string p_detector - ) -{ - - if(before) - insertAssemblyBefore(firp,p_orig,"lea rsp, [rsp-128]"); - else - assert(0); // add handling for inserting lea after given insn - - p_orig->SetComment("callback: " + p_detector); - - - Instruction_t* call =insertAssemblyAfter(firp,p_orig,"call 0"); - - ConvertCallToCallbackHandler64(firp, call, p_detector, 0); // no args for now - - insertAssemblyAfter(firp,call,"lea rsp, [rsp + 128 + 0]"); // no args for nwo - - return p_orig; -} - -Instruction_t* Cgc2Elf_Instrument::insertTerminate(Instruction_t* after) -{ - char buf[100]; - sprintf(buf, "mov eax, %d", SYS_exit); - - after=insertAssemblyAfter(firp, after, buf); - after=insertAssemblyAfter(firp, after, "int 0x80"); - - return after; -} - -Instruction_t* Cgc2Elf_Instrument::insertTransmit(Instruction_t* after, int sysno, int force_fd) -{ - Instruction_t *jmp2return=NULL, *jmp2error=NULL, *success=NULL, *error=NULL; - char fdbuf[100]; - char buf[100]; - sprintf(buf, "mov eax, %d", sysno); - if (force_fd >= 0) - { - sprintf(fdbuf, "mov ebx, %d", force_fd); - after=insertAssemblyAfter(firp, after, "push ebx"); // push old fd - after=insertAssemblyAfter(firp, after, fdbuf); // force fd - } - after=insertAssemblyAfter(firp, after, "push esi"); // push tx_bytes - after=insertAssemblyAfter(firp, after, buf); // set eax to syscall # - after=insertAssemblyAfter(firp, after, "int 0x80"); // make syscall - after=insertAssemblyAfter(firp, after, "pop esi"); // pop tx_bytes - if (force_fd >= 0) - { - after=insertAssemblyAfter(firp, after, "pop ebx"); // restore old fd - } - after=insertAssemblyAfter(firp, after, "cmp eax, -1"); // if return == -1 - jmp2error=after=insertAssemblyAfter(firp, after, "je 0x0"); // jmp to error - after=insertAssemblyAfter(firp, after, "cmp esi, 0"); // if tx_bytes == 0 - jmp2return=after=insertAssemblyAfter(firp, after, "je 0x0"); // jmp to success - after=insertAssemblyAfter(firp, after, "mov [esi], eax"); // store tx_bytes - success=after=insertAssemblyAfter(firp, after, "mov eax, 0"); // return success - error=after=insertAssemblyAfter(firp, after, "mov eax, 25"); // return error - after=insertAssemblyAfter(firp, after, "nop"); // sync point. - - jmp2error->SetTarget(error); - jmp2return->SetTarget(success); - success->SetFallthrough(after); - - return after; -} - -Instruction_t* Cgc2Elf_Instrument::insertReadExitOnEOF(Instruction_t* after) -{ - Instruction_t *jmp2return=NULL, *jmp2error=NULL, *success=NULL, *error=NULL; - char buf[100]; - sprintf(buf, "mov eax, %d", SYS_read); - after=insertAssemblyAfter(firp, after, "push esi"); // push tx_bytes - after=insertAssemblyAfter(firp, after, buf); // set eax to syscall # - after=insertAssemblyAfter(firp, after, "int 0x80"); // make syscall - - after = insertAssemblyAfter(firp, after, "cmp eax, 0"); - Instruction_t* jmp2terminate=insertAssemblyAfter(firp, after, "je 0x0"); // jmp to terminate - - after=insertAssemblyAfter(firp, jmp2terminate, "pop esi"); // pop tx_bytes - after=insertAssemblyAfter(firp, after, "cmp eax, -1"); // if return == -1 - jmp2error=after=insertAssemblyAfter(firp, after, "je 0x0"); // jmp to error - after=insertAssemblyAfter(firp, after, "cmp esi, 0"); // if tx_bytes == 0 - jmp2return=after=insertAssemblyAfter(firp, after, "je 0x0"); // jmp to success - after=insertAssemblyAfter(firp, after, "mov [esi], eax"); // store tx_bytes - success=after=insertAssemblyAfter(firp, after, "mov eax, 0"); // return success - error=after=insertAssemblyAfter(firp, after, "mov eax, 25"); // return error - after=insertAssemblyAfter(firp, after, "nop"); // sync point. - - jmp2error->SetTarget(error); - jmp2return->SetTarget(success); - success->SetFallthrough(after); - - // terminate sequence - Instruction_t* n = addNewAssembly(firp, NULL, "nop"); - n->SetFallthrough(after); // pick anything here, it doesn't matter as we're terminating - Instruction_t* term = insertTerminate(n); - jmp2terminate->SetTarget(n); - - return after; -} - -Instruction_t* Cgc2Elf_Instrument::insertReceive(Instruction_t* after, bool force_stdin, bool exit_on_eof) -{ - if (force_stdin) - { - // force read from file descriptor 0 - after = insertAssemblyAfter(firp, after, "push ebx"); // save original fd - after = insertAssemblyAfter(firp, after, "xor ebx, ebx"); // fd = 0 - if (exit_on_eof) - after = insertReadExitOnEOF(after); - else - after = insertTransmit(after, SYS_read); - after = insertAssemblyAfter(firp, after, "pop ebx"); // restore - return after; - } - else - { - if (exit_on_eof) - return insertReadExitOnEOF(after); - else - return insertTransmit(after, SYS_read); - } -} - -// eax ebx ecx edx esi edi -// int fdwait(int nfds, fd_set *readfds, fd_set *writefds, const struct timeval *timeout, int *readyfds) -// int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); - -// %ebx, %ecx, %edx, %esi, %edi, %ebp -// force_no_timeout: set %edi to 0 -Instruction_t* Cgc2Elf_Instrument::insertFdwait(Instruction_t* after) -{ - Instruction_t *jmp2return=NULL, *jmp2error=NULL, *success=NULL, *error=NULL; - char buf[100]; - sprintf(buf, "mov eax, %d", 142 /* SYS_newselect -- not defined? */); - after=insertAssemblyAfter(firp, after, "push edi"); // push readyfds - after=insertAssemblyAfter(firp, after, buf); // set eax to syscall # - after=insertAssemblyAfter(firp, after, "mov edi, esi"); // mov 4th param to fdwait - fdwait(...,timeout,...) - // into 5th param to select - select(...,timeout,...) - after=insertAssemblyAfter(firp, after, "mov esi, 0"); // set 4th param to select to 0 - after=insertAssemblyAfter(firp, after, "int 0x80"); // make syscall - after=insertAssemblyAfter(firp, after, "pop edi"); // pop readyfds - after=insertAssemblyAfter(firp, after, "cmp eax, -1"); // if return == -1 - jmp2error=after=insertAssemblyAfter(firp, after, "je 0x0"); // jmp to error - after=insertAssemblyAfter(firp, after, "cmp edi, 0"); // if tx_bytes == 0 - jmp2return=after=insertAssemblyAfter(firp, after, "je 0x0"); // jmp to success - after=insertAssemblyAfter(firp, after, "mov [edi], eax"); // store return value into readyfds - success=after=insertAssemblyAfter(firp, after, "mov eax, 0"); // return success - error=after=insertAssemblyAfter(firp, after, "mov eax, 25"); // return error - after=insertAssemblyAfter(firp, after, "nop"); // sync point. - - jmp2error->SetTarget(error); - jmp2return->SetTarget(success); - success->SetFallthrough(after); - - return after; -} -Instruction_t* Cgc2Elf_Instrument::insertAllocate(Instruction_t* after) -{ - Instruction_t *jmp2return=NULL, *jmp2error=NULL, *success=NULL, *error=NULL; - char buf[100]; - after=insertAssemblyAfter(firp, after, "push ebp"); // push ebp to save reg - after=insertAssemblyAfter(firp, after, "push edx"); // push (void **)addr - after=insertAssemblyAfter(firp, after, "push esi"); // save reg - after=insertAssemblyAfter(firp, after, "push edi"); // save reg - -#ifdef SYS_mmap2 - sprintf(buf, "mov eax, %d", SYS_mmap2); -#else - assert(0); // mmap2 required -#endif - after=insertAssemblyAfter(firp, after, buf); // set eax to syscall # - - - - after=insertAssemblyAfter(firp, after, "mov ebp, 0"); // mov 0 to 6th param to mmap2 - mmap2(...,0) - after=insertAssemblyAfter(firp, after, "mov edi, -1"); // mov -1 to 5th param to mmap2 - mmap2(...,-1,0) - sprintf(buf, "mov esi, %d", MAP_PRIVATE|MAP_ANONYMOUS); - after=insertAssemblyAfter(firp, after, buf); // mov MAP_PRIV|ANON to 4th param to mmap2 - mmap2(...,PA,-1,0) - sprintf(buf, "mov edx, %d", PROT_READ|PROT_WRITE|PROT_EXEC); - after=insertAssemblyAfter(firp, after, buf); // mov RWX to 3rd param to mmap2 - mmap2(...RWX,,PA,-1,0) - after=insertAssemblyAfter(firp, after, "mov ecx, ebx"); // mov length to 2nd param to mmap2 - mmap2(...,len,RWX,,PA,-1,0) - after=insertAssemblyAfter(firp, after, "mov ebx,0"); // mov 0 to 1st param to mmap2 - mmap2(0,len,RWX,,PA,-1,0) - - after=insertAssemblyAfter(firp, after, "int 0x80"); // make syscall - after=insertAssemblyAfter(firp, after, "pop edi"); // restore reg - after=insertAssemblyAfter(firp, after, "pop esi"); // restore reg - after=insertAssemblyAfter(firp, after, "pop edx"); // pop (void**)addr - after=insertAssemblyAfter(firp, after, "pop ebp"); // pop ebp to restore reg - after=insertAssemblyAfter(firp, after, "cmp eax, -1"); // if return == -1 - jmp2error=after=insertAssemblyAfter(firp, after, "je 0x0"); // jmp to error - after=insertAssemblyAfter(firp, after, "cmp edx, 0"); // if addr == 0 - jmp2return=after=insertAssemblyAfter(firp, after, "je 0x0"); // jmp to success - after=insertAssemblyAfter(firp, after, "mov [edx], eax"); // store return value into readyfds - success=after=insertAssemblyAfter(firp, after, "mov eax, 0"); // return success - error=after=insertAssemblyAfter(firp, after, "mov eax, 25"); // return error - after=insertAssemblyAfter(firp, after, "nop"); // sync point. - - jmp2error->SetTarget(error); - jmp2return->SetTarget(success); - success->SetFallthrough(after); - - return after; -} - -Instruction_t* Cgc2Elf_Instrument::insertDeallocate(Instruction_t* after) -{ - Instruction_t *jmp2return=NULL, *jmp2error=NULL, *success=NULL, *error=NULL; - char buf[100]; - sprintf(buf, "mov eax, %d", SYS_munmap); - after=insertAssemblyAfter(firp, after, buf); // set eax to syscall # - after=insertAssemblyAfter(firp, after, "int 0x80"); // make syscall - after=insertAssemblyAfter(firp, after, "cmp eax, -1"); // if return == -1 - jmp2error=after=insertAssemblyAfter(firp, after, "je 0x0"); // jmp to error - success=after=insertAssemblyAfter(firp, after, "mov eax, 0"); // return success - error=after=insertAssemblyAfter(firp, after, "mov eax, 25"); // return error - after=insertAssemblyAfter(firp, after, "nop"); // sync point. - - jmp2error->SetTarget(error); - success->SetFallthrough(after); - - return after; -} - -Instruction_t* Cgc2Elf_Instrument::insertRandom(Instruction_t* after) -{ -/* - d: 85 d2 test %ecx,%ecx -J1: 7e 11 jle L4 - 11: b8 00 00 00 00 mov $0x0,%eax -L3: 88 04 01 mov %al,[%ebx+%eax*1] - 19: 83 c0 01 add $0x1,%eax - 1c: 39 d0 cmp %ecx,%eax -J2: 75 f6 jne L3 - 20: eb 05 jmp L2 -L4: ba 00 00 00 00 mov $0x0,%ecx -L2: 85 db test %edx,%edx -J3: 74 02 je L1 - 2b: 89 13 mov %ecx,(%edx) -L1: b8 00 00 00 00 mov $0x0,%eax -*/ - - Instruction_t *J1=NULL, *J2=NULL, *J3=NULL, *L1=NULL, *L2=NULL, *L3=NULL, *L4=NULL; - - after=insertAssemblyAfter(firp, after, "test ecx, ecx"); - J1=after=insertAssemblyAfter(firp, after, "jle 0x0"); - after=insertAssemblyAfter(firp, after, "mov eax, 0"); -// L3=after=insertAssemblyAfter(firp, after, "mov [ebx+eax], al"); - L3=after=insertAssemblyAfter(firp, after, "mov byte [ebx+eax], -1"); // give afl a better chance - after=insertAssemblyAfter(firp, after, "add eax, 1"); - after=insertAssemblyAfter(firp, after, "cmp eax, ecx"); - J2=after=insertAssemblyAfter(firp, after, "jne 0x0"); - - L4=after=insertAssemblyAfter(firp, after, "mov ecx, 0"); - L2=after=insertAssemblyAfter(firp, after, "test edx, edx"); - J3=after=insertAssemblyAfter(firp, after, "je 0x0"); - after=insertAssemblyAfter(firp, after, "mov [edx], ecx"); - L1=after=insertAssemblyAfter(firp, after, "mov eax, 0"); - - J1->SetTarget(L4); - J2->SetTarget(L3); - J2->SetFallthrough(L2); - J3->SetTarget(L1); - - - return after; -} - - -bool Cgc2Elf_Instrument::add_c2e_instrumentation(libIRDB::Instruction_t* insn) -{ - - assert(insn); - cout<<"Adding CGC->Elf instrumentation for "<<insn->GetBaseID()<<":"<<insn->getDisassembly()<<endl; - - Instruction_t* tmp=insn; - Instruction_t* termjmp=NULL, *terminsn=NULL; - Instruction_t* transmitjmp=NULL, *transmitinsn=NULL; - Instruction_t* receivejmp=NULL, *receiveinsn=NULL; - Instruction_t* fdwaitjmp=NULL, *fdwaitinsn=NULL; - Instruction_t* allocatejmp=NULL, *allocateinsn=NULL; - Instruction_t* deallocatejmp=NULL, *deallocateinsn=NULL; - Instruction_t* randomjmp=NULL, *randominsn=NULL; - Instruction_t* old=insn; - Instruction_t* failinsn=NULL; - - old=insertAssemblyBefore(firp,tmp,"cmp eax, 1"); // terminate - terminsn=tmp; - termjmp=tmp=insertAssemblyAfter(firp,tmp,"jne 0"); - tmp=insertTerminate(tmp); - tmp->SetFallthrough(old); - transmitinsn=tmp=addNewAssembly(firp,NULL,"cmp eax, 2"); //transmit - transmitjmp=tmp=insertAssemblyAfter(firp,tmp,"jne 0"); - if (getForceWriteToStdout()) - tmp=insertTransmit(tmp, SYS_write, getForceWriteFd()); // force output on fd=1 - else - tmp=insertTransmit(tmp); - tmp->SetFallthrough(old); - receiveinsn=tmp=addNewAssembly(firp,NULL,"cmp eax, 3"); //receive - receivejmp=tmp=insertAssemblyAfter(firp,tmp,"jne 0"); - tmp=insertReceive(tmp, getForceReadFromStdin(), getForceExitOnReadEOF()); - tmp->SetFallthrough(old); - fdwaitinsn=tmp=addNewAssembly(firp,NULL,"cmp eax, 4"); //fdwait - fdwaitjmp=tmp=insertAssemblyAfter(firp,tmp,"jne 0"); - tmp=insertFdwait(tmp); - tmp->SetFallthrough(old); - allocateinsn=tmp=addNewAssembly(firp,NULL,"cmp eax, 5"); //allocate - allocatejmp=tmp=insertAssemblyAfter(firp,tmp,"jne 0"); - tmp=insertAllocate(tmp); - tmp->SetFallthrough(old); - deallocateinsn=tmp=addNewAssembly(firp,NULL,"cmp eax, 6"); //deallocate - deallocatejmp=tmp=insertAssemblyAfter(firp,tmp,"jne 0"); - tmp=insertDeallocate(tmp); - tmp->SetFallthrough(old); - randominsn=tmp=addNewAssembly(firp,NULL,"cmp eax, 7"); // random - randomjmp=tmp=insertAssemblyAfter(firp,tmp,"jne 0"); - tmp=insertRandom(tmp); - tmp->SetFallthrough(old); - failinsn=tmp=addNewAssembly(firp,NULL,"mov eax, 13"); // fail - failinsn->SetFallthrough(old); - - termjmp->SetTarget(transmitinsn); - transmitjmp->SetTarget(receiveinsn); - receivejmp->SetTarget(fdwaitinsn); - fdwaitjmp->SetTarget(allocateinsn); - allocatejmp->SetTarget(deallocateinsn); - deallocatejmp->SetTarget(randominsn); - randomjmp->SetTarget(failinsn); - - // convert orig. insn to nop. - string bits; - bits.resize(1); - bits[0]=0x90; - old->SetDataBits(bits); - - return true; -} - -bool Cgc2Elf_Instrument::needs_c2e_instrumentation(libIRDB::Instruction_t* insn) -{ - // instrument int instructions - DISASM d; - insn->Disassemble(d); - return strstr(d.CompleteInstr,"int 0x80")!=0; -} - -bool Cgc2Elf_Instrument::instrument_ints() -{ - bool success=true; - InstructionSet_t allinsns=firp->GetInstructions(); - - // we do this in two passes. first pass: find instructions. - for(InstructionSet_t::iterator it=allinsns.begin(); - it!=allinsns.end(); - ++it) - { - Instruction_t* insn=*it; - if(needs_c2e_instrumentation(insn)) - success = success && add_c2e_instrumentation(insn); - - } - - return success; -} - - - -bool Cgc2Elf_Instrument::execute() -{ - - bool success=true; - - success = success && instrument_ints(); - - return success; -} - - diff --git a/tools/c2e/c2e_instr.hpp b/tools/c2e/c2e_instr.hpp deleted file mode 100644 index e217ddf06..000000000 --- a/tools/c2e/c2e_instr.hpp +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#ifndef c2e_instrument_hpp -#define c2e_instrument_hpp - -#include <libIRDB-core.hpp> - -#include <syscall.h> - - - -class Cgc2Elf_Instrument -{ - public: - Cgc2Elf_Instrument(libIRDB::FileIR_t *the_firp) : firp(the_firp) { - forceReadFromStdin = false; - forceExitOnReadEOF = false; - forceWriteToStdout = false; - forceWriteFd = -1; - } - bool execute(); - - void setForceReadFromStdin(bool force) { forceReadFromStdin = force; } - void setForceExitOnReadEOF(bool force) { forceExitOnReadEOF = force; } - void setForceWriteToStdout(bool force, int fd = 1) { forceWriteToStdout = force; forceWriteFd = fd; } - - bool getForceReadFromStdin() const { return forceReadFromStdin; } - bool getForceExitOnReadEOF() const { return forceExitOnReadEOF; } - bool getForceWriteToStdout() const { return forceWriteToStdout; } - int getForceWriteFd() const { return forceWriteFd; } - - private: - - libIRDB::Instruction_t* insertTerminate(libIRDB::Instruction_t* after) ; - libIRDB::Instruction_t* insertTransmit(libIRDB::Instruction_t* after, int sysno=SYS_write, int force_fd=-1); - libIRDB::Instruction_t* insertReadExitOnEOF(libIRDB::Instruction_t* after); - libIRDB::Instruction_t* insertReceive(libIRDB::Instruction_t* after, bool force_stdin=true, bool forceExitOnEOF=true) ; - libIRDB::Instruction_t* insertFdwait(libIRDB::Instruction_t* after) ; - libIRDB::Instruction_t* insertAllocate(libIRDB::Instruction_t* after) ; - libIRDB::Instruction_t* insertDeallocate(libIRDB::Instruction_t* after) ; - libIRDB::Instruction_t* insertRandom(libIRDB::Instruction_t* after) ; - - - - bool add_c2e_instrumentation(libIRDB::Instruction_t* insn); - bool needs_c2e_instrumentation(libIRDB::Instruction_t* insn); - - bool instrument_ints(); - - libIRDB::FileIR_t* firp; - - bool forceReadFromStdin; - bool forceExitOnReadEOF; - bool forceWriteToStdout; - int forceWriteFd; - -}; - -#endif - diff --git a/tools/cgc_buffrecv/SConscript b/tools/cgc_buffrecv/SConscript deleted file mode 100644 index 2bd4decb2..000000000 --- a/tools/cgc_buffrecv/SConscript +++ /dev/null @@ -1,33 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - -myenv.Append(CCFLAGS=" -DCGC") - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="buffrecv.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-syscall IRDB-util transform MEDSannotation ") -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -myenv.Alias("install", "$SECURITY_TRANSFORMS_HOME/bin/") -Default(install) - - - -Return('install') diff --git a/tools/cgc_buffrecv/SConstruct b/tools/cgc_buffrecv/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/cgc_buffrecv/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/cgc_buffrecv/buffrecv_driver.cpp b/tools/cgc_buffrecv/buffrecv_driver.cpp deleted file mode 100644 index ca7a75ea4..000000000 --- a/tools/cgc_buffrecv/buffrecv_driver.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libgen.h> -#include <unistd.h> -#include <stdlib.h> -#include <getopt.h> - -#include <libIRDB-core.hpp> -#include "buffrecv_instrument.hpp" - -using namespace std; -using namespace libIRDB; - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" --varid=<variant_id>\n"; -} - - -int varid=0; - -int parse_args(int p_argc, char* p_argv[]) -{ - int option = 0; - char options[] = "v:"; - struct option long_options[] = { - {"varid", required_argument, NULL, 'v'}, - {NULL, no_argument, NULL, '\0'}, // end-of-array marker - }; - - while ((option = getopt_long( - p_argc, - p_argv, - options, - long_options, - NULL)) != -1) - { - printf("Found option %c\n", option); - switch (option) - { - case 'v': - { - varid=atoi(::optarg); - cout<<"Transforming variant "<<dec<<varid<<endl; - break; - } - default: - return 1; - } - } - return 0; -} - - -int main(int argc, char **argv) -{ - if(0 != parse_args(argc,argv)) - { - usage(argv[0]); - exit(1); - } - - string programName(argv[0]); - int variantID = varid; - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - cout << argv[0] << " started\n"; - - bool success = false; - bool one_success = false; - bool one_fail=false; - - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - try - { - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - cout<<"Transforming "<<this_file->GetURL()<<endl; - - assert(firp && pidp); - - BuffRecv_Instrument wsci(firp); - - success = wsci.execute(); - - if (success) - { - cout<<"Writing changes for "<<this_file->GetURL()<<endl; - one_success = true; - - firp->WriteToDB(); - } - else - { - one_fail=true; - cout<<"Skipping (no changes) "<<this_file->GetURL()<<endl; - } - - delete firp; - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - // if any transforms for any files succeeded, we commit - if (one_success) - { - cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); - } - - return one_fail; -} - diff --git a/tools/cgc_buffrecv/buffrecv_instrument.cpp b/tools/cgc_buffrecv/buffrecv_instrument.cpp deleted file mode 100644 index 4466e4041..000000000 --- a/tools/cgc_buffrecv/buffrecv_instrument.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - */ - -#include <stdlib.h> -#include <string> -#include <iostream> - -#include "buffrecv_instrument.hpp" -#include "Rewrite_Utility.hpp" - - -using namespace std; -using namespace libIRDB; - -virtual_offset_t getAvailableAddress(FileIR_t *p_virp) -{ - static int counter = -16; - counter += 16; - return 0xf0080000 + counter; -} - -static Instruction_t* addNewAssembly(FileIR_t* firp, Instruction_t *p_instr, string p_asm) -{ - Instruction_t* newinstr; - if (p_instr) - newinstr = allocateNewInstruction(firp,p_instr->GetAddress()->GetFileID(), p_instr->GetFunction()); - else - newinstr = allocateNewInstruction(firp,BaseObj_t::NOT_IN_DATABASE, NULL); - - firp->RegisterAssembly(newinstr, p_asm); - - if (p_instr) - { - newinstr->SetFallthrough(p_instr->GetFallthrough()); - p_instr->SetFallthrough(newinstr); - } - - return newinstr; -} - -// site should be: int 0x80 instruction in receive() wrapper -bool BuffRecv_Instrument::_add_buffered_receive_instrumentation(Instruction_t *site) -{ - string bits; - bits.resize(1); - bits[0]=0x90; - site->SetDataBits(bits); // convert site to nop instruction - -//cout<<"Found syscall to instrument "<<site->getDisassembly()<<endl; - - virtual_offset_t postCallbackReturn = getAvailableAddress(firp); - char tmpbuf[100]; - sprintf(tmpbuf,"push 0x%x", postCallbackReturn); - - Instruction_t *tmp=site, *callback=NULL, *post_callback=NULL; - tmp=insertAssemblyAfter(firp,tmp,"pushf"); - tmp=insertAssemblyAfter(firp,tmp,"pusha"); - tmp=insertAssemblyAfter(firp,tmp,tmpbuf); // push <ret addr> - callback=tmp=insertAssemblyAfter(firp,tmp,"nop"); - post_callback=tmp=insertAssemblyAfter(firp,tmp,"popa"); - tmp=insertAssemblyAfter(firp,tmp,"popf"); -// tmp=insertAssemblyAfter(firp,tmp,"mov eax, 0"); - post_callback->GetAddress()->SetVirtualOffset(postCallbackReturn); - callback->SetCallback("buffered_receive"); - return true; -} - -bool BuffRecv_Instrument::add_buffered_receive_instrumentation() -{ - - bool success=true; - - for(SyscallSiteSet_t::iterator it=syscalls.GetSyscalls().begin(); - it!=syscalls.GetSyscalls().end(); - ++it) - { - SyscallSite_t ss=*it; - Instruction_t *site=ss.GetSyscallSite(); - SyscallNumber_t num=ss.GetSyscallNumber(); - if(num==SNT_receive) - { - cout << "Found RECEIVE syscall - instrument: " << site->getDisassembly() << " " << hex << site->GetAddress()->GetVirtualOffset() << dec << endl; - success = success && _add_buffered_receive_instrumentation(site); - } - } - - /* return an exit code */ - return success; /* success? */ -} - - -static const ARGTYPE* FindMemoryArgument(const DISASM &d) -{ - if((d.Argument1.ArgType & MEMORY_TYPE) == MEMORY_TYPE) - return &d.Argument1; - if((d.Argument2.ArgType & MEMORY_TYPE) == MEMORY_TYPE) - return &d.Argument2; - if((d.Argument3.ArgType & MEMORY_TYPE) == MEMORY_TYPE) - return &d.Argument3; - if((d.Argument4.ArgType & MEMORY_TYPE) == MEMORY_TYPE) - return &d.Argument4; - - return NULL; -} - - -static string get_memory_addr(const DISASM& d) -{ - string s=d.CompleteInstr; - size_t pos=s.find('['); - - assert(pos!=string::npos); - - s.replace(0,pos-1,""); - - pos=s.find(']'); - s.replace(pos+1,s.length(),""); - - return s; -} - -static bool has_index_register(Instruction_t* i) -{ - DISASM d; - i->Disassemble(d); - const ARGTYPE* arg=FindMemoryArgument(d); - - if(!arg) - return false; - - if(arg->Memory.Scale) - return true; - return false; - -} - -static string regToRegstring(size_t regno) -{ - switch(regno) - { - case REG0: return "eax"; - case REG1: return "ecx"; - case REG2: return "edx"; - case REG3: return "ebx"; - case REG4: return "esp"; - case REG5: return "ebp"; - case REG6: return "esi"; - case REG7: return "edi"; - default: assert(0); - } -} - -std::ostream& BuffRecv_Instrument::displayStatistics(std::ostream &os) -{ -} - -bool BuffRecv_Instrument::execute() -{ - bool success=true; - - success = success && add_buffered_receive_instrumentation(); - - return success; -} - - diff --git a/tools/cgc_buffrecv/buffrecv_instrument.hpp b/tools/cgc_buffrecv/buffrecv_instrument.hpp deleted file mode 100644 index 20353d44e..000000000 --- a/tools/cgc_buffrecv/buffrecv_instrument.hpp +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - */ - -#ifndef buffrecv_instrument_hpp -#define buffrecv_instrument_hpp - -#include <libIRDB-core.hpp> -#include <libIRDB-util.hpp> -#include <libIRDB-syscall.hpp> - -#include "elfio/elfio.hpp" -#include "elfio/elfio_dump.hpp" - -class BuffRecv_Instrument -{ - public: - BuffRecv_Instrument(libIRDB::FileIR_t *the_firp) : firp(the_firp), syscalls(firp) - { - int elfoid=firp->GetFile()->GetELFOID(); - pqxx::largeobject lo(elfoid); - libIRDB::pqxxDB_t *interface=dynamic_cast<libIRDB::pqxxDB_t*>(libIRDB::BaseObj_t::GetInterface()); - assert(interface); - lo.to_file(interface->GetTransaction(),"readeh_tmp_file.exe"); - - elfiop=new ELFIO::elfio; - elfiop->load("readeh_tmp_file.exe"); - ELFIO::dump::header(std::cout,*elfiop); - ELFIO::dump::section_headers(std::cout,*elfiop); - ELFIO::dump::segment_headers(std::cout,*elfiop); - } - virtual ~BuffRecv_Instrument() { delete elfiop; } - bool execute(); - - private: - // main tasks - bool _add_buffered_receive_instrumentation(libIRDB::Instruction_t *site); - bool add_buffered_receive_instrumentation(); - std::ostream& displayStatistics(std::ostream &os); - - private: - libIRDB::FileIR_t* firp; - libIRDB::Syscalls_t syscalls; - ELFIO::elfio* elfiop; -}; - -#endif - diff --git a/tools/cgc_hlx/Makefile.in b/tools/cgc_hlx/Makefile.in deleted file mode 100644 index 00b95db27..000000000 --- a/tools/cgc_hlx/Makefile.in +++ /dev/null @@ -1,41 +0,0 @@ - - -PROGS=selective_cfi.exe - -CXX=@CXX@ -CXXFLAGS= -INCLUDE=-I. -I../include -I../xform -I../../beaengine/include -I../../libIRDB/include/ -I../../libMEDSannotation/include/ -I../libtransform/include/ -I../transforms -CXXFLAGS= @EXTRA_CXXFLAGS@ $(INCLUDE) -Wall -LIBS=-L../../lib -lxform -lIRDB-core -lIRDB-cfg -lBeaEngine_s_d -lpqxx -lMEDSannotation -ltransform ../transforms/Rewrite_Utility.o -lpq - -OBJS=cgc_hlx.o cgc_hlx_driver.o -programs=cgc_hlx.exe - -.SUFFIXES: .o .c .exe .cpp .hpp - -all: $(programs) - @echo "---------------------------------------------" - @echo "- CGC HLX directory -- Build complete -" - @echo "---------------------------------------------" - - --include $(OBJS:.o=.d) - -%.o: %.cpp - $(CXX) -c $(CXXFLAGS) $*.cpp - @# - @# build dependencies -- http://scottmcpeak.com/autodepend/autodepend.html - @# - @cpp -MM $(CXXFLAGS) $*.cpp > $*.d - @cp -f $*.d $*.d.tmp - @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $*.d - @rm -f $*.d.tmp - -clean: - rm -f *.o core *.exe - -$(programs): ../../lib/*.a - -cgc_hlx.exe: $(OBJS) - $(CXX) $(CXXFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - diff --git a/tools/cgc_hlx/SConscript b/tools/cgc_hlx/SConscript deleted file mode 100644 index 25e348e0e..000000000 --- a/tools/cgc_hlx/SConscript +++ /dev/null @@ -1,30 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="cgc_hlx.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util MEDSannotation ") -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install) - - - -Return('install') diff --git a/tools/cgc_hlx/SConstruct b/tools/cgc_hlx/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/cgc_hlx/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/cgc_hlx/cgc_hlx.cpp b/tools/cgc_hlx/cgc_hlx.cpp deleted file mode 100644 index 0c4c84e7c..000000000 --- a/tools/cgc_hlx/cgc_hlx.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include "cgc_hlx.hpp" -#include "Rewrite_Utility.hpp" -#include <stdlib.h> - -/* -* HLX: Heap Layout Transform -* -* Pad malloc and/or allocate -* -*/ - -#define CINDERELLA_MALLOC "cinderella::malloc" -#define CINDERELLA_ALLOCATE "cinderella::allocate" -#define CINDERELLA_DEALLOCATE "cinderella::deallocate" - -using namespace std; -using namespace libIRDB; - -Function_t* HLX_Instrument::findFunction(string p_functionName) -{ - for(set<Function_t*>::iterator it=m_firp->GetFunctions().begin(); - it!=m_firp->GetFunctions().end(); - ++it) - { - Function_t* func=*it; - - if(func && func->GetName() == p_functionName) - return func; - } - - return NULL; -} - -// pad argument #1 of function, assume it's the size -bool HLX_Instrument::padSizeOnAllocation(Function_t* const p_func, const int padding, const int shr_factor) -{ - assert(p_func); - - Instruction_t *entry = p_func->GetEntryPoint(); - - if (!entry) - { - cerr << "function: " << p_func->GetName() << " has no entry point defined" << endl; - return false; - } - - cout << "padding function: " << p_func->GetName() << " at: 0x" << hex << entry->GetAddress()->GetVirtualOffset() << dec << " padding: " << padding << " shr_factor: " << shr_factor << endl; - - /* - * mov eax, [esp+4] - * shr eax, k - * add eax, p - * mov [esp+4], eax - * - * e.g.: size: 256 malloc padding: 32, shift factor = 5 - * mov eax, [esp+4] ; 256 - * shr eax, 5 ; size << 5 = 8 - * add eax, 32 ; size << 5 + 32 = 40 - * add [esp+4], eax ; size = size + size << 5 + 32 = 256 + 40 = 296 - * - * e.g.: size: 4096 padding: 4096 shift factor = 32 - * mov eax, [esp+4] ; 4096 - * shr eax, 32 ; size << 32 = 0 - * add eax, 4096 ; size << 32 + 4096 = 4096 - * add [esp+4], eax ; size = size + size << 32 + 4096 = 8192 - */ - Instruction_t* instr = NULL; - Instruction_t* orig = NULL; - - orig = insertAssemblyBefore(m_firp, entry, "mov eax, [esp+4]"); - entry->SetComment("pad malloc/allocate sequence"); - - char buf[1024]; - - if (shr_factor > 0) - { - sprintf(buf, "shr eax, %d", shr_factor); - instr = insertAssemblyAfter(m_firp, entry, buf); - } - - sprintf(buf, "add eax, %d", padding); // in bytes - - if (shr_factor > 0) - instr = insertAssemblyAfter(m_firp, instr, buf); - else - instr = insertAssemblyAfter(m_firp, entry, buf); - - instr = insertAssemblyAfter(m_firp, instr, "add [esp+4], eax"); - instr->SetFallthrough(orig); - - return true; -} - -// pad argument #2 of function, assume it's the size -bool HLX_Instrument::padSizeOnDeallocation(Function_t* const p_func, const int padding) -{ -return true; // make sure deactivated for now - assert(p_func); - - Instruction_t *entry = p_func->GetEntryPoint(); - - if (!entry) - { - cerr << "function: " << p_func->GetName() << " has no entry point defined" << endl; - return false; - } - - cout << "padding function: " << p_func->GetName() << " at: 0x" << hex << entry->GetAddress()->GetVirtualOffset() << dec << "padding: " << padding << endl; - - char buf[1024]; - - /* - * eax <-- [esp + 8] ; get the size (1st argument) - * add eax, padding ; compute new size - * add [esp+8], eax ; set to new size - */ - - Instruction_t* instr = NULL; - Instruction_t* orig = NULL; - - orig = insertAssemblyBefore(m_firp, entry, "mov eax, [esp+8]"); - entry->SetComment("pad deallocate"); - - sprintf(buf, "add eax, %d", padding); // in bytes - instr = insertAssemblyAfter(m_firp, entry, buf); - - instr = insertAssemblyAfter(m_firp, instr, "mov [esp+8], eax"); - instr->SetFallthrough(orig); - - return true; -} - -bool HLX_Instrument::execute() -{ - bool success=false; - - if (mallocPaddingEnabled()) - { - Function_t *cinderella_malloc = findFunction(CINDERELLA_MALLOC); - if (cinderella_malloc) - { - cout << "found " << CINDERELLA_MALLOC << endl; - if (padSizeOnAllocation(cinderella_malloc, getMallocPadding(), getShiftRightFactor())) - { - success = true; - cout << CINDERELLA_MALLOC << " padded successfully: " << getMallocPadding() << " bytes" << endl; - } - } - else - { - cout << CINDERELLA_MALLOC << " not found" << endl; - } - } - - if (allocatePaddingEnabled()) - { - Function_t *cinderella_allocate = findFunction(CINDERELLA_ALLOCATE); - Function_t *cinderella_deallocate = findFunction(CINDERELLA_DEALLOCATE); - - if (cinderella_allocate) - { - cout << "found " << CINDERELLA_ALLOCATE << endl; - - if (padSizeOnAllocation(cinderella_allocate, getAllocatePadding())) - { - success = true; - cout << CINDERELLA_ALLOCATE << " padded successfully: " << getAllocatePadding() << " bytes" << endl; -#ifdef DO_NOT_USE - if (cinderella_deallocate && padSizeOnDeallocation(cinderella_deallocate, getAllocatePadding())) - { - cout << "found " << CINDERELLA_DEALLOCATE << endl; - cout << CINDERELLA_DEALLOCATE << " padded successfully: " << getAllocatePadding() << " bytes" << endl; - } -#endif - } - } - else - { - cout << CINDERELLA_ALLOCATE << " not found" << endl; - } - } - - return success; -} diff --git a/tools/cgc_hlx/cgc_hlx.hpp b/tools/cgc_hlx/cgc_hlx.hpp deleted file mode 100644 index f4f9d96a6..000000000 --- a/tools/cgc_hlx/cgc_hlx.hpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the - * University of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - */ - -#ifndef hlx_hpp -#define hlx_hpp - -#include <libIRDB-core.hpp> - -#define DEFAULT_MALLOC_PADDING 64 -#define DEFAULT_SHR_FACTOR 32 -#define DEFAULT_ALLOCATE_PADDING 4096 - -class HLX_Instrument -{ - public: - HLX_Instrument(libIRDB::FileIR_t *the_firp) : - m_firp(the_firp) { - m_enable_malloc_padding = false; - m_enable_allocate_padding = false; - m_malloc_padding = 0; - m_allocate_padding = 0; - m_shr_factor = DEFAULT_SHR_FACTOR; - } - virtual ~HLX_Instrument() {} - void enableMallocPadding(const int malloc_padding, const int shr_factor=DEFAULT_SHR_FACTOR) { - m_enable_malloc_padding = true; - m_malloc_padding = malloc_padding; - m_shr_factor = shr_factor; - } - void enableAllocatePadding(const int allocate_padding, const int shr_factor=DEFAULT_SHR_FACTOR) { - m_enable_allocate_padding = true; - m_allocate_padding = allocate_padding; - } - - bool mallocPaddingEnabled() const { return m_enable_malloc_padding; } - bool allocatePaddingEnabled() const { return m_enable_allocate_padding; } - int getMallocPadding() const { return m_malloc_padding; } - int getAllocatePadding() const { return m_allocate_padding; } - - int getShiftRightFactor() const { return m_shr_factor; } - bool execute(); - - private: - libIRDB::Function_t* findFunction(std::string); - bool padSizeOnAllocation(libIRDB::Function_t* const, const int padding, const int shr_factor = 0); - bool padSizeOnDeallocation(libIRDB::Function_t* const, const int padding); - - private: - libIRDB::FileIR_t* m_firp; - bool m_enable_malloc_padding; - int m_malloc_padding; - bool m_enable_allocate_padding; - int m_allocate_padding; - int m_shr_factor; // shift right factor (for malloc) -}; - -#endif diff --git a/tools/cgc_hlx/cgc_hlx_driver.cpp b/tools/cgc_hlx/cgc_hlx_driver.cpp deleted file mode 100644 index 1fd1b2f19..000000000 --- a/tools/cgc_hlx/cgc_hlx_driver.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> -#include <getopt.h> - -#include "cgc_hlx.hpp" - -using namespace std; -using namespace libIRDB; - -#define BINARY_NAME "a.ncexe" -#define SHARED_OBJECTS_DIR "shared_objects" - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" varid=<variant_id> [--do_malloc_padding=<padding_size>] [--shr_malloc_factor=<shr_malloc_factor>] [--do_allocate_padding=<padding_size>]\n"; -} - -int varid=0; -bool enable_malloc_padding = false; -bool enable_allocate_padding = false; -int malloc_padding = DEFAULT_MALLOC_PADDING; -int shr_malloc_factor = DEFAULT_SHR_FACTOR; -int allocate_padding = DEFAULT_ALLOCATE_PADDING; - -int parse_args(int p_argc, char* p_argv[]) -{ - int option = 0; - char options[] = "v:m:a:s"; - struct option long_options[] = { - {"varid", required_argument, NULL, 'v'}, - {"do_malloc_padding", required_argument, NULL, 'm'}, - {"do_allocate_padding", required_argument, NULL, 'a'}, - {"shr_malloc_factor", required_argument, NULL, 's'}, - {NULL, no_argument, NULL, '\0'}, // end-of-array marker - }; - - while ((option = getopt_long( - p_argc, - p_argv, - options, - long_options, - NULL)) != -1) - { - printf("Found option %c\n", option); - switch (option) - { - case 'v': - { - varid=atoi(::optarg); - cout<<"Transforming variant "<<dec<<varid<<endl; - break; - } - case 'm': - { - enable_malloc_padding = true; - malloc_padding=atoi(::optarg); - break; - } - case 's': - { - shr_malloc_factor=atoi(::optarg); - break; - } - case 'a': - { - enable_allocate_padding = true; - allocate_padding=atoi(::optarg); - break; - } - default: - return 1; - } - } - return 0; -} - - -int main(int argc, char **argv) -{ - string programName(argv[0]); - if(0 != parse_args(argc,argv)) - { - usage(argv[0]); - exit(1); - } - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(varid); - assert(pidp->IsRegistered()==true); - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - cout<<"Transforming "<<this_file->GetURL()<<endl; - - assert(firp && pidp); - - try - { - HLX_Instrument hlx(firp); - - if (enable_malloc_padding) - hlx.enableMallocPadding(malloc_padding, shr_malloc_factor); - if (enable_allocate_padding) - hlx.enableAllocatePadding(allocate_padding); - - bool success = hlx.execute(); - - if (success) - { - cout << "Padding successful" << endl; - one_success = true; - firp->WriteToDB(); - delete firp; - } - else - { - cout<<"Skipping (no changes) "<<this_file->GetURL()<<endl; - } - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - // if any transforms for any files succeeded, we commit - if (one_success) - { - cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); - } - - return 0; -} - diff --git a/tools/cgc_protect/cgc_protect_one.sh b/tools/cgc_protect/cgc_protect_one.sh deleted file mode 100755 index 4179d645e..000000000 --- a/tools/cgc_protect/cgc_protect_one.sh +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/bash - -# -# Given a directory full of POVs, protect a singleton CB -# by sandboxing the appropriate instructions -# -# - -CGC_BIN=$1 # input cgc binary -CGC_PROTECTED=$2 # output(protected) cgc binary -POV_DIR=$3 # directory containing POVs - -benchmark=`basename $CGC_BIN _` -log=tmp.log.$$ - -CRASH_SITES=tmp.crashes.$$ - -# run cb-test on each POV invidually -for i in `ls ${POV_DIR}/*.xml` -do - echo "" - echo $i - - one_pov=$i - binary=`basename $CGC_BIN` - binary_dir=`dirname $CGC_BIN` - core=${binary_dir}/core - - sudo rm $core 2>/dev/null - sudo cb-test --debug --xml ${one_pov} --timeout 20 --directory ${binary_dir} --cb ${binary} --log $log - grep "core identified" $log - if [ $? -eq 0 ]; then - if [ -f $core ]; then - sudo chown `whoami` $core - eip=`$PEASOUP_HOME/tools/extract_eip_from_core.sh ${CGC_BIN} $core` - if [ $? -eq 0 ]; then - echo "$eip" >> $CRASH_SITES - fi - echo "EIP: $eip" - fi - fi - - sudo rm $core 2>/dev/null -done - -# -# sandbox all uncovered faulting instructions -# -if [ -f $CRASH_SITES ]; then - tmp=tmp.$$ - sort $CRASH_SITES | uniq > $tmp - mv $tmp $CRASH_SITES - - cso_file="crashes.cso" - rm $cso_file 2>/dev/null - - while read -r LINE || [[ -n $LINE ]]; do - echo "$benchmark,$LINE,,Tainted Dereference" >> $cso_file - done < $CRASH_SITES - - echo "CRASH SITES UNCOVERED:" - cat $cso_file - - if [ -f $cso_file ]; then - $PEASOUP_HOME/tools/ps_analyze_cgc.sh $CGC_BIN $CGC_PROTECTED --step-option watch_allocate:--warning_file=`pwd`/$cso_file - rm -fr peasoup_executable_directory* - else - exit 1 - fi -fi - -sudo rm $log 2>/dev/null -rm $CRASH_SITES 2>/dev/null - -exit 0 diff --git a/tools/cgc_protect/is_new_pov.sh b/tools/cgc_protect/is_new_pov.sh deleted file mode 100755 index 41a46ae07..000000000 --- a/tools/cgc_protect/is_new_pov.sh +++ /dev/null @@ -1,77 +0,0 @@ -#!/bin/bash - -# -# This script is invoked by crash_filter.py to determine whether a -# POV results in a new crashing instruction -# -# Returns success (0) only if the POV results in a new crash point -# Returns > 0 otherwise -# -# /techx_share/techx_umbrella/peasoup/security_transforms/tools/cgc_protect/is_new_pov.sh /home/vagrant/techx_work/0b32aa01_crash_filter/id:000049,sig:11,src:000007,op:arith8,pos:88,val:+9.10288.xml /home/vagrant/techx_work/0b32aa01_crash_filter/0b32aa01_01.crash.summary /home/vagrant/techx_work/0b32aa01_crash_filter/0b32aa01_01 -# - -POV_PATH=$1 # fully qualified path for POV -CRASH_SUMMARY=$2 # crash summary file -CGC_BIN=$3 # input cgc binary (@todo: handle multi-cbs) - -cbtest=${CGC_UMBRELLA_DIR}/scripts/techx-cb-test -timeout=20 -delimiter="###" - -log=`pwd`/tmp.log - -pov_base=`basename ${POV_PATH}` -binary=`basename $CGC_BIN` -binary_dir=`dirname $CGC_BIN` -core=${binary_dir}/core - -# if the pov is already in the crash summary file, then we've seen it before -tmp=`grep -F "${pov_base}${delimiter}" ${CRASH_SUMMARY}` -if [ $? -eq 0 ]; then - exit 2 -fi - -# cleanup any stale core files -if [ -f $core ]; then - sudo rm $core &>/dev/null -fi - -# invoke techx-cb-test in an attempt to get a core file -# @todo: input.py has already run the input... at some point we should just -# have input.py record the crashing instruction so that we don't have -# to re-run the pov here -echo "sudo -E $cbtest --debug --xml ${POV_PATH} --timeout $timeout --directory ${binary_dir} --cb ${binary} --log $log" -sudo -E $cbtest --debug --xml ${POV_PATH} --timeout $timeout --directory ${binary_dir} --cb ${binary} --log $log -grep "core identified" $log -if [ $? -eq 0 ]; then - if [ -f $core ]; then - echo "is_new_pov.sh: core file found" - sudo chown `whoami` $core - eip=`timeout $timeout $PEASOUP_HOME/tools/extract_eip_from_core.sh ${CGC_BIN} $core` - if [ $? -eq 0 ]; then - tmp=`grep -F "${delimiter}$eip" ${CRASH_SUMMARY}` - if [ $? -eq 0 ]; then - echo "${pov_base}${delimiter}${eip}" >> ${CRASH_SUMMARY} - exit 1 - else - # new crash instruction, add to summary file - echo "${pov_base}${delimiter}${eip}" >> ${CRASH_SUMMARY} - exit 0 - fi - else - # cannot extract eip - echo "${pov_base}${delimiter}0x0" >> ${CRASH_SUMMARY} - exit 1 - fi - - sudo rm $core &>/dev/null - else - # core file identified, but no core file found - echo "${pov_base}${delimiter}0x0" >> ${CRASH_SUMMARY} - exit 1 - fi -else - # no core file identified at all - echo "${pov_base}${delimiter}0x0" >> ${CRASH_SUMMARY} - exit 1 -fi diff --git a/tools/cgc_protect/pov_to_cso.sh b/tools/cgc_protect/pov_to_cso.sh deleted file mode 100755 index ae2e5013a..000000000 --- a/tools/cgc_protect/pov_to_cso.sh +++ /dev/null @@ -1,156 +0,0 @@ -#!/bin/bash - -# -# Given a directory full of POVs, protect a singleton CB -# by sandboxing the appropriate instructions -# - -CGC_BIN=$1 # input cgc binary -CGC_CSID=$2 # cgc name -POV_DIR=$3 # directory containing POVs -CSO_FILE=$4 # output: CSO warning file suitable for sandboxing step -POV_CRASH_SUMMARY_FILE=$5 # input/output: POV/raw inputs-->crash summary file -CRASH_DIR=$6 # directory with raw crashing inputs -INPUT_CRASH_SUMMARY_FILE=$7 # input/output: POV/raw inputs-->crash summary file -CRASH_SITES=$8 # list of crash sites - -timeout=20 -local_crash_summary=tmp.crash.summary.$$ -log=`pwd`/tmp.log.$$ - -cbtest=$CGC_UMBRELLA_DIR/scripts/techx-cb-test - -delimiter="###" - - -ulimit -c unlimited - -# copy the crash summary file locally -cp $POV_CRASH_SUMMARY_FILE $local_crash_summary -cat $INPUT_CRASH_SUMMARY_FILE >> $local_crash_summary - -# run cb-test on each POV invidually -# not used for CQE -if [ -d ${POV_DIR} ]; then - -for i in `ls ${POV_DIR}/*.xml` -do - echo "" - echo $i - - one_pov=$i - pov_base=`basename $one_pov` - - binary=`basename $CGC_BIN` - binary_dir=`dirname $CGC_BIN` - core=${binary_dir}/core - - # lookup pov - tmp=`grep -F "${pov_base}" $local_crash_summary` - if [ $? -eq 0 ];then - eip=`echo $tmp | awk -F"${delimiter}" '{print $2}'` - echo $eip | grep "0x0" - if [ ! $? -eq 0 ]; then - echo "$eip" >> $CRASH_SITES - fi - echo "Found pov: ${pov_base} in cache -- eip = $eip" - continue - else - echo "POV ${pov_base} not found in cache -- attempt to extract crashing instruction" - fi - - # cleanup any stale core files - if [ -f $core ]; then - sudo rm $core 2>/dev/null - fi - - echo "sudo -E $cbtest --debug --xml ${one_pov} --timeout $timeout --directory ${binary_dir} --cb ${binary} --log $log" - sudo -E $cbtest --debug --xml ${one_pov} --timeout $timeout --directory ${binary_dir} --cb ${binary} --log $log - grep "core identified" $log - if [ $? -eq 0 ]; then - if [ -f $core ]; then - echo "pov_to_cso.sh: core file found" - sudo chown `whoami` $core - eip=`timeout $timeout $PEASOUP_HOME/tools/extract_eip_from_core.sh ${CGC_BIN} $core` - if [ $? -eq 0 ]; then - echo "$eip" >> $CRASH_SITES - echo "${pov_base}${delimiter}${eip}" >> $local_crash_summary - else - echo "${pov_base}${delimiter}0x0" >> $local_crash_summary - fi - - sudo rm $core 2>/dev/null - else - echo "pov_to_cso.sh: cannot find core file" - echo "${pov_base}${delimiter}0x0" >> $local_crash_summary - fi - else - echo "${pov_base}${delimiter}0x0" >> $local_crash_summary - fi -done - -fi - -# -# Extract crash sites from crashing input dir (if any) -# -if [ -d $CRASH_DIR ]; then - echo "crash directory was specified: $CRASH_DIR" - for i in `ls ${CRASH_DIR}/*` - do - # lookup crash input - crash_base=`basename ${i}` - tmp=`grep -F "${crash_base}${delimiter}" $local_crash_summary` - if [ $? -eq 0 ];then - eip=`echo $tmp | awk -F"${delimiter}" '{print $2}'` - echo $eip | grep "0x0" - if [ ! $? -eq 0 ]; then - echo "$eip" >> $CRASH_SITES - fi - echo "Found crash: ${crash_base} in cache -- eip = $eip" - continue - else - echo "crashing input ${crash_base} not found in cache -- attempt to extract crashing instruction" - fi - - eip=`timeout $timeout ${PEASOUP_HOME}/tools/replay_with_gdb.sh ${CGC_BIN} ${i}` - if [ $? -eq 0 ]; then - # segmentation fault detected and valid eip - echo "detected valid crash site: $eip" - echo $eip >> $CRASH_SITES - echo "${crash_base}${delimiter}${eip}" >> $local_crash_summary - else - echo "no valid crash site detected: $eip" - echo "${crash_base}${delimiter}0x0" >> $local_crash_summary - fi - done -fi - -# local_crash_summary should have a list of all potential crash sites -# extract all the instructions to sandbox -grep "${delimiter}" $local_crash_summary | awk -F"${delimiter}" '{print $2}' | sort | uniq >> $CRASH_SITES - -# -# generate policy file for input to sandboxing step -# - -if [ -f $CRASH_SITES ]; then - # format: 0x<address_in_hex> - tmp=tmp.$$ - grep -v "0x0\$" $CRASH_SITES | egrep '^0x[a-fA-F0-9]+$' | sort | uniq > $tmp - mv $tmp $CRASH_SITES - - while read -r LINE || [[ -n $LINE ]]; do - echo "$CGC_CSID,$LINE,,Tainted Dereference" >> $CSO_FILE - done < $CRASH_SITES -fi - -# mv crash summary file out -sort $local_crash_summary | uniq > tmp.$$ -mv tmp.$$ ${INPUT_CRASH_SUMMARY_FILE} - -sudo rm $log 2>/dev/null -#rm $CRASH_SITES 2>/dev/null -killall `basename $CGC_BIN` - -exit 0 diff --git a/tools/cgc_rigrandom/Makefile.in b/tools/cgc_rigrandom/Makefile.in deleted file mode 100644 index 798b826d4..000000000 --- a/tools/cgc_rigrandom/Makefile.in +++ /dev/null @@ -1,42 +0,0 @@ - - - -CXX=@CXX@ -CXXFLAGS= -INCLUDE=-I. -I../include -I../xform -I../../beaengine/include -I../../libIRDB/include/ -I../../libMEDSannotation/include/ -I../libtransform/include/ -I../transforms -CXXFLAGS= @EXTRA_CXXFLAGS@ $(INCLUDE) -LIBS=-L../../lib -lxform -lIRDB-core -lIRDB-cfg -lBeaEngine_s_d -lpqxx -lMEDSannotation -ltransform ../transforms/Rewrite_Utility.o -lpq - - -OBJS=rigrandom_driver.o rigrandom_instr.o -programs=rigrandom.exe - -.SUFFIXES: .o .c .exe .cpp .hpp - -all: $(programs) - @echo "-----------------------------------" - @echo "- cgc_rigrandom directory -- Build complete -" - @echo "-----------------------------------" - - --include $(OBJS:.o=.d) - -%.o: %.cpp - $(CXX) -c $(CXXFLAGS) $*.cpp - @# - @# build dependencies -- http://scottmcpeak.com/autodepend/autodepend.html - @# - @cpp -MM $(CXXFLAGS) $*.cpp > $*.d 2> /dev/null || true # might fail on solaris with CXX=sun's CC. - @cp -f $*.d $*.d.tmp - @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $*.d - @rm -f $*.d.tmp - -clean: - rm -f *.o core *.exe - -$(programs): ../../lib/*.a - -$(programs): $(OBJS) - $(CXX) $(CXXFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - cp $@ ${SECURITY_TRANSFORMS_HOME}/plugins_install/ - diff --git a/tools/cgc_rigrandom/SConscript b/tools/cgc_rigrandom/SConscript deleted file mode 100644 index 0f3f9e16e..000000000 --- a/tools/cgc_rigrandom/SConscript +++ /dev/null @@ -1,32 +0,0 @@ -import os - -print 'cwd='+os.getcwd() - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - -#CFLAGS="-fPIC " - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="rigrandom.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util ") - -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install) - -Return('install') diff --git a/tools/cgc_rigrandom/SConstruct b/tools/cgc_rigrandom/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/cgc_rigrandom/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/cgc_rigrandom/rigrandom_driver.cpp b/tools/cgc_rigrandom/rigrandom_driver.cpp deleted file mode 100644 index d2c8d9154..000000000 --- a/tools/cgc_rigrandom/rigrandom_driver.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "rigrandom_instr.hpp" - -using namespace std; -using namespace libIRDB; - -void usage(char* name) -{ - cerr<<"Usage: " << name << " <variant_id> <random_byte>\n"; -} - -int main(int argc, char **argv) -{ - if (argc != 3) - { - usage(argv[0]); - exit(1); - } - - string programName(argv[0]); - int variantID = atoi(argv[1]); - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - cout << argv[0] << " started with 'random' byte " << argv[2][0] << "\n"; - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - cout << "Transforming " << this_file->GetURL() << endl; - - assert(firp && pidp); - - try - { - RigRandom_Instrument rri(firp, argv[2][0]); - int success = rri.execute(); - - if (success) - { - cout<<"Writing changes for "<<this_file->GetURL()<<endl; - one_success = true; - firp->WriteToDB(); - delete firp; - } - else - { - cout<<"Skipping (no changes) "<<this_file->GetURL()<<endl; - } - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - // if any integer transforms for any files succeeded, we commit - if (one_success) - { - cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); - } - - return 0; -} diff --git a/tools/cgc_rigrandom/rigrandom_instr.cpp b/tools/cgc_rigrandom/rigrandom_instr.cpp deleted file mode 100644 index bac01cdbc..000000000 --- a/tools/cgc_rigrandom/rigrandom_instr.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include "utils.hpp" -#include "rigrandom_instr.hpp" -#include "Rewrite_Utility.hpp" -#include <stdlib.h> -#include <sstream> - -using namespace std; -using namespace libIRDB; - -static Instruction_t* addNewAssembly(FileIR_t* firp, Instruction_t *p_instr, string p_asm) -{ - Instruction_t* newinstr; - if (p_instr) - newinstr = allocateNewInstruction(firp,p_instr->GetAddress()->GetFileID(), p_instr->GetFunction()); - else - newinstr = allocateNewInstruction(firp,BaseObj_t::NOT_IN_DATABASE, NULL); - - firp->RegisterAssembly(newinstr, p_asm); - - if (p_instr) - { - newinstr->SetFallthrough(p_instr->GetFallthrough()); - p_instr->SetFallthrough(newinstr); - } - - return newinstr; -} - -Instruction_t* RigRandom_Instrument::insertRandom(Instruction_t* after) -{ -/* - d: 85 d2 test %ecx,%ecx -J1: 7e 11 jle L4 - 11: b8 00 00 00 00 mov $0x0,%eax -L3: 88 04 01 mov [%ebx+%eax*1], 0x41 (or passed-in value) - 19: 83 c0 01 add $0x1,%eax - 1c: 39 d0 cmp %ecx,%eax -J2: 75 f6 jne L3 - 20: eb 05 jmp L2 -L4: ba 00 00 00 00 mov $0x0,%ecx -L2: 85 db test %edx,%edx -J3: 74 02 je L1 - 2b: 89 13 mov %ecx,(%edx) -L1: b8 00 00 00 00 mov $0x0,%eax -*/ - - Instruction_t *J1=NULL, *J2=NULL, *J3=NULL, *L1=NULL, *L2=NULL, *L3=NULL, *L4=NULL; - - after=insertAssemblyAfter(firp, after, "test ecx, ecx"); - J1=after=insertAssemblyAfter(firp, after, "jle 0x0"); - after=insertAssemblyAfter(firp, after, "mov eax, 0"); - - // user-selected random sequence - stringstream ss; - ss << "mov [ebx+eax], byte 0x" << std::hex << (int) random_start << std::dec; - L3=after=insertAssemblyAfter(firp, after, ss.str().c_str()); - - after=insertAssemblyAfter(firp, after, "add eax, 1"); - after=insertAssemblyAfter(firp, after, "cmp eax, ecx"); - J2=after=insertAssemblyAfter(firp, after, "jne 0x0"); - - L4=after=insertAssemblyAfter(firp, after, "mov ecx, 0"); - L2=after=insertAssemblyAfter(firp, after, "test edx, edx"); - J3=after=insertAssemblyAfter(firp, after, "je 0x0"); - after=insertAssemblyAfter(firp, after, "mov [edx], ecx"); - L1=after=insertAssemblyAfter(firp, after, "mov eax, 0"); - - J1->SetTarget(L4); - J2->SetTarget(L3); - J2->SetFallthrough(L2); - J3->SetTarget(L1); - - return after; -} - -bool RigRandom_Instrument::add_rr_instrumentation(libIRDB::Instruction_t* insn) -{ - assert(insn); - cout<<"Adding CGC->Elf instrumentation for "<<insn->GetBaseID()<<":"<<insn->getDisassembly()<<endl; - - Instruction_t* tmp=insn; - Instruction_t* randomjmp=NULL, *randominsn=NULL; - Instruction_t* old=insn; - Instruction_t* failinsn=NULL; - - old=insertAssemblyBefore(firp,tmp,"cmp eax, 7"); // terminate - randominsn=tmp; - randomjmp=tmp=insertAssemblyAfter(firp,tmp,"jne 0"); - tmp=insertRandom(tmp); - tmp->SetFallthrough(old); - failinsn=tmp=addNewAssembly(firp,NULL,"mov eax, 13"); // fail - failinsn->SetFallthrough(old); - - randomjmp->SetTarget(failinsn); - - // nop - string bits; - bits.resize(1); - bits[0]=0x90; - old->SetDataBits(bits); - - return true; -} - -bool RigRandom_Instrument::needs_rr_instrumentation(libIRDB::Instruction_t* insn) -{ - // instrument int instructions - DISASM d; - insn->Disassemble(d); - return strstr(d.CompleteInstr,"int")!=0; -} - -bool RigRandom_Instrument::instrument_ints() -{ - bool success=true; - - // only instrument syscall to random - bool eax_7=false; - for(InstructionSet_t::iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); - ++it) - { - Instruction_t* insn=*it; - DISASM d; - insn->Disassemble(d); - if (strstr(d.Instruction.Mnemonic,"mov") != 0 && - strstr(d.Argument1.ArgMnemonic, "eax") != 0 && - strstr(d.Argument2.ArgMnemonic, "00000007") != 0) - eax_7 = true; - if (eax_7 && strstr(d.CompleteInstr,"int") != 0) - { - success = success && add_rr_instrumentation(insn); - eax_7 = false; - } - - } - - return success; -} - - - -bool RigRandom_Instrument::execute() -{ - bool success=true; - - success = success && instrument_ints(); - - return success; -} diff --git a/tools/cgc_rigrandom/rigrandom_instr.hpp b/tools/cgc_rigrandom/rigrandom_instr.hpp deleted file mode 100644 index 0090558ea..000000000 --- a/tools/cgc_rigrandom/rigrandom_instr.hpp +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#ifndef rigrandom_instrument_hpp -#define rigrandom_instrument_hpp - -#include <libIRDB-core.hpp> - -#include <syscall.h> - - - -class RigRandom_Instrument -{ - public: - RigRandom_Instrument(libIRDB::FileIR_t *the_firp, char random_start='A') : firp(the_firp), random_start(random_start) {} - bool execute(); - - private: - - libIRDB::Instruction_t* insertRandom(libIRDB::Instruction_t* after) ; - - bool add_rr_instrumentation(libIRDB::Instruction_t* insn); - bool needs_rr_instrumentation(libIRDB::Instruction_t* insn); - - bool instrument_ints(); - - libIRDB::FileIR_t* firp; - char random_start; -}; - -#endif - diff --git a/tools/cgclibc/Makefile b/tools/cgclibc/Makefile deleted file mode 100644 index c42ae4024..000000000 --- a/tools/cgclibc/Makefile +++ /dev/null @@ -1,49 +0,0 @@ -CC=g++ -CFLAGS= -g -Wall -DCGC -INCLUDE=-I. -I../include -I../xform -I../../beaengine/include -I../../libIRDB/include/ -I../../libMEDSannotation/include/ -I../libtransform/include/ -I../transforms -I../../include -LIBS=-L../../lib -lxform -lIRDB-core -lIRDB-cfg -lIRDB-util -lIRDB-syscall -lBeaEngine_s_d -lpqxx -lMEDSannotation -ltransform ../transforms/Rewrite_Utility.o - -program=display_functions.exe -program2=cgclibc.exe -program3=infer_syscall_wrappers.exe - -all: $(program) $(program2) $(program3) - @echo "-----------------------------------------------" - @echo "- CGC libc static inference engine -- Build complete -" - @echo "-----------------------------------------------" - -OBJS=cgclibc.o cgclibc_driver.o -OBJS2=display_functions.o cgclibc.o -OBJS3=infer_syscall_wrappers.o cgclibc.o - -.SUFFIXES: .o .c .exe .cpp .hpp - --include $(OBJS:.o=.d) - -%.o: %.cpp - $(CC) $(INCLUDE) $(CFLAGS) -c $< - @# - @# build dependencies -- http://scottmcpeak.com/autodepend/autodepend.html - @# -# $(CC) -MM $(INCLUDE) $(CFLAGS) $*.cpp > $*.d -# @cp -f $*.d $*.d.tmp -# @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $*.d -# @rm -f $*.d.tmp - - -clean: - rm -f *.o core *.exe *.d - -#$(program): ../../lib/*.a -#$(program): $(OBJS) -# $(CC) $(CFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - -cgclibc.exe: $(OBJS) ../../lib/*.a - $(CC) $(CFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - -display_functions.exe: $(OBJS2) ../../lib/*.a - $(CC) $(CFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - -infer_syscall_wrappers.exe: $(OBJS3) ../../lib/*.a - $(CC) $(CFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - diff --git a/tools/cgclibc/README b/tools/cgclibc/README deleted file mode 100644 index a0b858bdb..000000000 --- a/tools/cgclibc/README +++ /dev/null @@ -1,58 +0,0 @@ -Identification of malloc() + other libc functions -(not focussing on free right now) - -20150307 - -Legend: -Static M/F: static determination of candidates for malloc/free - +Dyn: add dynamic testing of malloc - +Dom: add simple dominator heuristic - +Clus: add clustering heuristic (malloc and free have to share a global) - - Static <==Static + Dyanmic==> -Test name Result M/F +Dyn +Dom +Clus Comments -------------- ------ ----- ---- ------- ------ --------- -CADET_00001 PASS 0/0 No malloc/free -EAGLE_00004_1 PASS 0/0 No malloc/free -EAGLE_00004_2 PASS 0/0 No malloc/free -EAGLE_00004_3 PASS 0/0 No malloc/free -KPRCA_00001 PASS 6/7 1/7 true malloc found -KPRCA_00003 PASS 1/2 true malloc found -KPRCA_00015 PASS 1/2 true malloc found -LUNGE_00002 PASS 3/3 2/2 1/2 true malloc found -LUNGE_00005_1 PASS 6/2 1/2 true malloc found -LUNGE_00005_2 PASS 5/2 2/2 1/1 true malloc found -LUNGE_00005_3 PASS 4/2 2/2 1/1 true malloc found -LUNGE_00005_4 PASS 5/2 2/2 1/1 true malloc found -LUNGE_00005_5 PASS 4/2 2/2 1/1 true malloc found -LUNGE_00005_6 PASS 4/2 2/2 1/1 true malloc found -NRFIN_00003 PASS 2/0 0/0 No malloc/free -NRFIN_00010 PASS 12/6 0/6 No malloc/free (uses allocate()/deallocate() directly) -NRFIN_00013 PASS 4/0 0/0 No malloc/free (uses allocate() directly) -TNETS_00002 PASS 9/11 5/11 3/6 1/1 true malloc found -YAN01_00001 PASS 0/0 No malloc/free -YAN01_00002 PASS 0/0 No malloc/free -YAN01_00003 PASS 0/0 No malloc/free - -Example testing for functions besides malloc - -TNETS02 inference examples -Some stats: -#functions in TNETS02 : 94 -#libc functions to infer: 17 -cinderella run-time : 10mns 30secs - (6.7sec per function in TNETS02) - -libc functions successfully inferred: -prince positive malloc malloc -prince positive strdup strdup -prince positive strlen strlen -prince positive strlcpy strlcpy -prince positive strlcat strlcat -prince positive strcmp strcmp -prince positive strncmp strncmp -prince positive strchr strchr -prince positive strtok strtok -prince positive strspn strspn -prince positive strcspn strcspn -prince positive memset memset diff --git a/tools/cgclibc/SConscript b/tools/cgclibc/SConscript deleted file mode 100644 index af9fc6ccf..000000000 --- a/tools/cgclibc/SConscript +++ /dev/null @@ -1,44 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - -myenv.Append(CCFLAGS="-DCGC") - -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -cgclibc=myenv.Object("cgclibc.cpp") -files1=Split("cgclibc_driver.cpp")+cgclibc -files2=Split("display_functions.cpp")+cgclibc -files3=Split("infer_syscall_wrappers.cpp")+cgclibc - - - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split(env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-syscall IRDB-util ") - -pgm=myenv.Program("cgclibc.exe", files1, LIBPATH=LIBPATH, LIBS=LIBS) -install1=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install1) - -pgm=myenv.Program("display_functions.exe", files2, LIBPATH=LIBPATH, LIBS=LIBS) -install2=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install2) - -pgm=myenv.Program("infer_syscall_wrappers.exe", files3, LIBPATH=LIBPATH, LIBS=LIBS) -install3=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install3) - -ret=[] + lib1 + lib2 + lib3; - -Return('ret') diff --git a/tools/cgclibc/SConstruct b/tools/cgclibc/SConstruct deleted file mode 100644 index 44d3bd9e8..000000000 --- a/tools/cgclibc/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -ret=SConscript("SConscript") -Return('ret') diff --git a/tools/cgclibc/cgclibc.cpp b/tools/cgclibc/cgclibc.cpp deleted file mode 100644 index 104fc27c7..000000000 --- a/tools/cgclibc/cgclibc.cpp +++ /dev/null @@ -1,888 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include <set> -#include <iostream> - -#include "cgclibc.hpp" - -using namespace std; - -// WARNING: DO NOT CHANGE FORMAT OF OUTPUT -void CGC_libc::emitFunctionInfo(Function_t *p_fn) -{ - if (p_fn && p_fn->GetEntryPoint() && p_fn->GetEntryPoint()->GetAddress()) - { - cout << "function " << p_fn->GetName() << " 0x" << hex << p_fn->GetEntryPoint()->GetAddress()->GetVirtualOffset() << dec << endl; - } -} - -// format of file -// <test> positive <libc_function> <candidate_function> -// -// post: m_mallocUniverse will contains the relevant candidate functions -void CGC_libc::setPositiveInferences(std::string p_positiveFile) -{ - ifstream pin(p_positiveFile.c_str(), std::ifstream::in); - while (!pin.eof()) - { - char buf[2024]; - char libcFn[2024]; - char candidateFn[2024]; - - if (pin.getline(buf, 2000)) - { - sscanf(buf,"%*s %*s %s %s", libcFn, candidateFn); - cout << "fn: " << libcFn << endl; - - if (strcmp(libcFn,"malloc")==0) - { - set<Function_t*>::iterator it; - for (it = m_firp->GetFunctions().begin(); it != m_firp->GetFunctions().end(); ++it) - { - Function_t *fn = *it; - if (fn && fn->GetName() == string(candidateFn)) - { - m_mallocUniverse.insert(m_cg.FindNode(fn)); - } - } - } - } - } - - pin.close(); -} - -// format of file -// <test> negative <libc_function> <candidate_function> -// -// post: m_mallocNegativeUniverse set -void CGC_libc::setNegativeInferences(std::string p_negativeFile) -{ - ifstream pin(p_negativeFile.c_str(), std::ifstream::in); - while (!pin.eof()) - { - char buf[2024]; - char libcFn[2024]; - char candidateFn[2024]; - - if (pin.getline(buf, 2000)) - { - sscanf(buf,"%*s %*s %s %s", libcFn, candidateFn); - cout << "fn: " << libcFn << endl; - - if (strcmp(libcFn,"malloc")==0) - { - set<Function_t*>::iterator it; - for (it = m_firp->GetFunctions().begin(); it != m_firp->GetFunctions().end(); ++it) - { - Function_t *fn = *it; - if (fn && fn->GetName() == string(candidateFn)) - { - cout << fn->GetName() << " cannot be malloc()" << endl; - m_mallocNegativeUniverse.insert(m_cg.FindNode(fn)); - } - } - } - } - } - - pin.close(); -} - -void CGC_libc::displayAllFunctions() -{ - FunctionSet_t &functions = m_firp->GetFunctions(); - for (set<Function_t*>::iterator i = functions.begin(); i != functions.end(); ++i) - { - Function_t *fn = *i; - if (!fn) continue; - emitFunctionInfo(fn); - } -} - -static void emitCandidate(std::string str, Function_t *p_fn) -{ - if (p_fn && p_fn->GetEntryPoint() && p_fn->GetEntryPoint()->GetAddress()) - { - cout << "static positive " << str << " " << p_fn->GetName() << " 0x" << hex << p_fn->GetEntryPoint()->GetAddress()->GetVirtualOffset() << dec << " " << endl; - } -} - -static void displayFinalInference(Callgraph_t &p_cg, CallGraphNodeSet_t &p_maybes, string p_funcName) -{ - for (CallGraphNodeSet_t::iterator i = p_maybes.begin(); i != p_maybes.end(); ++i) - { - CallGraphNode_t *node = *i; - if (node->IsHellnode()) continue; - - Function_t *fn = node->GetFunction(); - if (!fn) continue; - emitCandidate(p_funcName, fn); - } -} - -static void displayMaybes(Callgraph_t &p_cg, CallGraphNodeSet_t& p_maybes, string p_funcName) -{ - for (CallGraphNodeSet_t::iterator i = p_maybes.begin(); i != p_maybes.end(); ++i) - { - CallGraphNode_t *n = *i; - if (n->IsHellnode()) continue; - Function_t *fn = n->GetFunction(); - if (fn && fn->GetEntryPoint() && fn->GetEntryPoint()->GetAddress()) - { - cout << "maybe " << p_funcName << " 0x" << hex << fn->GetEntryPoint()->GetAddress()->GetVirtualOffset() << dec << " " << fn->GetName() << " args: " << fn->GetNumArguments() << endl; - } - } -} - -static void displayMaybes(Callgraph_t &p_cg, set<Function_t*> &p_maybes, string p_funcName) -{ - // obsolete? - for (set<Function_t*>::iterator i = p_maybes.begin(); i != p_maybes.end(); ++i) - { - Function_t *fn = *i; - if (fn && fn->GetEntryPoint() && fn->GetEntryPoint()->GetAddress()) - { - cout << "maybe " << p_funcName << " 0x" << hex << fn->GetEntryPoint()->GetAddress()->GetVirtualOffset() << dec << " " << fn->GetName() << endl; - } - } -} - -CGC_libc::CGC_libc(FileIR_t *p_firp) : - m_syscalls(p_firp) -{ - m_skipHellNode = false; - m_clustering = false; - m_dominance = false; - - m_firp = p_firp; - m__terminateWrapper = NULL; - m_transmitWrapper = NULL; - m_receiveWrapper = NULL; - m_fdwaitWrapper = NULL; - m_allocateWrapper = NULL; - m_deallocateWrapper = NULL; - m_randomWrapper = NULL; - - m_cg.AddFile(m_firp); - m_cg.Dump(cout); - - int elfoid=m_firp->GetFile()->GetELFOID(); - pqxx::largeobject lo(elfoid); - libIRDB::pqxxDB_t *interface=dynamic_cast<libIRDB::pqxxDB_t*>(libIRDB::BaseObj_t::GetInterface()); - assert(interface); - lo.to_file(interface->GetTransaction(),"tmp.exe"); - - m_elfiop=new ELFIO::elfio; - m_elfiop->load("tmp.exe"); -} - -void CGC_libc::findSyscallWrappers() -{ - SyscallSiteSet_t sites = m_syscalls.GetSyscalls(); - - FunctionSet_t f_terminate; - FunctionSet_t f_transmit; - FunctionSet_t f_receive; - FunctionSet_t f_fdwait; - FunctionSet_t f_allocate; - FunctionSet_t f_deallocate; - FunctionSet_t f_random; - - set<SyscallSite_t>::iterator it; - for (it = sites.begin(); it != sites.end(); ++it) - { - SyscallSite_t site = *it; - Function_t* fn = site.GetSite()->GetFunction(); - - if (!fn) continue; - - switch (site.GetSyscallNumber()) - { - case SNT_terminate: - f_terminate.insert(fn); - break; - case SNT_transmit: - f_transmit.insert(fn); - break; - case SNT_receive: - f_receive.insert(fn); - break; - case SNT_fdwait: - f_fdwait.insert(fn); - break; - case SNT_allocate: - f_allocate.insert(fn); - break; - case SNT_deallocate: - f_deallocate.insert(fn); - break; - case SNT_random: - f_random.insert(fn); - break; - } - } - - if (f_terminate.size() == 1) - { - FunctionSet_t::iterator fi = f_terminate.begin(); - if (*fi) - m__terminateWrapper = m_cg.FindNode(*fi); - } - - if (f_transmit.size() == 1) - { - FunctionSet_t::iterator fi = f_transmit.begin(); - if (*fi) - m_transmitWrapper = m_cg.FindNode(*fi); - } - - if (f_receive.size() == 1) - { - FunctionSet_t::iterator fi = f_receive.begin(); - if (*fi) - m_receiveWrapper = m_cg.FindNode(*fi); - } - - if (f_fdwait.size() == 1) - { - FunctionSet_t::iterator fi = f_fdwait.begin(); - if (*fi) - m_fdwaitWrapper = m_cg.FindNode(*fi); - } - - if (f_random.size() == 1) - { - FunctionSet_t::iterator fi = f_random.begin(); - if (*fi) - m_randomWrapper = m_cg.FindNode(*fi); - } - - if (f_allocate.size() == 1) - { - FunctionSet_t::iterator fi = f_allocate.begin(); - if (*fi) - { - m_allocateWrapper = m_cg.FindNode(*fi); - m_cg.GetAncestors(m_allocateWrapper, m_maybeMallocs, m_skipHellNode); - } - } - - if (f_deallocate.size() == 1) - { - FunctionSet_t::iterator fi = f_deallocate.begin(); - if (*fi) - { - m_deallocateWrapper = m_cg.FindNode(*fi); - m_cg.GetAncestors(m_deallocateWrapper, m_maybeFrees, m_skipHellNode); - } - } -} - -bool CGC_libc::potentialMallocFunctionPrototype(Function_t *p_fn) -{ - // conservatively rely only on the number of arguments - return (p_fn && p_fn->GetNumArguments() == 1) ? true : false; - -/* - if (p_fn && p_fn->GetNumArguments() == 1) - { - FuncType_t* ftype = p_fn->GetType(); - if (!ftype) return true; - - AggregateType_t* aggtype = ftype->GetArgumentsType(); - if (!aggtype) return true; - - Type_t *t = aggtype->GetAggregatedType(0); - if (!t) return true; - - cout << " type id: " << t->GetTypeID() << " / " << t->GetName() << endl; - if (t->IsUnknownType() || t->IsNumericType() || t->IsBasicType()) - return true; - else - return false; - } - - return false; -*/ -} - -bool CGC_libc::potentialFreeFunctionPrototype(Function_t *p_fn) -{ - // conservatively rely only on the number of arguments - return (p_fn && p_fn->GetNumArguments() == 1) ? true : false; - -/* - if (p_fn && p_fn->GetNumArguments() == 1) - { - FuncType_t* ftype = p_fn->GetType(); - if (!ftype) return true; - - AggregateType_t* aggtype = ftype->GetArgumentsType(); - if (!aggtype) return true; - - Type_t *t = aggtype->GetAggregatedType(0); - if (!t) return true; - - cout << " type id: " << t->GetTypeID() << " / " << t->GetName() << endl; - if (t->IsUnknownType() || t->IsPointerType()) - return true; - else - return false; - } - - return false; -*/ -} - -void CGC_libc::pruneMallocs() -{ - // remove functions that cannot be malloc() - // malloc() won't call transmit, receive, fdwait, even indirectly - // should have the right function prototype: POINTER malloc(NUMERIC) - - // make a copy - CallGraphNodeSet_t t = m_maybeMallocs; - - for (CallGraphNodeSet_t::iterator i = t.begin(); i != t.end(); ++i) - { - CallGraphNode_t* node = *i; - if (node->IsHellnode()) - { - m_maybeMallocs.erase(node); - continue; - } - - Function_t *fn = node->GetFunction(); - - if (fn == NULL) { - continue; - } - -cout << "Looking at function: 0x" << hex << fn << dec << endl; -cout << "Function name: " << fn->GetName() << endl; - - // m_mallocUniverse has candidate set of all mallocs - // (determined dynamically) - if (m_mallocUniverse.size() > 0 && m_mallocUniverse.count(node) == 0) - { - m_maybeMallocs.erase(node); - continue; - } - - if (m_mallocNegativeUniverse.count(node) > 0) - { - m_maybeMallocs.erase(node); - continue; - } - - if (m_cg.GetCalleesOfNode(m_transmitWrapper).count(node) > 0) - { - cout << "calls transmit, remove" << endl; - m_maybeMallocs.erase(node); - continue; - } - - if (m_cg.GetCalleesOfNode(m_receiveWrapper).count(node) > 0) - { - cout << "calls receive, remove" << endl; - m_maybeMallocs.erase(node); - continue; - } - - if (m_cg.GetCalleesOfNode(m_fdwaitWrapper).count(node) > 0) - { - cout << "calls fdwait, remove" << endl; - m_maybeMallocs.erase(node); - continue; - } - - cout << fn->GetName() << " has " << fn->GetNumArguments() << " arguments" << endl; - if (!potentialMallocFunctionPrototype(fn)) - { - m_maybeMallocs.erase(node); - continue; - } - } -} - -void CGC_libc::pruneFrees() -{ - // (2) remove functions that cannot be free() - // free() won't call transmit, receive, fdwait, even indirectly - // should have the right function prototype: void free(POINTER) - CallGraphNodeSet_t t = m_maybeFrees; - CallGraphNodeSet_t::iterator i; - - for (i = t.begin(); i != t.end(); ++i) - { - CallGraphNode_t *node = *i; - - if (node->IsHellnode()) - { - m_maybeFrees.erase(node); - continue; - } - - Function_t *fn = node->GetFunction(); - - if (!fn) continue; - -cout << "Looking at function: " << fn->GetName() << endl; - - if (m_cg.GetCalleesOfNode(m_transmitWrapper).count(node) > 0) - { - cout << "calls transmit, remove" << endl; - m_maybeFrees.erase(node); - continue; - } - - if (m_cg.GetCalleesOfNode(m_receiveWrapper).count(node) > 0) - { - cout << "calls receive, remove" << endl; - m_maybeFrees.erase(node); - continue; - } - - if (m_cg.GetCalleesOfNode(m_fdwaitWrapper).count(node) > 0) - { - cout << "calls fdwait, remove" << endl; - m_maybeFrees.erase(node); - continue; - } - - if (m_cg.GetCalleesOfNode(m_allocateWrapper).count(node) > 0) - { - cout << "calls allocate, remove" << endl; - m_maybeFrees.erase(node); - continue; - } - - if (!potentialFreeFunctionPrototype(fn)) - { - m_maybeFrees.erase(node); - continue; - } - - } -} - -#ifdef UNUSED -void CGC_libc::findUnreachableNodes() -{ - FunctionSet_t &functions = m_firp->GetFunctions(); - - for (FunctionSet_t::iterator it = functions.begin(); - it != functions.end(); ++it) - { - if (m_cg.GetCallersOfNode(*it).size() == 0) - { - cout << "Unreachable function detected: " << m_cg.GetNodeName(*it) << endl; - } - } -} -#endif - - -void CGC_libc::clusterFreeMalloc() -{ - if (m_maybeMallocs.size() == 0) - return; - - cout << "Do Malloc()" << endl; - - // m1 -> 20, 15 - // m2 -> 20, 12 - // m3 -> 20, 10 - std::map<CallGraphNode_t*, std::set<int> > mallocs; - - // f1 -> 8 - // f2 -> 10 - std::map<CallGraphNode_t*, std::set<int> > frees; - - for (CallGraphNodeSet_t::iterator n = m_maybeMallocs.begin(); n != m_maybeMallocs.end(); ++n) - { - CallGraphNode_t *node = *n; - if (!node || node->IsHellnode()) continue; - - Function_t *fn = node->GetFunction(); - if (!fn) continue; - - for(set<Instruction_t*>::const_iterator i=fn->GetInstructions().begin(); i!=fn->GetInstructions().end(); ++i) - { - Instruction_t *insn = *i; - if (!insn) continue; - - DISASM d; - insn->Disassemble(d); - - if (d.Argument1.ArgType == MEMORY_TYPE) - { - int displacement = d.Argument1.Memory.Displacement; - if (isGlobalData(displacement)) - { - cout << "Function: " << fn->GetName() << " global data found at displacement: " << displacement << endl; - mallocs[node].insert(displacement); - } - } - - if (d.Argument2.ArgType == MEMORY_TYPE) - { - int displacement = d.Argument2.Memory.Displacement; - if (isGlobalData(displacement)) - { - cout << "Function: " << fn->GetName() << " global data found at displacement: " << displacement << endl; - mallocs[node].insert(displacement); - } - } - - if (d.Argument3.ArgType == MEMORY_TYPE) - { - int displacement = d.Argument3.Memory.Displacement; - if (isGlobalData(displacement)) - { - cout << "Function: " << fn->GetName() << " global data found at displacement: " << displacement << endl; - mallocs[node].insert(displacement); - } - } - } - } - - cout << "Do Free()" << endl; - for (CallGraphNodeSet_t::iterator n = m_maybeFrees.begin(); n != m_maybeFrees.end(); ++n) - { - CallGraphNode_t *node = *n; - if (!node || node->IsHellnode()) continue; - - Function_t *fn = node->GetFunction(); - if (!fn) continue; - - for(set<Instruction_t*>::const_iterator i=fn->GetInstructions().begin(); i!=fn->GetInstructions().end(); ++i) - { - Instruction_t *insn = *i; - if (!insn) continue; - - DISASM d; - insn->Disassemble(d); - - if (d.Argument1.ArgType == MEMORY_TYPE) - { - int displacement = d.Argument1.Memory.Displacement; - if (isGlobalData(displacement)) - { - cout << "Function: " << fn->GetName() << " global data found at displacement: " << displacement << endl; - frees[node].insert(displacement); - } - } - - if (d.Argument2.ArgType == MEMORY_TYPE) - { - int displacement = d.Argument2.Memory.Displacement; - if (isGlobalData(displacement)) - { - cout << "Function: " << fn->GetName() << " global data found at displacement: " << displacement << endl; - frees[node].insert(displacement); - } - } - - if (d.Argument3.ArgType == MEMORY_TYPE) - { - int displacement = d.Argument3.Memory.Displacement; - if (isGlobalData(displacement)) - { - cout << "Function: " << fn->GetName() << " global data found at displacement: " << displacement << endl; - frees[node].insert(displacement); - } - } - } - } - - CallGraphNodeSet_t maybeMallocsWithGlobals; - CallGraphNodeSet_t maybeFreesWithGlobals; - - // find the true malloc - std::map<CallGraphNode_t*, std::set<int> >::iterator it; - std::map<CallGraphNode_t*, std::set<int> >::iterator it2; - - for (it = mallocs.begin(); it != mallocs.end(); ++it) - { - CallGraphNode_t *node = it->first; - if (!node || node->IsHellnode()) continue; - Function_t *fn = node->GetFunction(); - set<int> displacements = it->second; - cout << endl; - cout << "investigating function: " << fn->GetName() << endl; - for (set<int>::iterator d = displacements.begin(); d != displacements.end(); ++d) - { - int displacement = *d; - cout << " displacement: " << displacement << endl; - - // look for displacement in maybe frees - for (it2 = frees.begin(); it2 != frees.end(); ++it2) - { - CallGraphNode_t *node2 = it2->first; - if (!node2 || node2->IsHellnode()) continue; - Function_t *fn2 = node2->GetFunction(); - if (fn2 == fn) continue; - cout << " free function: " << fn2->GetName() << endl; - set<int> displacements2 = it2->second; - for (set<int>::iterator d2 = displacements2.begin(); d2 != displacements2.end(); ++d2) - { - int displacement2 = *d2; - cout << " displacement2(free): " << displacement2 << endl; - if (displacement == displacement2) - { - maybeMallocsWithGlobals.insert(node); - maybeFreesWithGlobals.insert(node2); - cout << " MATCH: " << fn->GetName() << " <--> " << fn2->GetName() << endl; - } - } - } - } - } - - cout << "maybe mallocs with clustering algo: " << maybeMallocsWithGlobals.size() << endl; - cout << "maybe frees with clustering algo: " << maybeFreesWithGlobals.size() << endl; - - m_maybeMallocs = maybeMallocsWithGlobals; - m_maybeFrees = maybeFreesWithGlobals; -} - -bool CGC_libc::isGlobalData(int p_address) -{ - for ( int i = 0; i < m_elfiop->sections.size(); ++i ) - { - - int flags = m_elfiop->sections[i]->get_flags(); - /* not a loaded section */ - if( (flags & SHF_ALLOC) != SHF_ALLOC) - continue; - if( (flags & SHF_EXECINSTR) == SHF_EXECINSTR) - continue; - - int first=m_elfiop->sections[i]->get_address(); - int second=m_elfiop->sections[i]->get_address()+m_elfiop->sections[i]->get_size(); - if (p_address >= first && p_address <= second) - return true; - } - - return false; -} - -// out: <nodes> has dominated functions erased -void CGC_libc::findDominant(CallGraphNodeSet_t& nodes) -{ - CallGraphNodeSet_t dominatedNodes; - - // for each function f - // A = get ancestors for each of f's immediate parent - // for each m in maybeMallocs - // if m is in all As, then m dominates f - - for (CallGraphNodeSet_t::iterator i = nodes.begin(); i != nodes.end(); ++i) - { - CallGraphNode_t *node = *i; - Function_t* fn = NULL; - - if (!node || node->IsHellnode()) - continue; - - fn = node->GetFunction(); - cout << "Looking for dominator of function " << fn->GetName() << endl; - - CallGraphNodeSet_t preds = m_cg.GetCallersOfNode(node); - if (preds.size() == 0) continue; - - // check to see if immediate caller dominates - if (preds.size() == 1) - { - bool yes_dominated = false; - // make sure the caller is in <nodes> - for (CallGraphNodeSet_t::iterator c = preds.begin(); c != preds.end(); ++c) - { - CallGraphNode_t *caller = *c; - if (caller == NULL) continue; - - if (nodes.count(caller) >= 1) - yes_dominated = true; - } - - if (yes_dominated) { - dominatedNodes.insert(node); - continue; - } - } - - int preds_count = 0; - CallGraphNodeSet_t ancestors[preds.size()]; - for (CallGraphNodeSet_t::iterator a = preds.begin(); a != preds.end(); ++a) - { - ancestors[preds_count] = m_cg.GetCallersOfNode(*a); - ancestors[preds_count].insert(*a); - preds_count++; - } - - // does m dominate fn? - for (CallGraphNodeSet_t::iterator m = nodes.begin(); m != nodes.end(); ++m) - { - cout << "Does function " << (*m)->GetFunction()->GetName() << " dominate " << node->GetFunction()->GetName() << "?" << endl; - int dominated = true; - for (int a = 0; a < preds_count; ++a) - { - if (ancestors[a].count(*m) == 0) - { - dominated = false; - } - } - - if (dominated) { - cout << "Function " << node->GetFunction()->GetName() << " is dominated by " << (*m)->GetFunction()->GetName() << endl; - dominatedNodes.insert(node); - } - } - } - - - for (CallGraphNodeSet_t::iterator d = dominatedNodes.begin(); d != dominatedNodes.end(); ++d) - { - nodes.erase(*d); - } -} - -bool CGC_libc::execute() -{ - displayAllFunctions(); - - cout << "CGC: syscall heuristic" << endl; - - findSyscallWrappers(); // finds the initial set of mallocs and frees - - displayMaybes(m_cg,m_mallocUniverse, "universe-malloc"); - - cout << "CGC: prune mallocs" << endl; - pruneMallocs(); - - cout << "prune frees" << endl; - pruneFrees(); - - displayMaybes(m_cg,m_mallocUniverse, "universe-malloc-2"); - - if (m_clustering) - { - cout << "# of candidate functions for malloc() prior to clustering: " << m_maybeMallocs.size() << endl; - cout << "# of candidate functions for free() prior to clustering: " << m_maybeFrees.size() << endl; - clusterFreeMalloc(); - displayMaybes(m_cg,m_maybeMallocs, "cluster-malloc"); - displayMaybes(m_cg,m_maybeFrees, "cluster-free"); - } - else - cout << "clustering heuristic is off" << endl; - - if (m_dominance) - { - cout << "# of candidate functions for malloc() prior to domination heuristic: " << m_maybeMallocs.size() << endl; - cout << "# of candidate functions for free(): prior to domination heuristic " << m_maybeFrees.size() << endl; - findDominant(m_maybeMallocs); - displayMaybes(m_cg,m_maybeMallocs, "dominator-malloc"); - - findDominant(m_maybeFrees); - displayMaybes(m_cg,m_maybeFrees, "dominator-free"); - } - else - cout << "domination heuristic is off" << endl; - - cout << endl << "Final summary" << endl; - cout << "-----------------------------------------" << endl; - cout << "Total # of functions: " << m_firp->GetFunctions().size() << endl; - cout << "# of candidate functions for malloc(): " << m_maybeMallocs.size() << endl; - cout << "# of candidate functions for free(): " << m_maybeFrees.size() << endl; - cout << endl; - - displayFinalInference(m_cg,m_maybeMallocs, "malloc"); - displayFinalInference(m_cg,m_maybeFrees, "free"); - - return true; -} - -bool CGC_libc::renameSyscallWrappers() -{ - bool success = false; - - findSyscallWrappers(); - - if (m__terminateWrapper && !m__terminateWrapper->IsHellnode() && - m__terminateWrapper->GetFunction()) - { - cout << "renaming " << m__terminateWrapper->GetFunction()->GetName() << " to cinderella::terminate" << endl; - m__terminateWrapper->GetFunction()->SetName("cinderella::terminate"); - success = true; - } - - if (m_transmitWrapper && !m_transmitWrapper->IsHellnode() && - m_transmitWrapper->GetFunction()) - { - cout << "renaming " << m_transmitWrapper->GetFunction()->GetName() << " to cinderella::transmit" << endl; - m_transmitWrapper->GetFunction()->SetName("cinderella::transmit"); - success = true; - } - - if (m_receiveWrapper && !m_receiveWrapper->IsHellnode() && - m_receiveWrapper->GetFunction()) - { - cout << "renaming " << m_receiveWrapper->GetFunction()->GetName() << " to cinderella::receive" << endl; - m_receiveWrapper->GetFunction()->SetName("cinderella::receive"); - success = true; - } - - if (m_fdwaitWrapper && !m_fdwaitWrapper->IsHellnode() && - m_fdwaitWrapper->GetFunction()) - { - cout << "renaming " << m_fdwaitWrapper->GetFunction()->GetName() << " to cinderella::fdwait" << endl; - m_fdwaitWrapper->GetFunction()->SetName("cinderella::fdwait"); - success = true; - } - - if (m_allocateWrapper && !m_allocateWrapper->IsHellnode() && - m_allocateWrapper->GetFunction()) - { - cout << "renaming " << m_allocateWrapper->GetFunction()->GetName() << " to cinderella::allocate" << endl; - m_allocateWrapper->GetFunction()->SetName("cinderella::allocate"); - success = true; - } - - if (m_deallocateWrapper && !m_deallocateWrapper->IsHellnode() && - m_deallocateWrapper->GetFunction()) - { - cout << "renaming " << m_deallocateWrapper->GetFunction()->GetName() << " to cinderella::deallocate" << endl; - m_deallocateWrapper->GetFunction()->SetName("cinderella::deallocate"); - success = true; - } - - if (m_randomWrapper && !m_randomWrapper->IsHellnode() && - m_randomWrapper->GetFunction()) - { - cout << "renaming " << m_randomWrapper->GetFunction()->GetName() << " to cinderella::random" << endl; - m_randomWrapper->GetFunction()->SetName("cinderella::random"); - success = true; - } - - return success; -} diff --git a/tools/cgclibc/cgclibc.hpp b/tools/cgclibc/cgclibc.hpp deleted file mode 100644 index 9df58ec31..000000000 --- a/tools/cgclibc/cgclibc.hpp +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#ifndef cgc_libc_h -#define cgc_libc_h - -#include <libIRDB-core.hpp> -#include <libIRDB-cfg.hpp> -#include <libIRDB-syscall.hpp> - -#include "elfio/elfio.hpp" -#include "elfio/elfio_dump.hpp" - - -using namespace libIRDB; - -class CGC_libc { - public: - CGC_libc(FileIR_t *p_firp); - void setPositiveInferences(std::string p_positiveFile); - void setNegativeInferences(std::string p_negativeFile); - - bool execute(); - bool renameSyscallWrappers(); - void displayAllFunctions(); - - void enableClusteringHeuristic() { m_clustering = true; } - void enableDominanceHeuristic() { m_dominance = true; } - - private: - void findSyscallWrappers(); - void pruneMallocs(); - void pruneFrees(); - void emitFunctionInfo(Function_t *); - bool potentialMallocFunctionPrototype(Function_t *p_fn); - bool potentialFreeFunctionPrototype(Function_t *p_fn); - void clusterFreeMalloc(); - bool isGlobalData(int p_address); - void findDominant(CallGraphNodeSet_t&); - - private: - FileIR_t *m_firp; - Callgraph_t m_cg; - Syscalls_t m_syscalls; - - CallGraphNode_t* m__terminateWrapper; - CallGraphNode_t* m_transmitWrapper; - CallGraphNode_t* m_receiveWrapper; - CallGraphNode_t* m_fdwaitWrapper; - CallGraphNode_t* m_allocateWrapper; - CallGraphNode_t* m_deallocateWrapper; - CallGraphNode_t* m_randomWrapper; - - CallGraphNodeSet_t m_maybeMallocs; - CallGraphNodeSet_t m_maybeFrees; - - CallGraphNodeSet_t m_mallocUniverse; - CallGraphNodeSet_t m_mallocNegativeUniverse; - - bool m_skipHellNode; - bool m_clustering; - bool m_dominance; - ELFIO::elfio* m_elfiop; -}; - -#endif diff --git a/tools/cgclibc/cgclibc_driver.cpp b/tools/cgclibc/cgclibc_driver.cpp deleted file mode 100644 index 7df442a01..000000000 --- a/tools/cgclibc/cgclibc_driver.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "MEDS_AnnotationParser.hpp" -#include "cgclibc.hpp" - -using namespace std; -using namespace libIRDB; -using namespace MEDS_Annotation; - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id> [--dominator] [--cluster] [--positive_inferences <filename> ] [--negative_inferences <filename>]\n"; -} - -static bool g_dominator = false; -static bool g_cluster = false; -static std::string g_positiveFile = ""; -static std::string g_negativeFile = ""; - -void parseOptions(int argc, char **argv) -{ - int i; - - for (i = 0; i < argc; ++i) - { - if (strcmp(argv[i], "--dominator") == 0) - g_dominator = true; - if (strcmp(argv[i], "--cluster") == 0) - g_cluster = true; - else if (strcmp(argv[i], "--positive-inferences") == 0) - g_positiveFile = argv[++i]; - else if (strcmp(argv[i], "--negative-inferences") == 0) - g_negativeFile = argv[++i]; - } -} - -int main(int argc, char **argv) -{ - if(argc < 2) - { - usage(argv[0]); - exit(1); - } - - parseOptions(argc, argv); - - string programName(argv[0]); - int variantID = atoi(argv[1]); - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - try - { - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - assert(firp && pidp); - - CGC_libc cgclibc(firp); - - if (g_dominator) cgclibc.enableDominanceHeuristic(); - if (g_cluster) cgclibc.enableClusteringHeuristic(); - - if (g_positiveFile.size() > 0) - cgclibc.setPositiveInferences(g_positiveFile); - - if (g_negativeFile.size() > 0) - cgclibc.setNegativeInferences(g_negativeFile); - - bool success=cgclibc.execute(); - - if (success) - { - one_success = true; - } - delete firp; - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - return 0; -} - diff --git a/tools/cgclibc/display_functions.cpp b/tools/cgclibc/display_functions.cpp deleted file mode 100644 index 89bf5fa2e..000000000 --- a/tools/cgclibc/display_functions.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2014 - Zephyr Software - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "MEDS_AnnotationParser.hpp" -#include "cgclibc.hpp" - -using namespace std; -using namespace libIRDB; -using namespace MEDS_Annotation; - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id>\n"; -} - -int main(int argc, char **argv) -{ - if(argc != 2) - { - usage(argv[0]); - exit(1); - } - - string programName(argv[0]); - int variantID = atoi(argv[1]); - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - try - { - FileIR_t *firp = new FileIR_t(*pidp, this_file); - assert(firp && pidp); - - CGC_libc cgclibc(firp); - - cgclibc.displayAllFunctions(); - - delete firp; - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - return 0; -} - diff --git a/tools/cgclibc/infer_syscall_wrappers.cpp b/tools/cgclibc/infer_syscall_wrappers.cpp deleted file mode 100644 index 8018c1bc5..000000000 --- a/tools/cgclibc/infer_syscall_wrappers.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the - * University of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "MEDS_AnnotationParser.hpp" -#include "cgclibc.hpp" - -using namespace std; -using namespace libIRDB; -using namespace MEDS_Annotation; - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id>\n"; -} - -int main(int argc, char **argv) -{ - if(argc != 2) - { - usage(argv[0]); - exit(1); - } - - string programName(argv[0]); - int variantID = atoi(argv[1]); - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - bool one_success = false; - - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - try - { - FileIR_t *firp = new FileIR_t(*pidp, this_file); - assert(firp && pidp); - - CGC_libc cgclibc(firp); - if (cgclibc.renameSyscallWrappers()) - { - firp->WriteToDB(); - one_success = true; - } - delete firp; - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - if (one_success) - { - cout << "renamed syscall wrappers successfully -- commit new names to DB" << endl; - pqxx_interface.Commit(); - } - else - { - cout << "no syscall wrappers detected" << endl; - } - - return 0; -} - diff --git a/tools/cinderella/Makefile b/tools/cinderella/Makefile deleted file mode 100644 index 91020c579..000000000 --- a/tools/cinderella/Makefile +++ /dev/null @@ -1,38 +0,0 @@ -CC=g++ -CFLAGS= -g -Wall -DCGC -INCLUDE=-I. -I../include -I../xform -I../../beaengine/include -I../../libIRDB/include/ -I../../libMEDSannotation/include/ -I../libtransform/include/ -I../transforms -I../../include -LIBS=-L../../lib -lxform -lIRDB-core -lIRDB-cfg -lIRDB-util -lIRDB-syscall -lBeaEngine_s_d -lpqxx -lMEDSannotation -ltransform ../transforms/Rewrite_Utility.o - -program=cinderella_prep.exe - -all: $(program) - @echo "-----------------------------------------------" - @echo "- CGC libc dynamic inference engine -- Build complete -" - @echo "-----------------------------------------------" - -OBJS=cinderella_prep.o cinderella_prep_driver.o - - -.SUFFIXES: .o .c .exe .cpp .hpp - --include $(OBJS:.o=.d) - -%.o: %.cpp - $(CC) $(INCLUDE) $(CFLAGS) -c $< - @# - @# build dependencies -- http://scottmcpeak.com/autodepend/autodepend.html - @# - $(CC) -MM $(INCLUDE) $(CFLAGS) $*.cpp > $*.d - @cp -f $*.d $*.d.tmp - @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $*.d - @rm -f $*.d.tmp - - -clean: - rm -f *.o core *.exe *.d - -$(program): ../../lib/*.a - -$(program): $(OBJS) - $(CC) $(CFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - diff --git a/tools/cinderella/SConscript b/tools/cinderella/SConscript deleted file mode 100644 index cbbf4d4ed..000000000 --- a/tools/cinderella/SConscript +++ /dev/null @@ -1,32 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - -#CFLAGS="-fPIC " - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="cinderella_prep.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util MEDSannotation ") -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install) - - - -Return('install') diff --git a/tools/cinderella/SConstruct b/tools/cinderella/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/cinderella/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/cinderella/cinderella_prep.cpp b/tools/cinderella/cinderella_prep.cpp deleted file mode 100644 index 2c863eb3e..000000000 --- a/tools/cinderella/cinderella_prep.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include "Rewrite_Utility.hpp" -#include "cinderella_prep.hpp" - -using namespace std; - -#define SPRI_AVAIL_ADDRESS 0xff08ff00 - -CinderellaPrep::CinderellaPrep(FileIR_t *p_firp) -{ - m_firp = p_firp; - - m_cg.AddFile(m_firp); -// m_cg.Dump(cout); - - int elfoid=m_firp->GetFile()->GetELFOID(); - pqxx::largeobject lo(elfoid); - libIRDB::pqxxDB_t *interface=dynamic_cast<libIRDB::pqxxDB_t*>(libIRDB::BaseObj_t::GetInterface()); - assert(interface); - lo.to_file(interface->GetTransaction(),"tmp.exe"); - - m_elfiop=new ELFIO::elfio; - m_elfiop->load("tmp.exe"); - ELFIO::dump::header(std::cout,*m_elfiop); - ELFIO::dump::section_headers(std::cout,*m_elfiop); - ELFIO::dump::segment_headers(std::cout,*m_elfiop); -} - -void CinderellaPrep::pinAllFunctionEntryPoints() -{ - Function_t* fn=NULL; - for(FunctionSet_t::iterator it=m_firp->GetFunctions().begin(); - it!=m_firp->GetFunctions().end(); - ++it - ) - { - fn=*it; - if (!fn) continue; - Instruction_t *insn = fn->GetEntryPoint(); - - if(insn && insn->GetAddress() && insn->GetAddress()->GetVirtualOffset() > 0) - { - insn->SetIndirectBranchTargetAddress(insn->GetAddress()); -printf("inferfn: pinning function entry point: %p\n", insn->GetAddress()->GetVirtualOffset()); - } - } -} - -void CinderellaPrep::addInferenceCallback(Instruction_t *site) -{ - virtual_offset_t postCallbackReturn = SPRI_AVAIL_ADDRESS; - char tmpbuf[200]; - sprintf(tmpbuf,"push 0x%x", postCallbackReturn); - - Instruction_t *tmp=site, *callback=NULL, *post_callback=NULL; -// Instruction_t *fallthrough = site->GetFallthrough(); - tmp=insertAssemblyAfter(m_firp,tmp,"lea esp, [esp-4096]"); - tmp=insertAssemblyAfter(m_firp,tmp,"pushf"); - tmp=insertAssemblyAfter(m_firp,tmp,"pusha"); - tmp=insertAssemblyAfter(m_firp,tmp,tmpbuf); // push <ret addr> - callback=tmp=insertAssemblyAfter(m_firp,tmp,"nop"); - post_callback=tmp=insertAssemblyAfter(m_firp,tmp,"popa"); - tmp=insertAssemblyAfter(m_firp,tmp,"popf"); - tmp=insertAssemblyAfter(m_firp,tmp,"lea esp, [esp+4096]"); - post_callback->GetAddress()->SetVirtualOffset(postCallbackReturn); - callback->SetCallback("inference_handler"); - -// tmp->SetFallthrough(fallthrough); -} - -Instruction_t* CinderellaPrep::findProgramEntryPoint() -{ - Instruction_t* insn=NULL; - for(InstructionSet_t::iterator it=m_firp->GetInstructions().begin(); - it!=m_firp->GetInstructions().end(); - ++it - ) - { - insn=*it; - if(insn->GetIndirectBranchTargetAddress() && - insn->GetIndirectBranchTargetAddress()->GetVirtualOffset()==(virtual_offset_t)m_elfiop->get_entry()) - { - cout << "program entry point is at 0x" << hex << m_elfiop->get_entry() << dec << endl; - return insn; - } - } - - return NULL; -} - -bool CinderellaPrep::execute() -{ - Instruction_t *entryPoint = findProgramEntryPoint(); - assert(entryPoint); - - insertAssemblyBefore(m_firp, entryPoint, "nop"); - addInferenceCallback(entryPoint); - - // must pin functions o/w zipr will move - pinAllFunctionEntryPoints(); - - return true; -} diff --git a/tools/cinderella/cinderella_prep.hpp b/tools/cinderella/cinderella_prep.hpp deleted file mode 100644 index aac9bc022..000000000 --- a/tools/cinderella/cinderella_prep.hpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#ifndef _cinderella_prep_h -#define _cinderella_prep_h - -#include <libIRDB-core.hpp> -#include <libIRDB-cfg.hpp> - -#include "elfio/elfio.hpp" -#include "elfio/elfio_dump.hpp" - -using namespace libIRDB; - -class CinderellaPrep { - public: - CinderellaPrep(FileIR_t *p_firp); - bool execute(); - - private: - Instruction_t* findProgramEntryPoint(); - void addInferenceCallback(Instruction_t *); - void pinAllFunctionEntryPoints(); - - private: - FileIR_t *m_firp; - ELFIO::elfio* m_elfiop; - Callgraph_t m_cg; -}; - -#endif diff --git a/tools/cinderella/cinderella_prep_driver.cpp b/tools/cinderella/cinderella_prep_driver.cpp deleted file mode 100644 index 8a89406e0..000000000 --- a/tools/cinderella/cinderella_prep_driver.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2014 - Zephyr Software - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "cinderella_prep.hpp" - -using namespace std; -using namespace libIRDB; - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id>\n"; -} - -int main(int argc, char **argv) -{ - if(argc != 2) - { - usage(argv[0]); - exit(1); - } - - string programName(argv[0]); - int variantID = atoi(argv[1]); - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - try - { - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - cout<<"Mallard: Transforming "<<this_file->GetURL()<<endl; - - assert(firp && pidp); - - CinderellaPrep prep(firp); - - bool success=prep.execute(); - - if (success) - { - one_success = true; - firp->WriteToDB(); - } - delete firp; - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - if (one_success) - { - pqxx_interface.Commit(); - } - - return 0; -} - diff --git a/tools/cookbook/SConscript b/tools/cookbook/SConscript deleted file mode 100644 index 7abb296f8..000000000 --- a/tools/cookbook/SConscript +++ /dev/null @@ -1,52 +0,0 @@ -import os - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - $SECURITY_TRANSFORMS_HOME/libtransform/include - ./ - ''' - -#CFLAGS="-fPIC " -myenv.Append(CXXFLAGS = " -std=c++11 ") - -CPPDEFINES = {} -if os.environ.has_key('PS_NO_IDAPRO'): - print "Assuming that there is no IDA Pro available." - CPPDEFINES["NO_IDAPRO"] = 1 - -pgms = {} -ppgms = [] - -pgms["instructioncountdriver.exe"] = (Dir('.').srcnode().abspath+"/x86_64_linux/instructioncount.cpp", Dir('.').srcnode().abspath+"/instructioncountdriver.cpp",) - -pgms["functioncalldriver.exe"] = (Dir('.').srcnode().abspath+"/x86_64_linux/functioncall.cpp", Dir('.').srcnode().abspath+"/functioncalldriver.cpp",) - -pgms["whitelistdriver.exe"] = (Dir('.').srcnode().abspath+"/x86_64_linux/whitelist.cpp", Dir('.').srcnode().abspath+"/whitelistdriver.cpp",) - -pgms["checkwhitelistdriver.exe"] = (Dir('.').srcnode().abspath+"/x86_64_linux/checkwhitelist.cpp", Dir('.').srcnode().abspath+"/checkwhitelistdriver.cpp",) - -pgms["logdriver.exe"] = (Dir('.').srcnode().abspath+"/logdriver.cpp",) - -pgms["syscalldriver.exe"] = (Dir('.').srcnode().abspath+"/x86_64_linux/syscall.cpp", Dir('.').srcnode().abspath+"/syscalldriver.cpp") - -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -myenv.Append(CPPDEFINES=CPPDEFINES) - -cookbook_obj = myenv.Object(Dir('.').srcnode().abspath+"/x86_64_linux/cookbook.cpp") - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=cookbook_obj + Split("xform IRDB-core IRDB-cfg IRDB-util pqxx BeaEngine_s_d transform MEDSannotation " + env.subst('$BASE_IRDB_LIBS') ) - -for pgm in pgms.keys(): - ppgms.append(myenv.Program(pgm, pgms[pgm], LIBPATH=LIBPATH, LIBS=LIBS)) - -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", ppgms) -Default(install) -Return('install') diff --git a/tools/cookbook/SConstruct b/tools/cookbook/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/cookbook/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/cookbook/checkwhitelist.hpp b/tools/cookbook/checkwhitelist.hpp deleted file mode 100644 index 5db21b754..000000000 --- a/tools/cookbook/checkwhitelist.hpp +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef _LIBTRANSFORM_CHECKWHITELIST_H_ -#define _LIBTRANSFORM_CHECKWHITELIST_H_ - -#include "cookbook.hpp" -namespace libTransform -{ - using namespace std; - using namespace libIRDB; - - class Checkwhitelist : public CookbookTransform - { - public: - Checkwhitelist(VariantID_t *p_variantID, - FileIR_t*p_variantIR, - set<std::string> *p_filteredFunctions); - int execute(); - private: - }; -} -#endif diff --git a/tools/cookbook/checkwhitelistdriver.cpp b/tools/cookbook/checkwhitelistdriver.cpp deleted file mode 100644 index 2c9ead22d..000000000 --- a/tools/cookbook/checkwhitelistdriver.cpp +++ /dev/null @@ -1,115 +0,0 @@ -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> - -#include "MEDS_AnnotationParser.hpp" -#include "transformutils.h" -#include "checkwhitelist.hpp" - -using namespace std; - -void usage(string programName) -{ - cerr << "Usage: " << programName << " <variant id> <annotation file>" <<endl; -} - -int main(int argc, char **argv) -{ - string programName(argv[0]); - char *strtolError = NULL; - int transformExitCode = 0; - int variantID = -1; - set<string> filteredFunctions; - VariantID_t *pidp = NULL; - FileIR_t *virp = NULL; - pqxxDB_t pqxx_interface; - File_t *fileId; - std::set<File_t*> files; - - /* - * Check that we've been called correctly: - * <program> <variant id> <annotation file> - */ - if(argc < 3) - { - usage(programName); - exit(1); - } - variantID = strtol(argv[1], &strtolError, 10); - if (*strtolError != '\0') - { - cerr << "Invalid variantID: " << argv[1] << endl; - exit(1); - } - - /* setup the interface to the sql server */ - BaseObj_t::SetInterface(&pqxx_interface); - - try - { - /* - * Read information about the program - * variant from the database and check - * some important assumptions. - */ - pidp=new VariantID_t(variantID); - assert(pidp && pidp->IsRegistered()==true); - - /* - * Loop through the variant's files and match - * it to the one given as a parameter. - */ - files = pidp->GetFiles(); - for (set<File_t*>::iterator it=files.begin(); - it!=files.end(); - ++it - ) - { - const char *name = (*it)->GetURL().c_str(); - if (strstr(name, argv[2]) != NULL) - { - fileId = *it; - break; - } - } - assert(fileId); - virp=new FileIR_t(*pidp, fileId); - assert(virp); - - /* - * Create a transformation and then - * invoke its execution. - */ - libTransform::Checkwhitelist checker(pidp, virp, &filteredFunctions); - transformExitCode = checker.execute(); - - /* - * If everything about the transformation - * went okay, then we will write the updated - * set of instructions to the database. - */ - if (transformExitCode == 0) - { - virp->WriteToDB(); - pqxx_interface.Commit(); - delete virp; - delete pidp; - } - else - { - cerr << programName << ": transform failed. Check logs." << endl; - } - return transformExitCode; - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << endl; - exit(1); - } - catch (...) - { - cerr << programName << ": Unexpected error" << endl; - exit(1); - } - return 1; -} diff --git a/tools/cookbook/cookbook.hpp b/tools/cookbook/cookbook.hpp deleted file mode 100644 index 5a669d82c..000000000 --- a/tools/cookbook/cookbook.hpp +++ /dev/null @@ -1,91 +0,0 @@ -#ifndef _LIBTRANSFORM_COOKBOOK_TRANSFORM_H_ -#define _LIBTRANSFORM_COOKBOOK_TRANSFORM_H_ - -#include "transform.hpp" -#include "VirtualOffset.hpp" - -namespace libTransform -{ - using namespace std; - using namespace libIRDB; - - /* - * Cookbook Transform: - * - * A subclass of Transform that provides a basic - * transform (an instruction comment logger) and - * extra features that make the cookbook examples - * easier to read. - */ - class CookbookTransform : public Transform - { - public: - /* - * CookbookTransform - * - * Constructor. It simply calls through to the parent - * constructor. - * - * Input: - * p_variantID: The variant ID (generated by the - * peasoupify process.) - * p_variantIR: Pointer to the intermediate representation - * of the file in the database. - * p_filteredFunctions: A set of functions that are blacklisted. - * - * Output: - * Returns: - */ - CookbookTransform(VariantID_t *p_variantID, - FileIR_t *p_variantIR, - set<std::string> *p_filteredFunctions) : - Transform(p_variantID, - p_variantIR, - p_filteredFunctions) - { - } - - /* - * execute() - * - * A function that subclasses can implement - * that will do the actual work of executing - * the transformation. - * - * Input: None - * Output: None - * Returns: 0/1 based on success or failure, - * respectively. - * - */ - virtual int execute(); - protected: - - /* - * addCookbookCallback: - * - * Add a callback to an instruction. - * - * Input: - * original: the original instruction to hook with a - * callback. - * callback: the name of the callback to invoke. - * before: true for executing the callback before - * the instruction. false to execute the callback - * after. - * extra: a pointer to some extra data - * passed to the callback - * - * Output: - * Returns: - * - * As a side effect, instructions are inserted that will - * invoke callback before or after original is executed. - */ - void addCookbookCallback(Instruction_t *original, - string callback, - bool before = true, - void *extra = 0); - }; -} -#endif diff --git a/tools/cookbook/functioncall.hpp b/tools/cookbook/functioncall.hpp deleted file mode 100644 index e4c301af6..000000000 --- a/tools/cookbook/functioncall.hpp +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef _LIBTRANSFORM_FUNCTIONCALL_H_ -#define _LIBTRANSFORM_FUNCTIONCALL_H_ - -#include "cookbook.hpp" -namespace libTransform -{ - using namespace std; - using namespace libIRDB; - - class Functioncall : public CookbookTransform - { - public: - Functioncall(VariantID_t *p_variantID, - FileIR_t*p_variantIR, - set<std::string> *p_filteredFunctions); - int execute(); - private: - }; -} -#endif diff --git a/tools/cookbook/functioncalldriver.cpp b/tools/cookbook/functioncalldriver.cpp deleted file mode 100644 index e075da5de..000000000 --- a/tools/cookbook/functioncalldriver.cpp +++ /dev/null @@ -1,115 +0,0 @@ -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> - -#include "MEDS_AnnotationParser.hpp" -#include "transformutils.h" -#include "functioncall.hpp" - -using namespace std; - -void usage(string programName) -{ - cerr << "Usage: " << programName << " <variant id> <annotation file>" <<endl; -} - -int main(int argc, char **argv) -{ - string programName(argv[0]); - char *strtolError = NULL; - int transformExitCode = 0; - int variantID = -1; - set<string> filteredFunctions; - VariantID_t *pidp = NULL; - FileIR_t *virp = NULL; - pqxxDB_t pqxx_interface; - File_t *fileId; - std::set<File_t*> files; - - /* - * Check that we've been called correctly: - * <program> <variant id> <annotation file> - */ - if(argc < 3) - { - usage(programName); - exit(1); - } - variantID = strtol(argv[1], &strtolError, 10); - if (*strtolError != '\0') - { - cerr << "Invalid variantID: " << argv[1] << endl; - exit(1); - } - - /* setup the interface to the sql server */ - BaseObj_t::SetInterface(&pqxx_interface); - - try - { - /* - * Read information about the program - * variant from the database and check - * some important assumptions. - */ - pidp=new VariantID_t(variantID); - assert(pidp && pidp->IsRegistered()==true); - - /* - * Loop through the variant's files and match - * it to the one given as a parameter. - */ - files = pidp->GetFiles(); - for (set<File_t*>::iterator it=files.begin(); - it!=files.end(); - ++it - ) - { - const char *name = (*it)->GetURL().c_str(); - if (strstr(name, argv[2]) != NULL) - { - fileId = *it; - break; - } - } - assert(fileId); - virp=new FileIR_t(*pidp, fileId); - assert(virp); - - /* - * Create a transformation and then - * invoke its execution. - */ - libTransform::Functioncall functioncaller(pidp, virp, &filteredFunctions); - transformExitCode = functioncaller.execute(); - - /* - * If everything about the transformation - * went okay, then we will write the updated - * set of instructions to the database. - */ - if (transformExitCode == 0) - { - virp->WriteToDB(); - pqxx_interface.Commit(); - delete virp; - delete pidp; - } - else - { - cerr << programName << ": transform failed. Check logs." << endl; - } - return transformExitCode; - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << endl; - exit(1); - } - catch (...) - { - cerr << programName << ": Unexpected error" << endl; - exit(1); - } - return 1; -} diff --git a/tools/cookbook/instructioncount.hpp b/tools/cookbook/instructioncount.hpp deleted file mode 100644 index b14511aec..000000000 --- a/tools/cookbook/instructioncount.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef _LIBTRANSFORM_INSTRUCTIONCOUNT_H_ -#define _LIBTRANSFORM_INSTRUCTIONCOUNT_H_ - -#include "cookbook.hpp" - -namespace libTransform -{ - using namespace std; - using namespace libIRDB; - - class InstructionCount : public CookbookTransform - { - public: - InstructionCount(VariantID_t *p_variantID, - FileIR_t*p_variantIR, - set<std::string> *p_filteredFunctions); - - int execute(); - }; -} - -#endif diff --git a/tools/cookbook/instructioncountdriver.cpp b/tools/cookbook/instructioncountdriver.cpp deleted file mode 100644 index 603f27fa6..000000000 --- a/tools/cookbook/instructioncountdriver.cpp +++ /dev/null @@ -1,114 +0,0 @@ -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> - -#include "MEDS_AnnotationParser.hpp" -#include "transformutils.h" -#include "instructioncount.hpp" - -using namespace std; - -void usage(string programName) -{ - cerr << "Usage: " << programName << " <variant id> <annotation file>" <<endl; -} - -int main(int argc, char **argv) -{ - string programName(argv[0]); - char *strtolError = NULL; - int transformExitCode = 0; - int variantID = -1; - set<string> filteredFunctions; - VariantID_t *pidp = NULL; - FileIR_t *virp = NULL; - pqxxDB_t pqxx_interface; - File_t *fileId; - std::set<File_t*> files; - - /* - * Check that we've been called correctly: - * <program> <variant id> <annotation file> - */ - if(argc < 3) - { - usage(programName); - exit(1); - } - variantID = strtol(argv[1], &strtolError, 10); - if (*strtolError != '\0') - { - cerr << "Invalid variantID: " << argv[1] << endl; - exit(1); - } - - /* setup the interface to the sql server */ - BaseObj_t::SetInterface(&pqxx_interface); - - try - { - /* - * Read information about the program - * variant from the database and check - * some important assumptions. - */ - pidp=new VariantID_t(variantID); - assert(pidp && pidp->IsRegistered()==true); - - /* - * Loop through the variant's files and match - * it to the one given as a parameter. - */ - files = pidp->GetFiles(); - for (set<File_t*>::iterator it=files.begin(); - it!=files.end(); - ++it - ) - { - const char *name = (*it)->GetURL().c_str(); - if (strstr(name, argv[2]) != NULL) - { - fileId = *it; - break; - } - } - assert(fileId); - virp=new FileIR_t(*pidp, fileId); - assert(virp); - - /* - * Create a transformation and then - * invoke its execution. - */ - libTransform::InstructionCount instructionCount(pidp, virp, &filteredFunctions); - transformExitCode = instructionCount.execute(); - /* - * If everything about the transformation - * went okay, then we will write the updated - * set of instructions to the database. - */ - if (transformExitCode == 0) - { - virp->WriteToDB(); - pqxx_interface.Commit(); - delete virp; - delete pidp; - } - else - { - cerr << programName << ": transform failed. Check logs." << endl; - } - return transformExitCode; - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << endl; - exit(1); - } - catch (...) - { - cerr << programName << ": Unexpected error" << endl; - exit(1); - } - return 1; -} diff --git a/tools/cookbook/logdriver.cpp b/tools/cookbook/logdriver.cpp deleted file mode 100644 index 346320b21..000000000 --- a/tools/cookbook/logdriver.cpp +++ /dev/null @@ -1,115 +0,0 @@ -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> - -#include "MEDS_AnnotationParser.hpp" -#include "transformutils.h" -#include "cookbook.hpp" - -using namespace std; - -void usage(string programName) -{ - cerr << "Usage: " << programName << " <variant id> <annotation file>" <<endl; -} - -int main(int argc, char **argv) -{ - string programName(argv[0]); - char *strtolError = NULL; - int transformExitCode = 0; - int variantID = -1; - set<string> filteredFunctions; - VariantID_t *pidp = NULL; - FileIR_t *virp = NULL; - pqxxDB_t pqxx_interface; - File_t *fileId; - std::set<File_t*> files; - - /* - * Check that we've been called correctly: - * <program> <variant id> <annotation file> - */ - if(argc < 3) - { - usage(programName); - exit(1); - } - variantID = strtol(argv[1], &strtolError, 10); - if (*strtolError != '\0') - { - cerr << "Invalid variantID: " << argv[1] << endl; - exit(1); - } - - /* setup the interface to the sql server */ - BaseObj_t::SetInterface(&pqxx_interface); - - try - { - /* - * Read information about the program - * variant from the database and check - * some important assumptions. - */ - pidp=new VariantID_t(variantID); - assert(pidp && pidp->IsRegistered()==true); - - /* - * Loop through the variant's files and match - * it to the one given as a parameter. - */ - files = pidp->GetFiles(); - for (set<File_t*>::iterator it=files.begin(); - it!=files.end(); - ++it - ) - { - const char *name = (*it)->GetURL().c_str(); - if (strstr(name, argv[2]) != NULL) - { - fileId = *it; - break; - } - } - assert(fileId); - virp=new FileIR_t(*pidp, fileId); - assert(virp); - - /* - * Create a transformation and then - * invoke its execution. - */ - libTransform::CookbookTransform logger(pidp, virp, &filteredFunctions); - transformExitCode = logger.execute(); - - /* - * If everything about the transformation - * went okay, then we will write the updated - * set of instructions to the database. - */ - if (transformExitCode == 0) - { - virp->WriteToDB(); - pqxx_interface.Commit(); - delete virp; - delete pidp; - } - else - { - cerr << programName << ": transform failed. Check logs." << endl; - } - return transformExitCode; - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << endl; - exit(1); - } - catch (...) - { - cerr << programName << ": Unexpected error" << endl; - exit(1); - } - return 1; -} diff --git a/tools/cookbook/syscall.hpp b/tools/cookbook/syscall.hpp deleted file mode 100644 index bd377ba47..000000000 --- a/tools/cookbook/syscall.hpp +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef _LIBTRANSFORM_SYSCALL_H_ -#define _LIBTRANSFORM_SYSCALL_H_ - -#include "cookbook.hpp" -namespace libTransform -{ - using namespace std; - using namespace libIRDB; - - class Syscall : public CookbookTransform - { - public: - Syscall(VariantID_t *p_variantID, - FileIR_t*p_variantIR, - set<std::string> *p_filteredFunctions); - int execute(); - private: - }; -} -#endif diff --git a/tools/cookbook/syscalldriver.cpp b/tools/cookbook/syscalldriver.cpp deleted file mode 100644 index c889739ee..000000000 --- a/tools/cookbook/syscalldriver.cpp +++ /dev/null @@ -1,114 +0,0 @@ -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> - -#include "MEDS_AnnotationParser.hpp" -#include "transformutils.h" -#include "syscall.hpp" - -using namespace std; - -void usage(string programName) -{ - cerr << "Usage: " << programName << " <variant id> <annotation file>" <<endl; -} - -int main(int argc, char **argv) -{ - string programName(argv[0]); - char *strtolError = NULL; - int transformExitCode = 0; - int variantID = -1; - set<string> filteredFunctions; - VariantID_t *pidp = NULL; - FileIR_t *virp = NULL; - pqxxDB_t pqxx_interface; - File_t *fileId; - std::set<File_t*> files; - - /* - * Check that we've been called correctly: - * <program> <variant id> <annotation file> - */ - if(argc < 3) - { - usage(programName); - exit(1); - } - variantID = strtol(argv[1], &strtolError, 10); - if (*strtolError != '\0') - { - cerr << "Invalid variantID: " << argv[1] << endl; - exit(1); - } - - /* setup the interface to the sql server */ - BaseObj_t::SetInterface(&pqxx_interface); - - try - { - /* - * Read information about the program - * variant from the database and check - * some important assumptions. - */ - pidp=new VariantID_t(variantID); - assert(pidp && pidp->IsRegistered()==true); - - /* - * Loop through the variant's files and match - * it to the one given as a parameter. - */ - files = pidp->GetFiles(); - for (set<File_t*>::iterator it=files.begin(); - it!=files.end(); - ++it - ) - { - const char *name = (*it)->GetURL().c_str(); - if (strstr(name, argv[2]) != NULL) - { - fileId = *it; - break; - } - } - assert(fileId); - virp=new FileIR_t(*pidp, fileId); - assert(virp); - - /* - * Create a transformation and then - * invoke its execution. - */ - libTransform::Syscall syscaller(pidp, virp, &filteredFunctions); - transformExitCode = syscaller.execute(); - /* - * If everything about the transformation - * went okay, then we will write the updated - * set of instructions to the database. - */ - if (transformExitCode == 0) - { - virp->WriteToDB(); - pqxx_interface.Commit(); - delete virp; - delete pidp; - } - else - { - cerr << programName << ": transform failed. Check logs." << endl; - } - return transformExitCode; - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << endl; - exit(1); - } - catch (...) - { - cerr << programName << ": Unexpected error" << endl; - exit(1); - } - return 1; -} diff --git a/tools/cookbook/whitelist.hpp b/tools/cookbook/whitelist.hpp deleted file mode 100644 index 6b3a2cacb..000000000 --- a/tools/cookbook/whitelist.hpp +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef _LIBTRANSFORM_WHITELISTCALL_H_ -#define _LIBTRANSFORM_WHITELISTCALL_H_ - -#include "cookbook.hpp" -namespace libTransform -{ - using namespace std; - using namespace libIRDB; - - class Whitelistcall : public CookbookTransform - { - public: - Whitelistcall(VariantID_t *p_variantID, - FileIR_t*p_variantIR, - set<std::string> *p_filteredFunctions); - int execute(); - private: - }; -} -#endif diff --git a/tools/cookbook/whitelistdriver.cpp b/tools/cookbook/whitelistdriver.cpp deleted file mode 100644 index 123407bf8..000000000 --- a/tools/cookbook/whitelistdriver.cpp +++ /dev/null @@ -1,115 +0,0 @@ -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> - -#include "MEDS_AnnotationParser.hpp" -#include "transformutils.h" -#include "whitelist.hpp" - -using namespace std; - -void usage(string programName) -{ - cerr << "Usage: " << programName << " <variant id> <annotation file>" <<endl; -} - -int main(int argc, char **argv) -{ - string programName(argv[0]); - char *strtolError = NULL; - int transformExitCode = 0; - int variantID = -1; - set<string> filteredFunctions; - VariantID_t *pidp = NULL; - FileIR_t *virp = NULL; - pqxxDB_t pqxx_interface; - File_t *fileId; - std::set<File_t*> files; - - /* - * Check that we've been called correctly: - * <program> <variant id> <annotation file> - */ - if(argc < 3) - { - usage(programName); - exit(1); - } - variantID = strtol(argv[1], &strtolError, 10); - if (*strtolError != '\0') - { - cerr << "Invalid variantID: " << argv[1] << endl; - exit(1); - } - - /* setup the interface to the sql server */ - BaseObj_t::SetInterface(&pqxx_interface); - - try - { - /* - * Read information about the program - * variant from the database and check - * some important assumptions. - */ - pidp=new VariantID_t(variantID); - assert(pidp && pidp->IsRegistered()==true); - - /* - * Loop through the variant's files and match - * it to the one given as a parameter. - */ - files = pidp->GetFiles(); - for (set<File_t*>::iterator it=files.begin(); - it!=files.end(); - ++it - ) - { - const char *name = (*it)->GetURL().c_str(); - if (strstr(name, argv[2]) != NULL) - { - fileId = *it; - break; - } - } - assert(fileId); - virp=new FileIR_t(*pidp, fileId); - assert(virp); - - /* - * Create a transformation and then - * invoke its execution. - */ - libTransform::Whitelistcall whitelister(pidp, virp, &filteredFunctions); - transformExitCode = whitelister.execute(); - - /* - * If everything about the transformation - * went okay, then we will write the updated - * set of instructions to the database. - */ - if (transformExitCode == 0) - { - virp->WriteToDB(); - pqxx_interface.Commit(); - delete virp; - delete pidp; - } - else - { - cerr << programName << ": transform failed. Check logs." << endl; - } - return transformExitCode; - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << endl; - exit(1); - } - catch (...) - { - cerr << programName << ": Unexpected error" << endl; - exit(1); - } - return 1; -} diff --git a/tools/cookbook/x86_64_linux/checkwhitelist.cpp b/tools/cookbook/x86_64_linux/checkwhitelist.cpp deleted file mode 100644 index a3731b338..000000000 --- a/tools/cookbook/x86_64_linux/checkwhitelist.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include "checkwhitelist.hpp" - -#include <assert.h> - - -using namespace libTransform; - -Checkwhitelist::Checkwhitelist(VariantID_t *p_variantID, FileIR_t *p_variantIR, set<std::string> *p_filteredFunctions) : CookbookTransform(p_variantID, p_variantIR, p_filteredFunctions) -{ - -} - -int Checkwhitelist::execute() -{ -#ifndef NO_IDAPRO - for ( - set<Function_t*>::const_iterator itf=getFileIR()->GetFunctions().begin(); - itf!=getFileIR()->GetFunctions().end(); - ++itf - ) - { - Function_t* func=*itf; - for ( - set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it - ) - { -#else - set<Instruction_t*> insns = getFileIR()->GetInstructions(); - for ( - set<Instruction_t*>::const_iterator it=insns.begin(); - it!=insns.end(); - ++it - ) - { -#endif - - Instruction_t* insn = *it; - if(insn /*&& insn->GetAddress()*/) - { - if (insn!=NULL && insn->GetFallthrough()!=NULL) - { - string syscall_callback = string("whitelist_syscall_check"); - unsigned char dbs[2] = {0,}; - - /* - * An Instruction_t has a convenience - * method for accessing the instruction's - * data. For an instruction, the op code - * is always in either the first or first - * and second byte. - */ - dbs[0] = insn->GetDataBits()[0]; - dbs[1] = insn->GetDataBits()[1]; - - /* - * syscall is two byte instruction - * on x64. - */ - if (dbs[0] == 0x0f && dbs[1] == 0x05 ) - { - /* - * Use CookbookTransform's convenience - * method to add a callback before the systemcall. - * This callback will determine if a write() - * is being called on a non-whitelisted - * file descriptor. - */ - addCookbookCallback(insn, syscall_callback); - } - } - } -#ifndef NO_IDAPRO - } -#endif - } - return 0; -} diff --git a/tools/cookbook/x86_64_linux/cookbook.cpp b/tools/cookbook/x86_64_linux/cookbook.cpp deleted file mode 100644 index be689ab7f..000000000 --- a/tools/cookbook/x86_64_linux/cookbook.cpp +++ /dev/null @@ -1,220 +0,0 @@ -#include "cookbook.hpp" - -#include "Rewrite_Utility.hpp" -#include <assert.h> - -using namespace libTransform; -void CookbookTransform::addCookbookCallback(Instruction_t *original, - string callback, - bool before, - void *extra) -{ - Instruction_t *start = NULL; - Instruction_t *rsp_save = NULL; - Instruction_t *rsp_restore = NULL; - Instruction_t *orig = NULL; - Instruction_t *call = NULL; - Instruction_t *push = NULL; - Instruction_t *rsp_unpush = NULL; - Instruction_t *save_flags = NULL; - Instruction_t *restore_flags = NULL; - char pushAsm[1024] = {0,}; - - /* - * We are going to insert some - * new instructions before/after the current - * one so that we can invoke a callback: - * - * nop - * [save the stack pointer] - * [invoke the callback] - * [restore the stack pointer] - * [original instruction] - */ - - if (before) - { - /* - * Insert the "start" instruction (nop) - * before the original instruction. We - * will chain the remainder of our new - * instructions from start. - * - * This function returns a new Instruction_t - * for the original instruction which we - * want to use from now on. - */ - orig = insertAssemblyBefore(getFileIR(), original, "nop"); - /* - * And the function makes original the nop. So, - * since that's our "start" instruction, we - * will reassign. - */ - start = original; - } - else - { - start = addNewAssembly("nop"); - } - - /* - * Use the so-called Red Zone - * for the invocation of the callback - * function. - */ - rsp_save = allocateNewInstruction( - original->GetAddress()->GetFileID(), original->GetFunction()); - start->SetFallthrough(rsp_save); - setAssembly(rsp_save, "lea rsp, [rsp-128]"); - - /* - * Push the flags onto the stack. - */ - save_flags = allocateNewInstruction( - original->GetAddress()->GetFileID(), original->GetFunction()); - rsp_save->SetFallthrough(save_flags); - setAssembly(save_flags, "pushf"); - - /* - * Create a push 0x<value> instruction - * and link it to the pushf. We are pushing - * the extra value that will end up being - * the third parameter to the callback. - */ - sprintf(pushAsm, "push 0x%08x\n", extra); - push = addNewAssembly(save_flags, pushAsm); - save_flags->SetFallthrough(push); - - /* - * Call the callback. - */ - call = allocateNewInstruction(original->GetAddress()->GetFileID(), - original->GetFunction()); - setAssembly(call, "call 0"); - call->SetComment("call " + callback + " before original."); - /* - * We are only setting up for one parameter - * since the first two are automatically given. - */ - addCallbackHandler64(call, callback, 1); - - /* - * Chain the call operation - * to the push. - */ - push->SetFallthrough(call); - - /* - * 'Unpush' without wasting a register. - */ - rsp_unpush = addNewAssembly(call, "lea rsp, [rsp+8]"); - call->SetFallthrough(rsp_unpush); - - /* - * Restore the CPU flags to their saved values. - */ - restore_flags = addNewAssembly(rsp_unpush, "popf"); - rsp_unpush->SetFallthrough(restore_flags); - - /* - * Restore rsp to its previous location. - */ - rsp_restore = addNewAssembly(restore_flags, "lea rsp, [rsp+128]"); - - /* - * Finish the chain: - * restore flags -> rsp restore - */ - restore_flags->SetFallthrough(rsp_restore); - - /* - * The last step depends on whether - * we are doing the callback before - * or after the instruction. - */ - if (before) - { - /* - * rsp restore -> original instruction - */ - rsp_restore->SetFallthrough(orig); - } - else - { - /* - * Link the end of our chain - * to the original instruction's - * fall through. Then, link the - * original instruction's fall - * through to our chain: - * - * [original] - * [callback invocation code] - * [original's fall through] - */ - rsp_restore->SetFallthrough(original->GetFallthrough()); - original->SetFallthrough(start); - } -} - -int CookbookTransform::execute() -{ - /* - * Our execution function is a series of - * nested loops that will ultimately mean - * that we will see each instruction in the - * program: - * - * for each function - * for each instruction - */ -#ifndef NO_IDAPRO - for ( - set<Function_t*>::const_iterator itf=getFileIR()->GetFunctions().begin(); - itf!=getFileIR()->GetFunctions().end(); - ++itf - ) - { - Function_t* func=*itf; - for ( - set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it - ) - { -#else - set<Instruction_t*> insns = getFileIR()->GetInstructions(); - for ( - set<Instruction_t*>::const_iterator it=insns.begin(); - it!=insns.end(); - ++it - ) - { -#endif - Instruction_t* insn = *it; - unsigned char dbs[2] = {0,}; - - /* - * An Instruction_t has a convenience - * method for accessing the instruction's - * data. For an instruction, the op code - * is always in either the first or first - * and second byte. - */ - dbs[0] = insn->GetDataBits()[0]; - dbs[1] = insn->GetDataBits()[1]; - - /* - * Log the opcode and the instruction's - * comments. These statements will - * show up in the peasoupified program's - * runtime logs/ directory. - */ - printf("%x %x:", dbs[0], dbs[1]); - cout << insn->GetComment() << endl; -#ifndef NO_IDAPRO - } -#endif - } - return 0; -} diff --git a/tools/cookbook/x86_64_linux/functioncall.cpp b/tools/cookbook/x86_64_linux/functioncall.cpp deleted file mode 100644 index 800fa3160..000000000 --- a/tools/cookbook/x86_64_linux/functioncall.cpp +++ /dev/null @@ -1,96 +0,0 @@ -#include "functioncall.hpp" - -#include <assert.h> - - -using namespace libTransform; - -Functioncall::Functioncall(VariantID_t *p_variantID, FileIR_t *p_variantIR, set<std::string> *p_filteredFunctions) : CookbookTransform(p_variantID, p_variantIR, p_filteredFunctions) -{ - -} - -int Functioncall::execute() -{ -#ifndef NO_IDAPRO - for ( - set<Function_t*>::const_iterator itf=getFileIR()->GetFunctions().begin(); - itf!=getFileIR()->GetFunctions().end(); - ++itf - ) - { - Function_t* func=*itf; - for ( - set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it - ) - { -#else - set<Instruction_t*> insns = getFileIR()->GetInstructions(); - for ( - set<Instruction_t*>::const_iterator it=insns.begin(); - it!=insns.end(); - ++it - ) - { -#endif - Instruction_t* insn = *it; - if(insn /*&& insn->GetAddress()*/) - { - if (insn!=NULL && insn->GetFallthrough()!=NULL) - { - string functioncall_callback = string("functioncall_callback"); - unsigned char dbs[1] = {0}; - - /* - * An Instruction_t has a convenience - * method for accessing the instruction's - * data. For an instruction, the op code - * is always in either the first or first - * and second byte. - */ - dbs[0] = insn->GetDataBits()[0]; - - /* - * call is 0xe8 on x64. Check for - * that type of instruction and - * double check that it has a target. - */ - if (dbs[0] == 0xe8 && - insn->GetTarget() - ) - { - /* - * Use the call instruction's target - * to get information about the target - * function using the libtransform API. - */ - Instruction_t *target = insn->GetTarget(); - Function_t *function = target->GetFunction(); - - if (function != NULL && - /* - * Use Function_t's GetName() function - * to determine if the target function - * is the one we want to hook. - * - */ - !function->GetName().compare("function1") - ) - { - /* - * Use CookbookTransform's convenience - * method to add a callback before insn. - */ - addCookbookCallback(insn, functioncall_callback); - } - } - } - } -#ifndef NO_IDAPRO - } -#endif - } - return 0; -} diff --git a/tools/cookbook/x86_64_linux/instructioncount.cpp b/tools/cookbook/x86_64_linux/instructioncount.cpp deleted file mode 100644 index 3ba2245e7..000000000 --- a/tools/cookbook/x86_64_linux/instructioncount.cpp +++ /dev/null @@ -1,145 +0,0 @@ -#include "instructioncount.hpp" - -#include "Rewrite_Utility.hpp" - -#include <assert.h> - -using namespace libTransform; - -InstructionCount::InstructionCount(VariantID_t *p_variantID, FileIR_t *p_variantIR, set<std::string> *p_filteredFunctions) : CookbookTransform(p_variantID, p_variantIR, p_filteredFunctions) -{ - -} - -int InstructionCount::execute() -{ -#ifndef NO_IDAPRO - for( - set<Function_t*>::const_iterator itf=getFileIR()->GetFunctions().begin(); - itf!=getFileIR()->GetFunctions().end(); - ++itf - ) - { - Function_t* func=*itf; - for( - set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it) - { -#else - set<Instruction_t*> insns = getFileIR()->GetInstructions(); - for ( - set<Instruction_t*>::const_iterator it=insns.begin(); - it!=insns.end(); - ++it - ) - { -#endif - Instruction_t* insn = *it; - if(insn&& insn->GetAddress()) - { - if (insn!=NULL&&insn->GetFallthrough()!=NULL) - { - string count_instruction = string("count_instruction"); - - addCookbookCallback(insn, count_instruction, true, NULL); - continue; - - Instruction_t *start = NULL; - Instruction_t *rsp_save = NULL; - Instruction_t *rsp_restore = NULL; - Instruction_t *pushf = NULL; - Instruction_t *popf = NULL; - Instruction_t *orig = NULL; - Instruction_t *call = NULL; - - /* - * We are going to insert some - * new instructions before the current - * one so that we can invoke a callback: - * - * nop - * [save the stack pointer] - * [save the flags] - * [invoke the callback] - * [restore the flags] - * [restore the stack pointer] - * [original instruction] - */ - /* - * Now, insert the "start" instruction (nop) - * before the original instruction. We - * will chain the remainder of our new - * instructions from start. - * - * This function returns a new Instruction_t - * for the original instruction which we - * want to use from now on. - */ - orig = insertAssemblyBefore(getFileIR(), insn, "nop"); - /* - * And the function makes insn the nop. So, - * since that's our "start" instruction, we - * will reassign. - */ - start = insn; - - /* - * Use the so-called Red Zone - * for the invocation of the callback - * function. - */ - rsp_save = allocateNewInstruction( - insn->GetAddress()->GetFileID(), insn->GetFunction()); - start->SetFallthrough(rsp_save); - setAssembly(rsp_save, "lea rsp, [rsp-128]"); - - /* - * Save the CPU flags. - */ - pushf = allocateNewInstruction( - insn->GetAddress()->GetFileID(), insn->GetFunction()); - rsp_save->SetFallthrough(pushf); - setAssembly(pushf, "pushf"); - - /* - * Call the callback. - */ - call = allocateNewInstruction(insn->GetAddress()->GetFileID(), - insn->GetFunction()); - setAssembly(call, "call 0"); - call->SetComment("nop to call " + count_instruction + "."); - addCallbackHandler64(call, count_instruction, 2); - - /* - * Chain the call operation - * to the pushf. - */ - pushf->SetFallthrough(call); - - /* - * Restore the CPU flags. - */ - popf = addNewAssembly(call, "popf"); - call->SetFallthrough(popf); - - /* - * Restore rsp to its previous location. - */ - rsp_restore = addNewAssembly(popf, "lea rsp, [rsp+128]"); - - /* - * Finish the chain: - * popf -> rsp restore - * rsp restore -> original instruction - */ - popf->SetFallthrough(rsp_restore); - rsp_restore->SetFallthrough(orig); - } - } -#ifndef NO_IDAPRO - } -#endif - } - return 0; -} diff --git a/tools/cookbook/x86_64_linux/syscall.cpp b/tools/cookbook/x86_64_linux/syscall.cpp deleted file mode 100644 index e48d54544..000000000 --- a/tools/cookbook/x86_64_linux/syscall.cpp +++ /dev/null @@ -1,75 +0,0 @@ -#include "syscall.hpp" - -#include <assert.h> - - -using namespace libTransform; - -Syscall::Syscall(VariantID_t *p_variantID, FileIR_t *p_variantIR, set<std::string> *p_filteredFunctions) : CookbookTransform(p_variantID, p_variantIR, p_filteredFunctions) -{ - -} - -int Syscall::execute() -{ -#ifndef NO_IDAPRO - for ( - set<Function_t*>::const_iterator itf=getFileIR()->GetFunctions().begin(); - itf!=getFileIR()->GetFunctions().end(); - ++itf - ) - { - Function_t* func=*itf; - for ( - set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it - ) - { -#else - set<Instruction_t*> insns = getFileIR()->GetInstructions(); - for ( - set<Instruction_t*>::const_iterator it=insns.begin(); - it!=insns.end(); - ++it - ) - { -#endif - Instruction_t* insn = *it; - if(insn /*&& insn->GetAddress()*/) - { - if (insn!=NULL && insn->GetFallthrough()!=NULL) - { - string syscall_callback = string("syscall_callback"); - unsigned char dbs[2] = {0,}; - - /* - * An Instruction_t has a convenience - * method for accessing the instruction's - * data. For an instruction, the op code - * is always in either the first or first - * and second byte. - */ - dbs[0] = insn->GetDataBits()[0]; - dbs[1] = insn->GetDataBits()[1]; - - /* - * syscall is two byte instruction - * on x64. - */ - if (dbs[0] == 0x0f && dbs[1] == 0x05 ) - { - /* - * Use CookbookTransform's convenience - * method to add a callback before insn. - */ - addCookbookCallback(insn, syscall_callback); - } - } - } -#ifndef NO_IDAPRO - } -#endif - } - return 0; -} diff --git a/tools/cookbook/x86_64_linux/whitelist.cpp b/tools/cookbook/x86_64_linux/whitelist.cpp deleted file mode 100644 index 96f095828..000000000 --- a/tools/cookbook/x86_64_linux/whitelist.cpp +++ /dev/null @@ -1,102 +0,0 @@ -#include "whitelist.hpp" - -#include <assert.h> - - -using namespace libTransform; - -Whitelistcall::Whitelistcall(VariantID_t *p_variantID, FileIR_t *p_variantIR, set<std::string> *p_filteredFunctions) : CookbookTransform(p_variantID, p_variantIR, p_filteredFunctions) -{ - -} - -int Whitelistcall::execute() -{ -#ifndef NO_IDAPRO - for ( - set<Function_t*>::const_iterator itf=getFileIR()->GetFunctions().begin(); - itf!=getFileIR()->GetFunctions().end(); - ++itf - ) - { - Function_t* func=*itf; - for ( - set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it - ) - { -#else - set<Instruction_t*> insns = getFileIR()->GetInstructions(); - for ( - set<Instruction_t*>::const_iterator it=insns.begin(); - it!=insns.end(); - ++it - ) - { -#endif - Instruction_t* insn = *it; - if(insn /*&& insn->GetAddress()*/) - { - if (insn!=NULL && insn->GetFallthrough()!=NULL) - { - string whitelist_callback = string("whitelist_open_callback"); - unsigned char dbs[1] = {0}; - - /* - * An Instruction_t has a convenience - * method for accessing the instruction's - * data. For an instruction, the op code - * is always in either the first or first - * and second byte. - */ - dbs[0] = insn->GetDataBits()[0]; - - /* - * call is 0xe8 on x64. Check for - * that type of instruction and - * double check that it has a target. - */ - if (dbs[0] == 0xe8 && - insn->GetTarget() - ) - { - /* - * Use the call instruction's target - * to get information about the target - * function using the libtransform API. - */ - Instruction_t *target = insn->GetTarget(); - Function_t *function = target->GetFunction(); - - if (function != NULL && - /* - * Use Function_t's GetName() function - * to determine if the target function - * is the one we want to hook. - * - * NB: The disassembler puts a . before - * the actual function name. So, we - * use the extended version of compare() - * to compensate. - */ - !function->GetName().compare(1, strlen("open"), "open") - ) - { - /* - * Use CookbookTransform's convenience - * method to add a callback after the call - * to open. The callback will take the open()'s - * return value and add it to the whitelist. - */ - addCookbookCallback(insn, whitelist_callback, false); - } - } - } - } -#ifndef NO_IDAPRO - } -#endif - } - return 0; -} diff --git a/tools/cover/Makefile.in b/tools/cover/Makefile.in deleted file mode 100644 index 7bb76e884..000000000 --- a/tools/cover/Makefile.in +++ /dev/null @@ -1,41 +0,0 @@ -# -# Makefile.in - DESCRIPTION. -# -# Copyright (c) 2011 - University of Virginia -# -# This file may be used and modified for non-commercial purposes as long as -# all copyright, permission, and nonwarranty notices are preserved. -# Redistribution is prohibited without prior written consent from the University of Virginia -# -# Please contact the authors for restrictions applying to commercial use. -# -# THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED -# WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF -# MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. -# - - - -CXX=@CXX@ -CC=@CC@ - -CFLAGS= -g -INCLUDE=-I. -I../../include -I../../xform -I../../beaengine/include -I../../libIRDB/include/ -LIBS=-L../../lib -L../../xform -lxform -lIRDB-core -lBeaEngine_s_d -lpqxx -lpq -OBJS=coverage.o - -.SUFFIXES: .o .c .cpp - -.cpp.o .c.o: - $(CXX) $(CFLAGS) $(INCLUDE) -c $< - - -all: cover - echo cover build complete - -clean: - rm -f *.o core cover - -cover: $(OBJS) cover.cpp ../../lib/* - $(CXX) $(CFLAGS) -o cover $(INCLUDE) cover.cpp $(OBJS) $(LIBS) - diff --git a/tools/cover/SConscript b/tools/cover/SConscript deleted file mode 100644 index 99b76265f..000000000 --- a/tools/cover/SConscript +++ /dev/null @@ -1,29 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="cover" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util ") - -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install) - - -Return('install') diff --git a/tools/cover/SConstruct b/tools/cover/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/cover/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/cover/cover.cpp b/tools/cover/cover.cpp deleted file mode 100644 index 8c3e86973..000000000 --- a/tools/cover/cover.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2013, 2014 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include <iostream> -#include "coverage.h" -#include <cstdlib> -#include <fstream> - -using namespace std; -using namespace libIRDB; - -void usage(string prog_name) -{ - cerr << "usage: "<<prog_name<<" <variant_id> <coverage_file> <output_file>" << endl; -} - - -int main(int argc, char **argv) -{ - - if(argc != 4) - { - usage(string(argv[0])); - return -1; - } - - int variant_id = atoi(argv[1]); - string coverage_file_name = string(argv[2]); - string output_file_name = string(argv[3]); - - coverage prog_coverage; - - ifstream coverage_file; - coverage_file.open(coverage_file_name.c_str()); - - if(!coverage_file.is_open()) - { - cerr<<"Coverage Error: Could not open coverage file: "<<coverage_file_name<<endl; - return -1; - } - - prog_coverage.parse_coverage_file(coverage_file); - coverage_file.close(); - - ofstream output_file; - output_file.open(output_file_name.c_str(),ofstream::out); - - if(!output_file.is_open()) - { - cerr<<"Coverage Error: Could not open output file: "<<output_file_name<<endl; - return -1; - } - - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - VariantID_t *vidp; - try - { - vidp = new VariantID_t(variant_id); - assert(vidp->IsRegistered()); - } - catch (DatabaseError_t pnide) - { - cout<<"Unexpected database error: "<<pnide<<endl; - return -1; - } - - prog_coverage.print_function_coverage_file(vidp,output_file); - - output_file.close(); -} - diff --git a/tools/cover/coverage.cpp b/tools/cover/coverage.cpp deleted file mode 100644 index 99cec2e08..000000000 --- a/tools/cover/coverage.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2013, 2014 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include "coverage.h" -#include <cassert> -#include <cerrno> -#include <cstdlib> -#include <limits.h> -#include <string> -#include <fstream> -#include <libgen.h> - - -using namespace std; -using namespace libIRDB; - -void trim(string& str) -{ - string::size_type pos = str.find_last_not_of(' '); - if(pos != string::npos) { - str.erase(pos + 1); - pos = str.find_first_not_of(' '); - if(pos != string::npos) str.erase(0, pos); - } - else str.erase(str.begin(), str.end()); -} - -enum STR2NUM_ERROR { STR2_SUCCESS, STR2_OVERFLOW, STR2_UNDERFLOW, STR2_INCONVERTIBLE }; - -//TODO: what if the string represents a negative number? Currently -//the number will be translated into an unsigned int. I could make this -//and incovertible situation. -STR2NUM_ERROR str2uint (unsigned int &i, char const *s, int base=0) -{ - char *end; - unsigned long l; - errno = 0; - l = strtoul(s, &end, base); - if ((errno == ERANGE && l == ULONG_MAX) || l > UINT_MAX) { - return STR2_OVERFLOW; - } - if (*s == '\0' || *end != '\0') { - return STR2_INCONVERTIBLE; - } - i = l; - - return STR2_SUCCESS; -} - - -void coverage::parse_coverage_file(ifstream &coverage_file) -{ - string line; - while(coverage_file.is_open() && std::getline(coverage_file,line)) - { - trim(line); - - if(line.empty()) - continue; - - string file,addr; - - istringstream iss(line); - - getline(iss,file,'+'); - assert(!file.empty()); - getline(iss,addr,'+'); - - //if addr is empty, assume the entry for file - //is the addr - trim(addr); - if(addr.empty()) - { - addr = file; - file = "a.ncexe"; - } - - - if(coverage_map.find(file) == coverage_map.end()) - { - file_coverage fc; - fc.file = file; - coverage_map[file]=fc; - } - - - unsigned int uint_addr; - assert(str2uint(uint_addr,addr.c_str())==STR2_SUCCESS); - - coverage_map[file].coverage[uint_addr]=uint_addr; - } -} - -file_coverage* coverage::find_file_coverage(string url) -{ - for(map<string, file_coverage >::iterator it=coverage_map.begin(); - it!=coverage_map.end(); ++it) - { - string key = it->first; - - //TODO: for now taking the base name, since that is how - //the shared objects are registered, but this might cause - //issues if shared objects have the same name. - - key=string(basename((char*)key.c_str())); - - if(key.empty()) - continue; - - if(url.find(key)!=string::npos) - { - return &(it->second); - } - } - - return NULL; -} - -void coverage::print_coverage_for_file(file_coverage *fc, FileIR_t *fileirp, ofstream &out_file) -{ - for( - set<Function_t*>::const_iterator func_it=fileirp->GetFunctions().begin(); - func_it!=fileirp->GetFunctions().end(); - ++func_it - ) - { - Function_t *func = *func_it; - if(func==NULL) - continue; - - unsigned int total_ins = func->GetInstructions().size(); - unsigned int covered_ins = 0; - - for( - set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it - ) - { - Instruction_t* instr = *it; - - if(instr==NULL || instr->GetAddress()==NULL) - continue; - - unsigned int addr = (unsigned int) instr->GetAddress()->GetVirtualOffset(); - if(fc->coverage.find(addr)!=fc->coverage.end()) - covered_ins++; - } - - double cov_percent = ((double)covered_ins)/((double)total_ins); - - out_file<<fc->file<<"+"<<func->GetName()<<" "<<cov_percent<<" "<<covered_ins<<" "<<total_ins<<endl; - - } -} - -void coverage::print_function_coverage_file(libIRDB::VariantID_t *vidp,std::ofstream &out_file) -{ - assert(vidp); - - for(set<File_t*>::iterator it=vidp->GetFiles().begin(); - it!=vidp->GetFiles().end(); - ++it - ) - { - File_t* this_file=*it; - assert(this_file); - - // read the db - FileIR_t *fileirp=new FileIR_t(*vidp,this_file); - assert(fileirp); - - //NULL fc should only happen if the coverage file is empty. - //TODO: add extra sanity checks to make sure that null only happens under these conditions. - file_coverage* fc = find_file_coverage(fileirp->GetFile()->GetURL()); - if(fc!=NULL) - { - print_coverage_for_file(fc, fileirp, out_file); - } - - delete fileirp; - } -} diff --git a/tools/cover/coverage.h b/tools/cover/coverage.h deleted file mode 100644 index 1af11b9fb..000000000 --- a/tools/cover/coverage.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2013, 2014 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#ifndef __PEASOUP_COVERAGE -#define __PEASOUP_COVERAGE - -#include <map> -#include <libIRDB-core.hpp> -#include <iostream> -#include <string> - -struct file_coverage -{ - std::string file; - std::map<unsigned int,unsigned int> coverage; -}; - -class coverage -{ -private: - std::map<std::string,file_coverage> coverage_map; - - file_coverage* find_file_coverage(std::string url); - void print_coverage_for_file(file_coverage *fc, libIRDB::FileIR_t *fileirp, std::ofstream &out_file); -public: - void parse_coverage_file(std::ifstream &coverage_file); - void print_function_coverage_file(libIRDB::VariantID_t *vidp,std::ofstream &out_file); -}; - -#endif diff --git a/tools/fix_canaries/SConscript b/tools/fix_canaries/SConscript deleted file mode 100644 index b678e79b8..000000000 --- a/tools/fix_canaries/SConscript +++ /dev/null @@ -1,28 +0,0 @@ -import os - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libEXEIO/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - $SECURITY_TRANSFORMS_HOME/xform - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - ''' - -# $SECURITY_TRANSFORMS_HOME/libtransform/include -CPPFLAGS="--std=c++11" -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ "IRDB-core IRDB-cfg IRDB-util pqxx BeaEngine_s_d transform MEDSannotation") - -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -myenv.Append(CPPFLAGS=CPPFLAGS) - -pgm=myenv.Program(target="fix_canaries.exe", source=Split("fix_canaries.cpp fix_canaries_driver.cpp"), LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/plugins_install/", pgm) -Default(install) -Return('install') diff --git a/tools/fix_canaries/SConstruct b/tools/fix_canaries/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/fix_canaries/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/fix_canaries/fix_canaries.cpp b/tools/fix_canaries/fix_canaries.cpp deleted file mode 100644 index 94d1d5313..000000000 --- a/tools/fix_canaries/fix_canaries.cpp +++ /dev/null @@ -1,595 +0,0 @@ -#include "fix_canaries.hpp" - -#include "Rewrite_Utility.hpp" -#include <assert.h> -#include <stdexcept> -#include "beaengine/BeaEngine.h" - -using namespace libTransform; -using namespace ELFIO; -using namespace libIRDB; - -FixCanaries::FixCanaries(FileIR_t *p_variantIR) : - Transform(NULL, p_variantIR, NULL), m_verbose(true) -{ - -} - -FixCanaries::~FixCanaries() -{ -} - -void FixCanaries::set_callback(const std::string &callback) { - m_callback = callback; -} - -void FixCanaries::LoadElf() -{ - unsigned int elfoid=0; - pqxxDB_t *interface=NULL; - - if (m_elfiop) - return; - - elfoid = getFileIR()->GetFile()->GetELFOID(); - interface = dynamic_cast<pqxxDB_t*>(BaseObj_t::GetInterface()); - - assert(interface); - - file_object.reset( - new pqxx::largeobjectaccess(interface->GetTransaction(), - elfoid, - std::ios::in)); - - file_object->to_file("tmp.exe"); - - m_elfiop.reset(new ELFIO::elfio); - m_elfiop->load("tmp.exe"); -} - -void FixCanaries::FindStartAddress() -{ - assert(m_elfiop != NULL); - m_start_addr = m_elfiop->get_entry(); - cout << "m_start_addr: 0x" << std::hex << m_start_addr << endl; -} - -Instruction_t *FixCanaries::add_instrumentation(Instruction_t *site, - const char *canary_register, const char *callback_name, const char *lea) -{ - FileIR_t *firp = getFileIR(); - virtual_offset_t postCallbackReturn = getAvailableAddress(); - char pushRetBuf[100], movCanaryValueBuf[100], movfs0x28Buf[100], setRdx[100]; - sprintf(pushRetBuf,"push 0x%x", postCallbackReturn); - sprintf(movCanaryValueBuf,"mov rsi, %s", canary_register); - sprintf(movfs0x28Buf,"mov rdi, [fs:0x28]"); - - if (lea != NULL) - sprintf(setRdx,"lea rdx, [%s]", lea); - - Instruction_t *tmp=site, *callback=NULL, *post_callback=NULL; - - tmp=::insertAssemblyAfter(firp,tmp,"push rsp"); - tmp=insertAssemblyAfter(firp,tmp,"push rbp"); - tmp=insertAssemblyAfter(firp,tmp,"push rdi"); - tmp=insertAssemblyAfter(firp,tmp,"push rsi"); - tmp=insertAssemblyAfter(firp,tmp,"push rdx"); - tmp=insertAssemblyAfter(firp,tmp,"push rcx"); - tmp=insertAssemblyAfter(firp,tmp,"push rbx"); - tmp=insertAssemblyAfter(firp,tmp,"push rax"); - tmp=insertAssemblyAfter(firp,tmp,"push r8"); - tmp=insertAssemblyAfter(firp,tmp,"push r9"); - tmp=insertAssemblyAfter(firp,tmp,"push r10"); - tmp=insertAssemblyAfter(firp,tmp,"push r11"); - tmp=insertAssemblyAfter(firp,tmp,"push r12"); - tmp=insertAssemblyAfter(firp,tmp,"push r13"); - tmp=insertAssemblyAfter(firp,tmp,"push r14"); - tmp=insertAssemblyAfter(firp,tmp,"push r15"); - tmp=insertAssemblyAfter(firp,tmp,"pushf"); - tmp=insertAssemblyAfter(firp,tmp,movfs0x28Buf); - tmp=insertAssemblyAfter(firp,tmp,movCanaryValueBuf); - if (lea != NULL) - tmp=insertAssemblyAfter(firp,tmp,setRdx); - else - tmp=insertAssemblyAfter(firp,tmp,"mov rdx, 0x0"); - /* - * The "bogus" return address that we push here - * will be popped by the callback handler - * invocation code in zipr. - */ - tmp=insertAssemblyAfter(firp,tmp,pushRetBuf); // push <ret addr> - - callback=tmp=insertAssemblyAfter(firp,tmp,"nop"); - callback->SetCallback(callback_name); - - post_callback=tmp=insertAssemblyAfter(firp,tmp,"popf"); - post_callback->GetAddress()->SetVirtualOffset(postCallbackReturn); - - tmp=insertAssemblyAfter(firp,tmp,"pop r15"); - tmp=insertAssemblyAfter(firp,tmp,"pop r14"); - tmp=insertAssemblyAfter(firp,tmp,"pop r13"); - tmp=insertAssemblyAfter(firp,tmp,"pop r12"); - tmp=insertAssemblyAfter(firp,tmp,"pop r11"); - tmp=insertAssemblyAfter(firp,tmp,"pop r10"); - tmp=insertAssemblyAfter(firp,tmp,"pop r9"); - tmp=insertAssemblyAfter(firp,tmp,"pop r8"); - tmp=insertAssemblyAfter(firp,tmp,"pop rax"); - tmp=insertAssemblyAfter(firp,tmp,"pop rbx"); - tmp=insertAssemblyAfter(firp,tmp,"pop rcx"); - tmp=insertAssemblyAfter(firp,tmp,"pop rdx"); - tmp=insertAssemblyAfter(firp,tmp,"pop rsi"); - tmp=insertAssemblyAfter(firp,tmp,"pop rdi"); - tmp=insertAssemblyAfter(firp,tmp,"pop rbp"); - tmp=insertAssemblyAfter(firp,tmp,"lea rsp, [rsp+8]"); - - return tmp; -} - -int FixCanaries::execute() -{ - uint64_t adjusted_size = 1; - - LoadElf(); - FindStartAddress(); -#if 0 - for( - set<Function_t*>::const_iterator itf=getFileIR()->GetFunctions().begin(); - itf!=getFileIR()->GetFunctions().end(); - ++itf - ) - { - Function_t* func=*itf; -#endif - for( -// set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - set<Instruction_t*>::const_iterator it=getFileIR()->GetInstructions().begin(); -// it!=func->GetInstructions().end(); - it!=getFileIR()->GetInstructions().end(); - ++it) - { - DISASM d; - Instruction_t* insn = *it; - - insn->Disassemble(d); - - if (insn->GetAddress()->GetVirtualOffset() == m_start_addr) { - if (m_verbose) - cout << "Found and hooked the start instruction." << endl; - add_instrumentation(insn, "rsp", "zipr_set_top_of_stack"); - } - /* - * Check to see if this is the push canary - * operation. - * mov target_reg_name, [fs:0xfs_displacement] - * mov rsp_displacement(rsp_reg_name), target_reg_name - * |---rsp_reg_and_offset-------| - */ - else if ((d.Instruction.Category & 0xFFFF) == DATA_TRANSFER && - d.Argument2.SegmentReg == FSReg && - d.Argument2.Memory.Displacement == 0x28 && - d.Argument1.ArgType & REGISTER_TYPE) { - DISASM md; - Instruction_t *mov_insn; - - bool numeric_register = false; - - int i = 0; - - char *target_reg_name = NULL; - uint16_t target_reg_value = 0; - char target_ereg_name[256] = {0,}; - char target_sreg_name[256] = {0,}; - - char *rsp_sreg_name = NULL, *rsp_reg_and_offset = NULL; - char rsp_reg_name[256] = {0,}; - - char asm_buffer[256] = {0,}; - int64_t fs_displacement = 0, rsp_displacement = 0; - uint64_t abs_rsp_displacement = 0; - - if (!(mov_insn = insn->GetFallthrough())) - continue; - - /* - * Setup the target register information. - */ - target_reg_value = d.Argument1.ArgType & 0xFFFF; - target_reg_name = d.Argument1.ArgMnemonic; - - /* - * Two cases here: - * 1: There is rax,rcx,rdx, etc. - * 2: There is r12, r11, etc. - */ - i = 0; - while (target_reg_name[i] != '\0') { - if (((int)target_reg_name[i]) >= ((int)'0') && - ((int)target_reg_name[i]) <= ((int)'9')) - { - numeric_register = true; - break; - } - i++; - } - if (!numeric_register) - { - strcpy(target_ereg_name, target_reg_name); - strcpy(target_sreg_name, target_reg_name+1); - target_ereg_name[0] = 'e'; - } else { - strcpy(target_ereg_name, target_reg_name); - strcpy(target_sreg_name, target_reg_name); - strcat(target_ereg_name, "d"); - strcat(target_sreg_name, "w"); - } - - fs_displacement = d.Argument2.Memory.Displacement; - - mov_insn->Disassemble(md); - - if ((md.Instruction.Category & 0xFFFF) ==DATA_TRANSFER && - (md.Argument1.Memory.BaseRegister == 0x10 || - md.Argument1.Memory.BaseRegister == 0x20 - ) && - md.Argument2.ArgType & REGISTER_TYPE && - (md.Argument2.ArgType & 0xFFFF) == target_reg_value) { - Instruction_t *tmp_insn; - int i = 0; - char *displacement_operation = NULL; - - rsp_displacement = md.Argument1.Memory.Displacement; - rsp_reg_and_offset = md.Argument1.ArgMnemonic; - strcpy(rsp_reg_name, rsp_reg_and_offset); - while (rsp_reg_name[i] != '\0' && - rsp_reg_name[i] != '+' && - rsp_reg_name[i] != '-') i++; - rsp_reg_name[i] = '\0'; - rsp_sreg_name = rsp_reg_name + 1; - - if (m_verbose == true) { - cout << "Load Canary Instr: " << d.CompleteInstr << endl; - cout << "Push Canary Instr: " << md.CompleteInstr << endl; - cout << "Mov Base Register: 0x" << std::hex << md.Argument1.Memory.BaseRegister <<endl; - cout << "FS displacement: 0x" << std::hex << fs_displacement <<endl; - cout << "Target register: " << endl; - cout << "\tvalue: 0x" << std::hex << target_reg_value << endl; - cout << "\tnames: " << target_reg_name << ", " - << target_ereg_name << ", " - << target_sreg_name << endl; - cout << "RSP register: " << endl; - cout << "\tregister and offset: " << rsp_reg_and_offset << endl; - cout << "\tnames: " << rsp_reg_name << ", " - << rsp_sreg_name << endl; - cout << "\tdisplacement: 0x"<<std::hex<<rsp_displacement <<endl; - } - - /* - * Move canary reference value into register. - */ - sprintf(asm_buffer, "mov %s, [fs:0x%x]\n", - target_reg_name, - fs_displacement); - if (m_verbose == true) - cout << "asm_buffer: " << asm_buffer; - setAssembly(insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - /* - * target register has - * xxxxxxxxxxxxaaaa - * where aaaa is 16 bits of stack address - * and x...x is canary value. - */ - - /* - * Calculate the difference between the stack pointer - * (the lowest 16 bits, actually!) and the previously - * saved stack pointer (lower 16 bits of target register, - * accessed through its 16-bit name). - */ - sprintf(asm_buffer, "sub %s, %s\n", target_sreg_name, rsp_sreg_name); - if (m_verbose == true) - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - /* - * target register contains the offset from current - * stack pointer to the location of the canary - * above us. - */ - - /* - * But, we need to be careful because we aren't actually - * now at the top of the stack with rsp. It's been adjusted - * by the size of the locals. Adjust based on that. - */ - if (rsp_displacement<0) { - abs_rsp_displacement = rsp_displacement*-1; - displacement_operation = "add"; - } else { - displacement_operation = "sub"; - abs_rsp_displacement = rsp_displacement; - } - sprintf(asm_buffer, "%s %s, 0x%x\n", - displacement_operation, - target_sreg_name, - abs_rsp_displacement); - if (m_verbose == true) - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - /* - * Finally, put the canary value on to the stack. - */ - sprintf(asm_buffer, "mov [%s], %s\n", - rsp_reg_and_offset, - target_reg_name); - if (m_verbose == true) - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - if (m_callback.length() != 0) { - tmp_insn = add_instrumentation( - tmp_insn, - target_reg_name, - m_callback.c_str(), rsp_reg_and_offset); - tmp_insn->SetFallthrough(mov_insn); - } - - /* - * Save canary+top of stack back to canary - * reference value. - */ - - /* - * Keep all of the canary reference value - * except for the 16 bits that hold the - * top of stack value. - */ - sprintf(asm_buffer, "mov %s, 0xFFFFFFFFFFFF0000\n", target_reg_name); - if (m_verbose == true) - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "and %s, [fs:0x%x]\n", - target_reg_name, - fs_displacement); - if (m_verbose == true) - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - /* - * Put the top of into those empty 16 bits. Use - * an add here and the 16-bit name of the target - * register to do it easily. - */ - sprintf(asm_buffer, "add %s, %s\n", target_sreg_name, rsp_sreg_name); - if (m_verbose == true) - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - if (rsp_displacement<0) { - abs_rsp_displacement = rsp_displacement*-1; - displacement_operation = "sub"; - } else { - abs_rsp_displacement = rsp_displacement; - displacement_operation = "add"; - } - sprintf(asm_buffer, "%s %s, 0x%x\n", - displacement_operation, - target_sreg_name, - abs_rsp_displacement); - if (m_verbose == true) - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - /* - * Now, deposit that value back into the - * canary reference value. - */ - sprintf(asm_buffer, "mov [fs:0x%x], %s\n", - fs_displacement, - target_sreg_name); - if (m_verbose == true) - cout << "asm_buffer: " << asm_buffer; - setAssembly(mov_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - if (m_callback.length() != 0) { - Instruction_t *t = mov_insn->GetFallthrough(); - tmp_insn=add_instrumentation( - mov_insn, - target_reg_name, - m_callback.c_str()); - tmp_insn->SetFallthrough(t); - } - } - } - /* - * Check to see if this is the start of the pop canary - * operation. - */ - else if ((d.Instruction.Category & 0xFFFF) == DATA_TRANSFER) { - DISASM xd; - - uint16_t target_reg_value = 0; - char *target_reg_name = NULL; - char target_ereg_name[256] = {0,}; - char target_sreg_name[256] = {0,}; - - char *rsp_reg_and_offset = NULL; - char rsp_reg_name[256] = {0,}; - char *rsp_sreg_name = NULL; - - int distance = 0, max_distance = 2; - Instruction_t *xor_insn = NULL; - bool followed_by_xor = false; - - /* - * We are looking for - * mov target_reg_name, rsp_displacement(rsp_reg_name) - * |---rsp_reg_and_offset-------| - * followed (closely [within max_distance]) by - * xor target_reg_name, qword [fs:0xfs_displacement] - */ - if (d.Argument2.ArgType & MEMORY_TYPE && - (d.Argument2.Memory.BaseRegister == 0x10 || - d.Argument2.Memory.BaseRegister == 0x20 - ) && - ((d.Argument1.ArgType & 0xFFFF0000)==(REGISTER_TYPE+GENERAL_REG))) { - - target_reg_value = d.Argument1.ArgType & 0xFFFF; - target_reg_name = d.Argument1.ArgMnemonic; - - xor_insn = insn->GetFallthrough(); - while (xor_insn != NULL && distance < max_distance) { - xor_insn->Disassemble(xd); - if ((xd.Instruction.Category & 0xFFFF) == LOGICAL_INSTRUCTION && - xd.Argument2.SegmentReg == FSReg && - xd.Argument2.Memory.Displacement == 0x28 && - xd.Argument1.ArgType & REGISTER_TYPE && - (xd.Argument1.ArgType & 0xFFFF) == target_reg_value) { - followed_by_xor = true; - break; - } - distance++; - xor_insn = xor_insn->GetFallthrough(); - } - if (followed_by_xor == true) { - char asm_buffer[256] = {0,}; - Instruction_t *tmp_insn; - int64_t fs_displacement = 0; - int i = 0; - bool numeric_register = false; - - rsp_reg_and_offset = d.Argument2.ArgMnemonic; - strcpy(rsp_reg_name, rsp_reg_and_offset); - i = 0; - while (rsp_reg_name[i] != '\0' && - rsp_reg_name[i] != '+' && - rsp_reg_name[i] != '-') i++; - rsp_reg_name[i] = '\0'; - rsp_sreg_name = rsp_reg_name + 1; - - /* - * Two cases here: - * 1: There is rax,rcx,rdx, etc. - * 2: There is r12, r11, etc. - * - * See (above) for additional description - * of how we are handling this. - */ - i = 0; - while (target_reg_name[i] != '\0') { - if (((int)target_reg_name[i]) >= ((int)'0') && - ((int)target_reg_name[i]) <= ((int)'9')) - { - numeric_register = true; - break; - } - i++; - } - if (!numeric_register) - { - strcpy(target_ereg_name, target_reg_name); - strcpy(target_sreg_name, target_reg_name+1); - target_ereg_name[0] = 'e'; - } else { - strcpy(target_ereg_name, target_reg_name); - strcpy(target_sreg_name, target_reg_name); - strcat(target_ereg_name, "d"); - strcat(target_sreg_name, "w"); - } - fs_displacement = xd.Argument2.Memory.Displacement; - - if (m_verbose == true) { - cout << "Load Complete Instr: " << d.CompleteInstr << endl; - cout << "XOR Complete Instr: " << xd.CompleteInstr << endl; - cout << "Load base register : 0x" << std::hex - << (d.Argument2.Memory.BaseRegister) << endl; - cout << "FS displacement: 0x"<<std::hex << fs_displacement <<endl; - cout << "Target register: " << endl; - cout << "\tvalue: 0x" << std::hex << target_reg_value << endl; - cout << "\tnames: " << target_reg_name << ", " - << target_ereg_name << ", " - << target_sreg_name << endl; - cout << "RSP register: " << endl; - cout << "\tregister and offset: " << rsp_reg_and_offset << endl; - cout << "\tnames: " << rsp_reg_name << ", " - << rsp_sreg_name << endl; - } - - /* - * Get the canary from the stack and put it in - * the target register. - */ - sprintf(asm_buffer, "mov %s, [%s]\n", - target_reg_name, - rsp_reg_and_offset); - if (m_verbose == true) - cout << "asm_buffer: " << asm_buffer; - setAssembly(insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - /* - * Jump back to the previous top of stack - * using canary reference value - * and store that in the lower 16 of the target. - */ - sprintf(asm_buffer, "add %s, [fs:0x%x]\n", - target_sreg_name, - fs_displacement); - if (m_verbose == true) - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - /* - * Move just those updated 16 bits back into - * the canary reference buffer. - */ - sprintf(asm_buffer, "mov [fs:0x%x], %s\n", - fs_displacement, target_sreg_name); - if (m_verbose == true) - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - if (m_callback.length() != 0) { - tmp_insn = add_instrumentation( - tmp_insn, - target_reg_name, - m_callback.c_str()); - tmp_insn->SetFallthrough(xor_insn); - } - - /* - * Since this code did not touch the upper - * 64-16 bits of the canary value on the - * stack or the canary reference value, - * any tampering should be evident through - * an xor. - */ - sprintf(asm_buffer, "xor %s, [fs:0x%x]\n", - target_reg_name, - fs_displacement); - if (m_verbose == true) - cout << "asm_buffer: " << asm_buffer; - setAssembly(xor_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - } - } - } - } -#if 0 - } -#endif - return true; -} diff --git a/tools/fix_canaries/fix_canaries.hpp b/tools/fix_canaries/fix_canaries.hpp deleted file mode 100644 index fd4ae83e5..000000000 --- a/tools/fix_canaries/fix_canaries.hpp +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef _LIBTRANSFORM_FIX_CANARIES_H_ -#define _LIBTRANSFORM_FIX_CANARIES_H_ - -#include "../../libtransform/include/transform.hpp" -#include "../../libMEDSannotation/include/VirtualOffset.hpp" -#include <libIRDB-core.hpp> -#include <libIRDB-cfg.hpp> -#include <libIRDB-syscall.hpp> -#include "elfio/elfio.hpp" -#include <functional> - -using namespace std; -using namespace libIRDB; -class FixCanaries : public libTransform::Transform -{ - public: - FixCanaries(FileIR_t*p_variantIR); - int execute(); - ~FixCanaries(); - void set_verbose(bool v) { m_verbose = v; } - void set_callback(const std::string &); - private: - libIRDB::Instruction_t *add_instrumentation(libIRDB::Instruction_t *, const char *, const char *, const char *lea = NULL); - void LoadElf(); - void FindStartAddress(); - std::unique_ptr<ELFIO::elfio> m_elfiop; - std::unique_ptr<pqxx::largeobjectaccess> file_object; - bool m_verbose = false; - std::string m_callback; - ELFIO::Elf64_Addr m_start_addr; -}; -#endif diff --git a/tools/fix_canaries/fix_canaries_driver.cpp b/tools/fix_canaries/fix_canaries_driver.cpp deleted file mode 100644 index 34d72806d..000000000 --- a/tools/fix_canaries/fix_canaries_driver.cpp +++ /dev/null @@ -1,123 +0,0 @@ -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "fix_canaries.hpp" - -using namespace std; -using namespace libIRDB; - -void usage(const char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id> [-v] [-c <callback>]\n"; -} - -int main(int argc, char **argv) -{ - pqxxDB_t pqxx_interface; - VariantID_t *pidp=NULL; - int variantID; - string programName; - bool verbose = false; - string callbackName; - bool parsed_parameters = true; - - programName = string(argv[0]); - if(argc < 2) - { - parsed_parameters = false; - } else { - variantID = atoi(argv[1]); - argv+=2; - } - - while (parsed_parameters && *argv != NULL) { - if (!strcmp("-v", *argv)) { - verbose = true; - } else if (!strcmp("-c", *argv)) { - argv++; - if (*argv == NULL) { - cerr << "-c requires a parameter." << endl; - } else { - callbackName = string(*argv); - } - } - argv++; - } - - if (!parsed_parameters) { - usage(programName.c_str()); - exit(1); - } - - if (verbose) { - cout << "verbose: " << verbose << endl; - cout << "callback: " << callbackName << endl; - cout << "variant: " << variantID << endl; - } - - /* setup the interface to the sql server */ - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - cout<<"fix_canaries_driver.exe started\n"; - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - cout<<"Transforming "<<this_file->GetURL()<<endl; - - assert(firp && pidp); - - try - { - FixCanaries fixcanaries(firp); - - if (verbose) { - fixcanaries.set_verbose(verbose); - } - if (callbackName.length() != 0) { - fixcanaries.set_callback(callbackName); - } - - int success=fixcanaries.execute(); - - if (success) - { - cout<<"Writing changes for "<<this_file->GetURL()<<endl; - one_success = true; - firp->WriteToDB(); - delete firp; - } - else - { - cout<<"Skipping (no changes) "<<this_file->GetURL()<<endl; - } - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - // if any integer transforms for any files succeeded, we commit - if (one_success) - { - cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); - } - - return 0; -} diff --git a/tools/fix_canaries/fix_canaries_xor.cpp b/tools/fix_canaries/fix_canaries_xor.cpp deleted file mode 100644 index 9d0bc63cd..000000000 --- a/tools/fix_canaries/fix_canaries_xor.cpp +++ /dev/null @@ -1,350 +0,0 @@ -#include "fix_canaries.hpp" - -#include "Rewrite_Utility.hpp" -#include <assert.h> -#include <stdexcept> -#include "beaengine/BeaEngine.h" - -using namespace libTransform; -using namespace ELFIO; -using namespace libIRDB; - -FixCanaries::FixCanaries(FileIR_t *p_variantIR) : - Transform(NULL, p_variantIR, NULL), m_verbose(true) -{ - -} - -FixCanaries::~FixCanaries() -{ -} - -void FixCanaries::LoadElf() -{ - unsigned int elfoid=0; - pqxxDB_t *interface=NULL; - - if (m_elfiop) - return; - - elfoid = getFileIR()->GetFile()->GetELFOID(); - interface = dynamic_cast<pqxxDB_t*>(BaseObj_t::GetInterface()); - - assert(interface); - - file_object.reset( - new pqxx::largeobjectaccess(interface->GetTransaction(), - elfoid, - std::ios::in)); - - file_object->to_file("tmp.exe"); - - m_elfiop.reset(new ELFIO::elfio); - m_elfiop->load("tmp.exe"); -} - -void FixCanaries::CalculateBaseAndSize() -{ - assert(m_elfiop != NULL); - ELFIO::section *text_section = m_elfiop->sections[".text"]; - - m_text_base = text_section->get_address(); - m_text_size = text_section->get_size(); -} -Instruction_t *FixCanaries::add_instrumentation(Instruction_t *site, - const char *canary_register) -{ - FileIR_t *firp = getFileIR(); - virtual_offset_t postCallbackReturn = getAvailableAddress(); - char pushRetBuf[100], movCanaryValueBuf[100], movfs0x28Buf[100]; - sprintf(pushRetBuf,"push 0x%x", postCallbackReturn); - sprintf(movCanaryValueBuf,"mov rsi, %s", canary_register); - sprintf(movfs0x28Buf,"mov rdi, [fs:0x28]"); - - Instruction_t *tmp=site, *callback=NULL, *post_callback=NULL; - - tmp=insertAssemblyAfter(firp,tmp,"push rsp"); - tmp=insertAssemblyAfter(firp,tmp,"push rbp"); - tmp=insertAssemblyAfter(firp,tmp,"push rdi"); - tmp=insertAssemblyAfter(firp,tmp,"push rsi"); - tmp=insertAssemblyAfter(firp,tmp,"push rdx"); - tmp=insertAssemblyAfter(firp,tmp,"push rcx"); - tmp=insertAssemblyAfter(firp,tmp,"push rbx"); - tmp=insertAssemblyAfter(firp,tmp,"push rax"); - tmp=insertAssemblyAfter(firp,tmp,"push r8"); - tmp=insertAssemblyAfter(firp,tmp,"push r9"); - tmp=insertAssemblyAfter(firp,tmp,"push r10"); - tmp=insertAssemblyAfter(firp,tmp,"push r11"); - tmp=insertAssemblyAfter(firp,tmp,"push r12"); - tmp=insertAssemblyAfter(firp,tmp,"push r13"); - tmp=insertAssemblyAfter(firp,tmp,"push r14"); - tmp=insertAssemblyAfter(firp,tmp,"push r15"); - tmp=insertAssemblyAfter(firp,tmp,"pushf"); - tmp=insertAssemblyAfter(firp,tmp,movfs0x28Buf); - tmp=insertAssemblyAfter(firp,tmp,movCanaryValueBuf); - /* - * The "bogus" return address that we push here - * will be popped by the callback handler - * invocation code in zipr. - */ - tmp=insertAssemblyAfter(firp,tmp,pushRetBuf); // push <ret addr> - - callback=tmp=insertAssemblyAfter(firp,tmp,"nop"); - callback->SetCallback("zipr_debug_canary_callback"); - - post_callback=tmp=insertAssemblyAfter(firp,tmp,"popf"); - post_callback->GetAddress()->SetVirtualOffset(postCallbackReturn); - - tmp=insertAssemblyAfter(firp,tmp,"pop r15"); - tmp=insertAssemblyAfter(firp,tmp,"pop r14"); - tmp=insertAssemblyAfter(firp,tmp,"pop r13"); - tmp=insertAssemblyAfter(firp,tmp,"pop r12"); - tmp=insertAssemblyAfter(firp,tmp,"pop r11"); - tmp=insertAssemblyAfter(firp,tmp,"pop r10"); - tmp=insertAssemblyAfter(firp,tmp,"pop r9"); - tmp=insertAssemblyAfter(firp,tmp,"pop r8"); - tmp=insertAssemblyAfter(firp,tmp,"pop rax"); - tmp=insertAssemblyAfter(firp,tmp,"pop rbx"); - tmp=insertAssemblyAfter(firp,tmp,"pop rcx"); - tmp=insertAssemblyAfter(firp,tmp,"pop rdx"); - tmp=insertAssemblyAfter(firp,tmp,"pop rsi"); - tmp=insertAssemblyAfter(firp,tmp,"pop rdi"); - tmp=insertAssemblyAfter(firp,tmp,"pop rbp"); - tmp=insertAssemblyAfter(firp,tmp,"lea rsp, [rsp+8]"); - - return tmp; -} - -int FixCanaries::execute() -{ - uint64_t adjusted_size = 1; - - LoadElf(); - CalculateBaseAndSize(); - - cout << "base: " << std::hex << m_text_base << endl; - cout << "size: " << std::hex << m_text_size << endl; - - /* - * Let's find the biggest, without going over. - * We need this to be a power of 2. - */ - while (adjusted_size<m_text_size) adjusted_size |= adjusted_size<<1; - m_text_size = adjusted_size>>1; - m_text_size &= ~((uint64_t)8); - - cout << "m_text_size: " << std::hex << m_text_size << endl; - - /* - * So, anything between base and base+size - * are valid for us to pick values from. - */ - - for( - set<Function_t*>::const_iterator itf=getFileIR()->GetFunctions().begin(); - itf!=getFileIR()->GetFunctions().end(); - ++itf - ) - { - Function_t* func=*itf; - for( - set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it) - { - DISASM d; - Instruction_t* insn = *it; - - insn->Disassemble(d); - - /* - * Check to see if this is the push canary - * operation. - */ - if ((d.Instruction.Category & 0xFFFF) == DATA_TRANSFER && - d.Argument2.SegmentReg == FSReg && - d.Argument2.Memory.Displacement == 0x28 && - d.Argument1.ArgType & REGISTER_TYPE) { - int64_t displacement = 0; - uint16_t reg_value = 0; - char *reg_name = NULL; - char asm_buffer[256] = {0,}; - char ereg_name[256] = {0,}; - Instruction_t *tmp_insn; - Instruction_t *original_fallthrough; - - original_fallthrough = insn->GetFallthrough(); - assert(original_fallthrough); - - reg_value = d.Argument1.ArgType & 0xFFFF; - displacement = d.Argument2.Memory.Displacement; - - reg_name = d.Argument1.ArgMnemonic; - strcpy(ereg_name, reg_name); - ereg_name[0] = 'e'; - - if (m_verbose == true) { - cout << "Complete Instr: " << d.CompleteInstr << endl; - cout << "reg_value: 0x" << std::hex << reg_value << endl; - cout << "reg name : " << reg_name << endl; - cout << "displacement: 0x" << std::hex << displacement << endl; - } - /* - * The output of this instruction goes in reg_name. - * That value will be the value stored on the stack - * as the canary. - */ - - sprintf(asm_buffer, "mov %s, 0xFFFFFFFF%08x\n", reg_name, m_text_size); - cout << "asm_buffer: " << asm_buffer; - setAssembly(insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "and %s, [fs:0x%x]\n", reg_name, displacement); - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "add %s, 0x%x\n", reg_name, m_text_base); - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "mov [fs:0x%x], %s\n", displacement, reg_name); - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "mov %s, [%s]\n", reg_name, ereg_name); - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "shr %s, 32\n", reg_name); - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "shl %s, 32\n", reg_name); - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "xor %s, [fs:0x%x]\n", reg_name, displacement); - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "rol %s, 32\n", reg_name); - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - /* - * Callback will print values of rax (what we are - * about to push as the canary value) and fs:0x28 - * (the value of the key and index). - */ - tmp_insn = add_instrumentation(tmp_insn, reg_name); - - tmp_insn->SetFallthrough(original_fallthrough); - } - /* - * Check to see if this is the start of the pop canary - * operation. - */ - if ((d.Instruction.Category & 0xFFFF) == DATA_TRANSFER) { - uint16_t storage_reg_value = 0; - int distance = 0, max_distance = 2; - Instruction_t *xor_instruction = NULL; - bool followed_by_xor = false; - - /* - * We are looking for - * mov A, qword [rsp+0x??] - * followed (closely) by - * xor A, qword [fs:0x28] - */ - if (d.Argument2.ArgType & MEMORY_TYPE && - /* d.Argument2.Memory.BaseRegister == 0x10 && *//* RSP */ - d.Argument1.ArgType & REGISTER_TYPE) { - storage_reg_value = d.Argument1.ArgType & 0xFFFF; - - DISASM xd; - xor_instruction = insn->GetFallthrough(); - while (xor_instruction != NULL && distance < max_distance) { - xor_instruction->Disassemble(xd); - if ((xd.Instruction.Category & 0xFFFF) == LOGICAL_INSTRUCTION && - xd.Argument2.SegmentReg == FSReg && - xd.Argument2.Memory.Displacement == 0x28 && - xd.Argument1.ArgType & REGISTER_TYPE && - (xd.Argument1.ArgType & 0xFFFF) == storage_reg_value) { - followed_by_xor = true; - break; - } - distance++; - xor_instruction = xor_instruction->GetFallthrough(); - } - if (followed_by_xor == true) { - if (m_verbose == true) { - cout << "Complete Instr: " << d.CompleteInstr << endl; - cout << "Complete Instr: " << xd.CompleteInstr << endl; - cout << endl; - } - char *rsp; - char *reg_name; - char ereg_name[256] = {0,}; - char asm_buffer[256] = {0,}; - Instruction_t *tmp_insn; - int64_t displacement = 0; - - rsp = d.Argument2.ArgMnemonic; - - reg_name = d.Argument1.ArgMnemonic; - strcpy(ereg_name, reg_name); - ereg_name[0] = 'e'; - - displacement = xd.Argument2.Memory.Displacement; - - sprintf(asm_buffer, "mov %s, [%s]\n",reg_name,rsp); - cout << "asm_buffer: " << asm_buffer; - setAssembly(insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "rol %s, 32\n",reg_name); - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "mov %s, [%s]\n",reg_name,ereg_name); - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "xor %s, [fs:0x%x]\n",reg_name,displacement); - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "shr %s, 32\n",reg_name); - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "xor %s, [%s]\n",reg_name,rsp); - cout << "asm_buffer: " << asm_buffer; - tmp_insn = addNewAssembly(tmp_insn, asm_buffer); - tmp_insn->SetFallthrough(xor_instruction); - memset(asm_buffer, 0, sizeof(asm_buffer)); - - sprintf(asm_buffer, "cmp %s, 0x0\n",ereg_name); - cout << "asm_buffer: " << asm_buffer; - setAssembly(xor_instruction, asm_buffer); - memset(asm_buffer, 0, sizeof(asm_buffer)); - } - } - } - } - } - return true; -} diff --git a/tools/fix_rets/Makefile.in b/tools/fix_rets/Makefile.in deleted file mode 100644 index 521dc2c07..000000000 --- a/tools/fix_rets/Makefile.in +++ /dev/null @@ -1,42 +0,0 @@ - - -PROGS=fix_rets.exe - -CXX=@CXX@ -CXXFLAGS= -INCLUDE=-I. -I../include -I../xform -I../../beaengine/include -I../../libIRDB/include/ -I../../libMEDSannotation/include/ -I../libtransform/include/ -I../transforms -CXXFLAGS= @EXTRA_CXXFLAGS@ $(INCLUDE) -Wall -LIBS=-L../../lib -lxform -lIRDB-core -lIRDB-cfg -lBeaEngine_s_d -lpqxx -lMEDSannotation -ltransform -lpq - - -OBJS=fix_rets.o fix_rets_driver.o -programs=fix_rets.exe - -.SUFFIXES: .o .c .exe .cpp .hpp - -all: $(programs) - @echo "---------------------------------------------" - @echo "- Fix Rets directory -- Build complete -" - @echo "---------------------------------------------" - - --include $(OBJS:.o=.d) - -%.o: %.cpp - $(CXX) -c $(CXXFLAGS) $*.cpp - @# - @# build dependencies -- http://scottmcpeak.com/autodepend/autodepend.html - @# - @cpp -M $(CXXFLAGS) $*.cpp > $*.d || true - @cp -f $*.d $*.d.tmp - @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $*.d - @rm -f $*.d.tmp - -clean: - rm -f *.o core *.exe - -$(programs): ../../lib/*.a - -fix_rets.exe: $(OBJS) - $(CXX) $(CXXFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - diff --git a/tools/fix_rets/SConscript b/tools/fix_rets/SConscript deleted file mode 100644 index 038d7b8a8..000000000 --- a/tools/fix_rets/SConscript +++ /dev/null @@ -1,30 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/libtransform/include - ''' - - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="fix_rets.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util transform MEDSannotation ") -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -#install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/plugins_install/", pgm) -Default(install) - -Return('install') diff --git a/tools/fix_rets/SConstruct b/tools/fix_rets/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/fix_rets/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/fix_rets/fix_rets.cpp b/tools/fix_rets/fix_rets.cpp deleted file mode 100644 index 9fd9bba36..000000000 --- a/tools/fix_rets/fix_rets.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include "fix_rets.hpp" - -#include <assert.h> - -using namespace libTransform; - -FixRets::FixRets(FileIR_t *p_variantIR) : Transform(NULL, p_variantIR, NULL) -{ - -} - -int FixRets::execute() -{ - string register_stack_pointer; - string stack_offset_size; - string pop_insn_assembly, ret_insn_assembly; - - if (getFileIR()->GetArchitectureBitWidth() == 64) - { - register_stack_pointer = "rsp"; - stack_offset_size = "8"; - } - else - { - register_stack_pointer = "esp"; - stack_offset_size = "4"; - } - pop_insn_assembly = "lea " + register_stack_pointer + - ", [" + register_stack_pointer + - "+" + stack_offset_size + "]"; - ret_insn_assembly = "jmp [" + - register_stack_pointer + - "-" + stack_offset_size + "]"; - cout << "pop_insn_assembly: " << pop_insn_assembly << endl; - cout << "ret_insn_assembly: " << ret_insn_assembly << endl; - - for( - set<Function_t*>::const_iterator itf=getFileIR()->GetFunctions().begin(); - itf!=getFileIR()->GetFunctions().end(); - ++itf - ) - { - Function_t* func=*itf; - for( - set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it) - { - Instruction_t* insn = *it; - if(insn&& insn->GetAddress()) - { - if (insn!=NULL) - { - //DISASM disasm; - //Disassemble(insn,disasm); - const auto disasm=DecodedInstruction_t(insn); - string stack_pointer; - string stack_offset_size; - - cout << "Complete instruction: " << disasm.getDisassembly() << "-" << endl; - if (disasm.isReturn()) // strcmp(disasm.CompleteInstr,"ret ")) - continue; - - bool isPinned = insn->GetIndirectBranchTargetAddress() - && insn->GetIndirectBranchTargetAddress()->GetVirtualOffset()!=0; - if (isPinned) - { - cout << "Skipping ret fix because it's pinned." << endl; - continue; - } - Instruction_t *pop = NULL; - Instruction_t *ret = insn; - - pop = allocateNewInstruction( - insn->GetAddress()->GetFileID(), insn->GetFunction()); - setAssembly(pop, pop_insn_assembly); - setAssembly(ret, ret_insn_assembly); - - carefullyInsertBefore(ret, pop); - pop->SetFallthrough(ret); - cout << "Fixing a ret!" << endl; - } - } - } - } - return true; -} diff --git a/tools/fix_rets/fix_rets.hpp b/tools/fix_rets/fix_rets.hpp deleted file mode 100644 index 9d838bfdb..000000000 --- a/tools/fix_rets/fix_rets.hpp +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#ifndef _LIBTRANSFORM_FIX_RETS_H_ -#define _LIBTRANSFORM_FIX_RETS_H_ - -#include "../../libtransform/include/transform.hpp" -#include "../../libMEDSannotation/include/VirtualOffset.hpp" -using namespace std; -using namespace libIRDB; - -class FixRets : public libTransform::Transform -{ - public: - FixRets(FileIR_t*p_variantIR); - int execute(); -}; -#endif diff --git a/tools/fix_rets/fix_rets_driver.cpp b/tools/fix_rets/fix_rets_driver.cpp deleted file mode 100644 index a0f6c9c00..000000000 --- a/tools/fix_rets/fix_rets_driver.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "fix_rets.hpp" - -using namespace std; -using namespace libIRDB; - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id>\n"; -} - -int main(int argc, char **argv) -{ - if(argc != 2) - { - usage(argv[0]); - exit(1); - } - - string programName(argv[0]); - int variantID = atoi(argv[1]); - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - cout<<"ret_shadow_stack.exe started\n"; - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - cout<<"Transforming "<<this_file->GetURL()<<endl; - - assert(firp && pidp); - - try - { - FixRets fix_rets(firp); - - - int success=fix_rets.execute(); - - if (success) - { - cout<<"Writing changes for "<<this_file->GetURL()<<endl; - one_success = true; - firp->WriteToDB(); - delete firp; - } - else - { - cout<<"Skipping (no changes) "<<this_file->GetURL()<<endl; - } - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - // if any integer transforms for any files succeeded, we commit - if (one_success) - { - cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); - } - - return 0; -} - diff --git a/tools/hook_dynamic_call/SConscript b/tools/hook_dynamic_call/SConscript deleted file mode 100644 index 7427e1aed..000000000 --- a/tools/hook_dynamic_call/SConscript +++ /dev/null @@ -1,35 +0,0 @@ -import os - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libEXEIO/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - $SECURITY_TRANSFORMS_HOME/xform - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - ''' - -# $SECURITY_TRANSFORMS_HOME/libtransform/include -CPPFLAGS="--std=c++11" -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-core IRDB-cfg IRDB-util pqxx BeaEngine_s_d transform MEDSannotation") - -myenv['debug'] = 1 -if 'debug' in myenv and int(myenv['debug']) == 1: - print "Setting debug mode" - myenv.Append(CFLAGS=" -g -O0") - myenv.Append(CXXFLAGS=" -g -O0") - myenv.Append(LINKFLAGS=" -g -O0") - -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -myenv.Append(CPPFLAGS=CPPFLAGS) - -pgm=myenv.Program(target="hook_dynamic_calls.exe", source=Split("hook_dynamic_calls.cpp hook_dynamic_calls_driver.cpp"), LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/plugins_install/", pgm) -Default(install) -Return('install') diff --git a/tools/hook_dynamic_call/SConstruct b/tools/hook_dynamic_call/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/hook_dynamic_call/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/hook_dynamic_call/hook_dynamic_calls.cpp b/tools/hook_dynamic_call/hook_dynamic_calls.cpp deleted file mode 100644 index 92ae42f72..000000000 --- a/tools/hook_dynamic_call/hook_dynamic_calls.cpp +++ /dev/null @@ -1,542 +0,0 @@ -#include "hook_dynamic_calls.hpp" - -#include "Rewrite_Utility.hpp" -#include <assert.h> -#include <stdexcept> - -using namespace libTransform; -using namespace ELFIO; -using namespace libIRDB; - -HookDynamicCalls::HookDynamicCalls(FileIR_t *p_variantIR, bool use_call) : - Transform(NULL, p_variantIR, NULL), - m_plt_addresses(NULL), - m_use_call(use_call) -{ -} - -HookDynamicCalls::~HookDynamicCalls() -{ - if (m_plt_addresses) - free(m_plt_addresses); -} - -Elf64_Addr HookDynamicCalls::ReadAddressInSectionAtOffset( - section *section, Elf64_Off offset) -{ - Elf64_Addr address; - const char *data = NULL; - LoadElf(); - - data = section->get_data(); - cout << "data: " << std::hex << (void*)data << endl; - cout << "seeked to: 0x" - << std::hex - << offset - << endl; - - memcpy(&address, &(data[offset]), sizeof(Elf64_Addr)); - - return address; -} - -void HookDynamicCalls::LoadElf() -{ - unsigned int elfoid=0; - pqxxDB_t *interface=NULL; - - if (m_elfiop) - return; - - elfoid = getFileIR()->GetFile()->GetELFOID(); - interface = dynamic_cast<pqxxDB_t*>(BaseObj_t::GetInterface()); - - assert(interface); - - file_object.reset( - new pqxx::largeobjectaccess(interface->GetTransaction(), - elfoid, - std::ios::in)); - - file_object->to_file("tmp.exe"); - - m_elfiop.reset(new ELFIO::elfio); - m_elfiop->load("tmp.exe"); -} - -void HookDynamicCalls::LoadPltIndexTable() -{ - section *rela_plt_section = NULL; - section *got_plt_section = NULL; - section *plt_section = NULL; - - int i = 0; - Elf_Xword entry_index = 0; - Elf64_Addr value = 0, offset = 0; - Elf_Word type; - Elf_Sxword addend, calcValue; - string name; - std::unique_ptr<relocation_section_accessor> pRsa; - unsigned int plt_second_half_offset = 0x6; - - if (m_plt_addresses) return; - - rela_plt_section = m_elfiop->sections[".rela.plt"]; - got_plt_section = m_elfiop->sections[".got.plt"]; - - if (got_plt_section) - plt_section = got_plt_section; - else - plt_section = rela_plt_section; - - //assert(rela_plt_section && plt_section); - - pRsa.reset(new relocation_section_accessor(*m_elfiop, rela_plt_section)); - m_plt_addresses = (Elf64_Addr*)calloc(pRsa->get_entries_num()+1, sizeof(Elf64_Addr)); - - for (entry_index = 0; entry_index < pRsa->get_entries_num(); entry_index++) - { - if (pRsa->get_entry(entry_index, - offset, - value, - name, - type, - addend, - calcValue)) - { - Elf64_Addr plt_address = 0; - Elf64_Off got_plt_offset = 0; - - got_plt_offset = offset - plt_section->get_address(); - plt_address = ReadAddressInSectionAtOffset( - plt_section, - got_plt_offset); - m_plt_addresses[entry_index] = plt_address - plt_second_half_offset; - } - } - - for (i=0; m_plt_addresses[i] != 0; i++) - cout << "m_plt_addresses[" << i << "]: " - << "0x" << std::hex << m_plt_addresses[i] << endl; -} - -void HookDynamicCalls::MakeSymbolOffsetTable() -{ - string name; - - Elf_Xword entry_index = 0; - Elf64_Addr value = 0, offset = 0; - Elf_Word type; - Elf_Sxword addend, calcValue; - - section *rela_plt_section = NULL; - std::unique_ptr<relocation_section_accessor> pRsa; - - if (m_symbol_offset_table) return; - - LoadElf(); - LoadPltIndexTable(); - - m_symbol_offset_table.reset(new std::map<std::string, ELFIO::Elf64_Addr>); - - rela_plt_section = m_elfiop->sections[".rela.plt"]; - assert(rela_plt_section); - - cout << "section: 0x"<<std::hex<< rela_plt_section->get_address() << endl; - pRsa.reset(new relocation_section_accessor(*m_elfiop, rela_plt_section)); - for (entry_index = 0; entry_index < pRsa->get_entries_num(); entry_index++) - { - if (pRsa->get_entry(entry_index, - offset, - value, - name, - type, - addend, - calcValue)) - { - m_symbol_offset_table->insert(std::pair<std::string, Elf64_Addr>(name, m_plt_addresses[entry_index])); - } - } - - std::map<std::string, Elf64_Addr>::iterator it; - it = m_symbol_offset_table->begin(); - for (; it != m_symbol_offset_table->end(); it++) - { - string n = it->first; - Elf64_Addr address = it->second; - cout << "symbol: " << n << "-" << endl; - cout << "Address: 0x" << std::hex << address << endl; - } - -} - -virtual_offset_t HookDynamicCalls::GetSymbolOffset(string &symbol) -{ - LoadElf(); - LoadPltIndexTable(); - MakeSymbolOffsetTable(); - - Elf64_Addr address = 0; - - try { - address = m_symbol_offset_table->at(symbol); - } catch (const std::out_of_range &a) { - address = -1; - } - - cerr << "" << symbol << ": 0x" << std::hex << address << endl; - return address; -} - -Instruction_t *HookDynamicCalls::add_instrumentation(Instruction_t *site,unsigned long id, bool use_call) -{ - FileIR_t *firp = getFileIR(); - Relocation_t *zipr_reloc = new Relocation_t; - virtual_offset_t postCallbackReturn = getAvailableAddress(); - char pushRetBuf[100], movIdBuf[100], movRaxBuf[100], movRspBuf[100]; - sprintf(pushRetBuf,"push 0x%x", postCallbackReturn); - sprintf(movIdBuf,"mov rdi, 0x%x", id); - sprintf(movRaxBuf,"mov rsi, rax"); - sprintf(movRspBuf,"mov rdx, rbp"); - - Instruction_t *tmp=site, - *callback=NULL, - *post_callback=NULL, - *fallthrough=NULL; - - zipr_reloc->SetType("zipr_value"); - - fallthrough = site->GetFallthrough(); - - site=insertAssemblyBefore(firp,tmp,"push rsp"); - tmp=insertAssemblyAfter(firp,tmp,"push rbp"); - tmp=insertAssemblyAfter(firp,tmp,"push rdi"); - tmp=insertAssemblyAfter(firp,tmp,"push rsi"); - tmp=insertAssemblyAfter(firp,tmp,"push rdx"); - tmp=insertAssemblyAfter(firp,tmp,"push rcx"); - tmp=insertAssemblyAfter(firp,tmp,"push rbx"); - tmp=insertAssemblyAfter(firp,tmp,"push rax"); - tmp=insertAssemblyAfter(firp,tmp,"push r8"); - tmp=insertAssemblyAfter(firp,tmp,"push r9"); - tmp=insertAssemblyAfter(firp,tmp,"push r10"); - tmp=insertAssemblyAfter(firp,tmp,"push r11"); - tmp=insertAssemblyAfter(firp,tmp,"push r12"); - tmp=insertAssemblyAfter(firp,tmp,"push r13"); - tmp=insertAssemblyAfter(firp,tmp,"push r14"); - tmp=insertAssemblyAfter(firp,tmp,"push r15"); - tmp=insertAssemblyAfter(firp,tmp,"pushf"); - tmp=insertAssemblyAfter(firp,tmp,movIdBuf); - /* - * Add a relocation here so a later step - * can change the value that goes in the first - * parameter to the callback function. - */ - tmp->GetRelocations().insert(zipr_reloc); - - tmp=insertAssemblyAfter(firp,tmp,movRaxBuf); - tmp=insertAssemblyAfter(firp,tmp,movRspBuf); - /* - * The "bogus" return address that we push here - * will be popped by the callback handler - * invocation code in zipr. - */ - tmp=insertAssemblyAfter(firp,tmp,pushRetBuf); // push <ret addr> - - if (use_call) - { - callback=tmp=insertAssemblyAfter(firp,tmp,"call 0"); - callback->SetTarget(callback); - } - else - callback=tmp=insertAssemblyAfter(firp,tmp,"nop"); - - callback->SetCallback("zipr_hook_dynamic_callback"); - - post_callback=tmp=insertAssemblyAfter(firp,tmp,"popf"); - post_callback->GetAddress()->SetVirtualOffset(postCallbackReturn); - - tmp=insertAssemblyAfter(firp,tmp,"pop r15"); - tmp=insertAssemblyAfter(firp,tmp,"pop r14"); - tmp=insertAssemblyAfter(firp,tmp,"pop r13"); - tmp=insertAssemblyAfter(firp,tmp,"pop r12"); - tmp=insertAssemblyAfter(firp,tmp,"pop r11"); - tmp=insertAssemblyAfter(firp,tmp,"pop r10"); - tmp=insertAssemblyAfter(firp,tmp,"pop r9"); - tmp=insertAssemblyAfter(firp,tmp,"pop r8"); - tmp=insertAssemblyAfter(firp,tmp,"pop rax"); - tmp=insertAssemblyAfter(firp,tmp,"pop rbx"); - tmp=insertAssemblyAfter(firp,tmp,"pop rcx"); - tmp=insertAssemblyAfter(firp,tmp,"pop rdx"); - tmp=insertAssemblyAfter(firp,tmp,"pop rsi"); - tmp=insertAssemblyAfter(firp,tmp,"pop rdi"); - tmp=insertAssemblyAfter(firp,tmp,"pop rbp"); - tmp=insertAssemblyAfter(firp,tmp,"lea rsp, [rsp+8]"); - - tmp->SetFallthrough(site); - - return tmp; -} - -void HookDynamicCalls::SetToHook(map<string,int> to_hook) -{ - m_to_hook = to_hook; -} - -/* - * The insn is a jump in a push/jump combination. - * If this is a dynamic call through the PLT, then - * the jump's target is going to be L0 (see below). - */ -bool HookDynamicCalls::GetPltCallTarget(Instruction_t *insn, - virtual_offset_t &target_addr) { - - section *got_plt_section = NULL; - section *rela_plt_section = NULL; - section *plt_section = NULL; - Elf64_Addr target; - Instruction_t *control_instruction = NULL; - string control_instruction_bits; - DISASM d; - - LoadElf(); - got_plt_section = m_elfiop->sections[".got.plt"]; - rela_plt_section = m_elfiop->sections[".rela.plt"]; - - if (got_plt_section) - plt_section = got_plt_section; - else - plt_section = rela_plt_section; - - /* - * PLT entry: - * - * L0: jmp *CALL_FIXED (a) - * L1: push CALL_FIXUP_IDX (b) - * L2: jmp CALL_FIXER_UPPER (c) - * ... - * FORK_FIXED: &L1 (d) - */ - - /* - * Is this an instruction with a target? - * That's a must. - */ - if (!(control_instruction = insn->GetTarget())) - return false; - - control_instruction_bits = control_instruction->GetDataBits(); - control_instruction->Disassemble(d); - - /* - * Determine the type of the operand - * based on the opcode. Is it relative? - * Is it absolute? - * - * target_target: CALL_FIXED - */ - switch ((uint8_t)control_instruction_bits[0]) - { - case 0xff: - { - /* - * Make sure that the opcode extension to this instruction - * actually indicates that this is a jump instruction: - * http://ref.x86asm.net/coder64.html#xFF - */ - if (((((uint8_t)control_instruction_bits[1]) & 0x38) >> 3) != 0x4) - { - return false; - } - - virtual_offset_t indirect_address = 0; - Elf64_Addr dereferenced_indirect_address; - /* - * Jmp indirect to an absolute address. - */ - cout << "control instruction: " << d.CompleteInstr << endl; - indirect_address = *((uint32_t*)&control_instruction_bits[2]) + - control_instruction_bits.length(); - /* - * indirect_address contains the address - * of the target of control instruction, - * if one such exists. - */ - if (!indirect_address) - return false; - - cout << "indirect_address: 0x" - << std::hex << indirect_address - << endl; - /* - * Dereference the address at the target of the - * target to determine what /it/ points at. - * I.e., *CALL_FIXED - */ - dereferenced_indirect_address = ReadAddressInSectionAtOffset( - plt_section, - indirect_address - plt_section->get_address()); - cout << "dereferenced_indirect_address: 0x" - << std::hex << dereferenced_indirect_address - << endl; - - /* - * Subtract 0x6 since that is the offset - * from the start of the PLT entry to the - * so-called second half (which starts at L1) - */ - target_addr = dereferenced_indirect_address - 0x6; - return true; - } - default: - cout << "Not a handled control instruction opcode: 0x" - << std::hex << ((uint8_t)(control_instruction_bits[0])) - 0 - << endl; - return false; - } - return false; -} - -void HookDynamicCalls::CalculateIndirectTargets() -{ - assert(m_to_hook.size() != 0); - for( - set<Function_t*>::const_iterator itf=getFileIR()->GetFunctions().begin(); - itf!=getFileIR()->GetFunctions().end(); - ++itf - ) - { - Function_t* func=*itf; - for( - set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it) - { - Instruction_t* insn = *it; - virtual_offset_t vo = 0; - if ((vo = insn->GetAddress()->GetVirtualOffset())) - { - cout << "Pairing 0x" << std::hex << vo << " with an instruction." << endl; - m_indtargs[vo] = insn; - } - } - } -} - -inline bool HookDynamicCalls::IsStraightCall(Instruction_t *possible_call) -{ - string possible_call_bits = possible_call->GetDataBits(); - return (uint8_t)possible_call_bits[0] == 0x00; -} - -bool HookDynamicCalls::IsPushJumpCombo(Instruction_t *possible_start_of_combo, Instruction_t *&to_hook) -{ - /* - * If the first instruction is a push - * and the fallthrough is a jump, - * return the address that is at the - * address being pushed. - */ - Instruction_t *first = possible_start_of_combo; - Instruction_t *second = possible_start_of_combo->GetFallthrough(); - string first_bits, second_bits; - virtual_offset_t pushed_offset; - DISASM first_d, second_d; - - first_bits = first->GetDataBits(); - first->Disassemble(first_d); - cout << "first: " << first_d.CompleteInstr << endl; - - if (!second) - return false; - - second_bits = second->GetDataBits(); - second->Disassemble(second_d); - cout << "second: " << second_d.CompleteInstr << endl; - - if (((uint8_t)first_bits[0]) != 0x68) - { - cout << "First instruction is not a push." << endl; - /* - * This is not a push. - */ - return false; - } - - if (((uint8_t)second_bits[0]) != 0xe9) - { - cout << "Second instruction is not a jump." << endl; - /* - * This is not a jmp. - * (at least not the kind that we can handle!) - */ - return false; - } - - pushed_offset = *(uint32_t*)&first_bits[1]; - cout << "pushed_offset: " << std::hex << pushed_offset << endl; - to_hook = m_indtargs[pushed_offset]; - return true; -} - -int HookDynamicCalls::execute() -{ - assert(m_to_hook.size() != 0); - CalculateIndirectTargets(); - for( - set<Function_t*>::const_iterator itf=getFileIR()->GetFunctions().begin(); - itf!=getFileIR()->GetFunctions().end(); - ++itf - ) - { - Function_t* func=*itf; - for( - set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - //set<Instruction_t*>::const_iterator it=getFileIR()->GetInstructions().begin(); - //it!=getFileIR()->GetInstructions().end(); - ++it) - { - Instruction_t *insn = *it; - virtual_offset_t target = 0; - Instruction_t *insn_to_hook = NULL; - - /* - * Check to see if insn is the start of a push/jmp - * combination. Or, it could be a straight call. - */ - if (IsPushJumpCombo(insn, insn_to_hook)) - { - cout << "Found PushJump combination." << endl; - GetPltCallTarget(insn->GetFallthrough(),target); - } - else if (IsStraightCall(insn)) - { - GetPltCallTarget(insn, target); - insn_to_hook = insn; - } - - if (insn_to_hook != NULL && target != 0) - { - /* - * In either case, to_hook is the one that we are going to instrument - * and the target should match the function call we want to hook. - */ - cout << "target: " << std::hex << target << endl; - map<string,int>::iterator m_to_hook_iterator = m_to_hook.begin(); - for (; m_to_hook_iterator != m_to_hook.end(); m_to_hook_iterator++) - { - string to_hook = m_to_hook_iterator->first; - int hook_id = m_to_hook_iterator->second; - if (target == GetSymbolOffset(to_hook)) - { - cout << "hooking " << to_hook << " call at 0x" - << std::hex << insn->GetAddress()->GetVirtualOffset() - << endl; - add_instrumentation(insn_to_hook, hook_id, m_use_call); - } - } - } - } - } - return true; -} diff --git a/tools/hook_dynamic_call/hook_dynamic_calls.hpp b/tools/hook_dynamic_call/hook_dynamic_calls.hpp deleted file mode 100644 index c140f101e..000000000 --- a/tools/hook_dynamic_call/hook_dynamic_calls.hpp +++ /dev/null @@ -1,50 +0,0 @@ -#ifndef _LIBTRANSFORM_HOOK_DYNAMIC_CALLS_H_ -#define _LIBTRANSFORM_HOOK_DYNAMIC_CALLS_H_ - -#include "../../libtransform/include/transform.hpp" -#include "../../libMEDSannotation/include/VirtualOffset.hpp" -#include <libIRDB-core.hpp> -#include <libIRDB-cfg.hpp> -#include <libIRDB-syscall.hpp> -#include "elfio/elfio.hpp" -#include <functional> - -using namespace std; -using namespace libIRDB; - -class Finally -{ - public: - Finally(std::function<void (void)> finally) : m_finally(finally) {} - ~Finally() { m_finally(); }; - private: - std::function<void (void)> m_finally; -}; - -class HookDynamicCalls : public libTransform::Transform -{ - public: - HookDynamicCalls(FileIR_t*p_variantIR, bool use_call = false); - int execute(); - ~HookDynamicCalls(); - void SetToHook(std::map<std::string,int> to_hook); - private: - bool GetPltCallTarget(libIRDB::Instruction_t *, virtual_offset_t &); - libIRDB::Instruction_t *add_instrumentation(libIRDB::Instruction_t *,unsigned long, bool use_call=false); - virtual_offset_t GetSymbolOffset(string &); - ELFIO::Elf64_Addr ReadAddressInSectionAtOffset(ELFIO::section *,ELFIO::Elf64_Off); - void LoadPltIndexTable(); - void MakeSymbolOffsetTable(); - void LoadElf(); - void CalculateIndirectTargets(); - bool IsPushJumpCombo(Instruction_t *, Instruction_t *&); - bool IsStraightCall(Instruction_t *); - std::unique_ptr<ELFIO::elfio> m_elfiop; - std::unique_ptr<pqxx::largeobjectaccess> file_object; - ELFIO::Elf64_Addr *m_plt_addresses; - std::unique_ptr<std::map<std::string, ELFIO::Elf64_Addr>> m_symbol_offset_table; - std::map<std::string,int> m_to_hook; - std::map<virtual_offset_t, libIRDB::Instruction_t*> m_indtargs; - bool m_use_call; -}; -#endif diff --git a/tools/hook_dynamic_call/hook_dynamic_calls_driver.cpp b/tools/hook_dynamic_call/hook_dynamic_calls_driver.cpp deleted file mode 100644 index b5fb372bd..000000000 --- a/tools/hook_dynamic_call/hook_dynamic_calls_driver.cpp +++ /dev/null @@ -1,139 +0,0 @@ -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "hook_dynamic_calls.hpp" - -using namespace std; -using namespace libIRDB; - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id> <use call> [<call> <id>]\n"; -} - -int main(int argc, char **argv) -{ - pqxxDB_t pqxx_interface; - VariantID_t *pidp=NULL; - int variantID; - string programName; - bool use_call = false; - - string call_name = ""; - int call_id = 0; - map<string, int> to_hook; - - if(argc < 3) - { - usage(argv[0]); - exit(1); - } - - programName = string(argv[0]); - variantID = atoi(argv[1]); - if (!strcmp(argv[2], "true")) - use_call = true; - - argv+=3; - - while (*argv) { - if (call_name.length() == 0) - { - call_name = string(*argv); - cout << "call_name: " << call_name << endl; - } - else - { - try - { - auto finally = [&call_id, &call_name] - { - call_id = 0; - call_name = ""; - }; - Finally f(finally); - - call_id = std::stoi(string(*argv)); - cout << "call_id: " << call_id << endl; - to_hook.insert(pair<string,int>(call_name, call_id)); - } - catch (const std::invalid_argument invalid) - { - cout << "Invalid call id: " << *argv << endl; - } - catch (const std::out_of_range &out_of_range) - { - cout << "Invalid call id: " << *argv << endl; - } - } - argv++; - } - - map<string,int>::iterator to_hook_iterator = to_hook.begin(); - for (; to_hook_iterator != to_hook.end(); to_hook_iterator++) - { - string name = to_hook_iterator->first; - int id = to_hook_iterator->second; - cout << name << " -> " << id << endl; - } - - /* setup the interface to the sql server */ - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - cout<<"hook_dynamic_calls.exe started\n"; - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - cout<<"Transforming "<<this_file->GetURL()<<endl; - - assert(firp && pidp); - - try - { - HookDynamicCalls hookdynamic(firp, use_call); - hookdynamic.SetToHook(to_hook); - - int success=hookdynamic.execute(); - - if (success) - { - cout<<"Writing changes for "<<this_file->GetURL()<<endl; - one_success = true; - firp->WriteToDB(); - delete firp; - } - else - { - cout<<"Skipping (no changes) "<<this_file->GetURL()<<endl; - } - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - // if any integer transforms for any files succeeded, we commit - if (one_success) - { - cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); - } - - return 0; -} diff --git a/tools/hook_start/SConscript b/tools/hook_start/SConscript deleted file mode 100644 index 2018f0475..000000000 --- a/tools/hook_start/SConscript +++ /dev/null @@ -1,29 +0,0 @@ -import os - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libEXEIO/include - $SECURITY_TRANSFORMS_HOME/libtransform/include - $SECURITY_TRANSFORMS_HOME/xform - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/third_party/elfio-code - ''' - -# $SECURITY_TRANSFORMS_HOME/libtransform/include -CPPFLAGS="--std=c++11" -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util transform MEDSannotation ") - -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -myenv.Append(CPPFLAGS=CPPFLAGS) - -pgm=myenv.Program(target="hook_start.exe", source=Split("hook_start.cpp hook_start_driver.cpp"), LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/plugins_install/", pgm) -Default(install) -Return('install') diff --git a/tools/hook_start/SConstruct b/tools/hook_start/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/hook_start/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/hook_start/hook_start.cpp b/tools/hook_start/hook_start.cpp deleted file mode 100644 index 4a2db36b2..000000000 --- a/tools/hook_start/hook_start.cpp +++ /dev/null @@ -1,152 +0,0 @@ -#include "hook_start.hpp" - -#include "Rewrite_Utility.hpp" -#include <assert.h> -#include <stdexcept> - -using namespace libTransform; -using namespace ELFIO; -using namespace libIRDB; -using namespace IRDBUtility; - -HookStart::HookStart(FileIR_t *p_variantIR) : - Transform(NULL, p_variantIR, NULL), - m_callback_name("zipr_hook_start") -{ -} - -HookStart::~HookStart() -{ -} - -void HookStart::LoadElf() -{ - unsigned int elfoid=0; - pqxxDB_t *interface=NULL; - - if (m_elfiop) - return; - - elfoid = getFileIR()->GetFile()->GetELFOID(); - interface = dynamic_cast<pqxxDB_t*>(BaseObj_t::GetInterface()); - - assert(interface); - - m_file_object.reset( - new pqxx::largeobjectaccess(interface->GetTransaction(), - elfoid, - std::ios::in)); - - m_file_object->to_file("tmp.exe"); - - m_elfiop.reset(new ELFIO::elfio); - m_elfiop->load("tmp.exe"); -} - -Instruction_t *HookStart::add_instrumentation(Instruction_t *site) -{ - Relocation_t *zipr_reloc = new Relocation_t; - //FileIR_t *firp = getFileIR(); - virtual_offset_t postCallbackReturn = getAvailableAddress(); - char pushRetBuf[100], - movIdBuf[100], - movRaxBuf[100], - movRspBuf[100]; - sprintf(pushRetBuf,"push qword 0x%lx", (long unsigned int)postCallbackReturn); - sprintf(movIdBuf,"mov rdi, 0x0"); - sprintf(movRaxBuf,"mov rsi, rax"); - sprintf(movRspBuf,"mov rdx, rsp"); - - cout << "postCallbackReturn: " << std::hex << postCallbackReturn << endl; - - zipr_reloc->SetType("zipr_value"); - - Instruction_t *tmp=site, - *callback=NULL, - *post_callback=NULL; - - site=insertAssemblyBefore(tmp,"push rsp"); - tmp=insertAssemblyAfter(tmp,"push rbp"); - tmp=insertAssemblyAfter(tmp,"push rdi"); - tmp=insertAssemblyAfter(tmp,"push rsi"); - tmp=insertAssemblyAfter(tmp,"push rdx"); - tmp=insertAssemblyAfter(tmp,"push rcx"); - tmp=insertAssemblyAfter(tmp,"push rbx"); - tmp=insertAssemblyAfter(tmp,"push rax"); - tmp=insertAssemblyAfter(tmp,"push r8"); - tmp=insertAssemblyAfter(tmp,"push r9"); - tmp=insertAssemblyAfter(tmp,"push r10"); - tmp=insertAssemblyAfter(tmp,"push r11"); - tmp=insertAssemblyAfter(tmp,"push r12"); - tmp=insertAssemblyAfter(tmp,"push r13"); - tmp=insertAssemblyAfter(tmp,"push r14"); - tmp=insertAssemblyAfter(tmp,"push r15"); - tmp=insertAssemblyAfter(tmp,"pushf"); - tmp=insertAssemblyAfter(tmp,movIdBuf); - /* - * Let's put a relocation on here! - */ - tmp->GetRelocations().insert(zipr_reloc); - tmp=insertAssemblyAfter(tmp,movRaxBuf); - tmp=insertAssemblyAfter(tmp,movRspBuf); - /* - * The "bogus" return address that we push here - * will be popped by the callback handler - * invocation code in zipr. - */ - tmp=insertAssemblyAfter(tmp,pushRetBuf); // push <ret addr> - - callback=tmp=insertAssemblyAfter(tmp,"call 0"); - callback->SetTarget(callback); - callback->SetCallback(m_callback_name); - - post_callback=tmp=insertAssemblyAfter(tmp,"popf"); - post_callback->GetAddress()->SetVirtualOffset(postCallbackReturn); - - tmp=insertAssemblyAfter(tmp,"pop r15"); - tmp=insertAssemblyAfter(tmp,"pop r14"); - tmp=insertAssemblyAfter(tmp,"pop r13"); - tmp=insertAssemblyAfter(tmp,"pop r12"); - tmp=insertAssemblyAfter(tmp,"pop r11"); - tmp=insertAssemblyAfter(tmp,"pop r10"); - tmp=insertAssemblyAfter(tmp,"pop r9"); - tmp=insertAssemblyAfter(tmp,"pop r8"); - tmp=insertAssemblyAfter(tmp,"pop rax"); - tmp=insertAssemblyAfter(tmp,"pop rbx"); - tmp=insertAssemblyAfter(tmp,"pop rcx"); - tmp=insertAssemblyAfter(tmp,"pop rdx"); - tmp=insertAssemblyAfter(tmp,"pop rsi"); - tmp=insertAssemblyAfter(tmp,"pop rdi"); - tmp=insertAssemblyAfter(tmp,"pop rbp"); - tmp=insertAssemblyAfter(tmp,"lea rsp, [rsp+8]"); - - tmp->SetFallthrough(site); - - return tmp; -} - -int HookStart::execute() -{ - LoadElf(); - for( - set<Function_t*>::const_iterator itf=getFileIR()->GetFunctions().begin(); - itf!=getFileIR()->GetFunctions().end(); - ++itf - ) - { - Function_t* func=*itf; - for( - set<Instruction_t*>::const_iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it) - { - Instruction_t *insn = *it; - if (insn->GetAddress() && - insn->GetAddress()->GetVirtualOffset()==m_elfiop->get_entry()) - { - add_instrumentation(insn); - } - } - } - return true; -} diff --git a/tools/hook_start/hook_start.hpp b/tools/hook_start/hook_start.hpp deleted file mode 100644 index a4dcaceb7..000000000 --- a/tools/hook_start/hook_start.hpp +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef _LIBTRANSFORM_HOOK_START_H_ -#define _LIBTRANSFORM_HOOK_START_H_ - -#include "../../libtransform/include/transform.hpp" -#include "../../libMEDSannotation/include/VirtualOffset.hpp" -#include <libIRDB-core.hpp> -#include <libIRDB-cfg.hpp> -#include <libIRDB-syscall.hpp> -#include "elfio/elfio.hpp" - -using namespace std; -using namespace libIRDB; - -class HookStart : public libTransform::Transform -{ - public: - HookStart(FileIR_t*p_variantIR); - ~HookStart(); - - void CallbackName(const std::string &callback_name) - { - m_callback_name = callback_name; - } - std::string CallbackName() - { - return m_callback_name; - } - int execute(); - private: - void LoadElf(); - Instruction_t *add_instrumentation(Instruction_t *site); - std::string m_callback_name; - std::unique_ptr<ELFIO::elfio> m_elfiop; - std::unique_ptr<pqxx::largeobjectaccess> m_file_object; - ELFIO::Elf64_Addr *m_plt_addresses; -}; -#endif diff --git a/tools/hook_start/hook_start_driver.cpp b/tools/hook_start/hook_start_driver.cpp deleted file mode 100644 index 363990940..000000000 --- a/tools/hook_start/hook_start_driver.cpp +++ /dev/null @@ -1,95 +0,0 @@ -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "hook_start.hpp" - -using namespace std; -using namespace libIRDB; - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id> [callback name]\n"; -} - -int main(int argc, char **argv) -{ - pqxxDB_t pqxx_interface; - VariantID_t *pidp=NULL; - int variantID; - string programName, callback_name; - - if(argc < 2) - { - usage(argv[0]); - exit(1); - } - - programName = string(argv[0]); - variantID = atoi(argv[1]); - - if (argv[2] != NULL) - callback_name = string(argv[2]); - - /* setup the interface to the sql server */ - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - cout<<"hook_start.exe started\n"; - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - cout<<"Transforming "<<this_file->GetURL()<<endl; - - assert(firp && pidp); - - try - { - int success = 0; - HookStart hookstart(firp); - - if (callback_name != "") - hookstart.CallbackName(callback_name); - - success=hookstart.execute(); - - if (success) - { - cout<<"Writing changes for "<<this_file->GetURL()<<endl; - one_success = true; - firp->WriteToDB(); - delete firp; - } - else - { - cout<<"Skipping (no changes) "<<this_file->GetURL()<<endl; - } - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - // if any integer transforms for any files succeeded, we commit - if (one_success) - { - cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); - } - - return 0; -} diff --git a/tools/ibtcheck/Makefile b/tools/ibtcheck/Makefile deleted file mode 100644 index f4a749340..000000000 --- a/tools/ibtcheck/Makefile +++ /dev/null @@ -1,6 +0,0 @@ -clean: - -rm -fr cal.* tmp.* peasoup.cal.tmp - -rm tmp.* - -test: - ./test_cal.sh diff --git a/tools/ibtcheck/ibtcheck.py b/tools/ibtcheck/ibtcheck.py deleted file mode 100644 index 61914a4f0..000000000 --- a/tools/ibtcheck/ibtcheck.py +++ /dev/null @@ -1,135 +0,0 @@ -import sys -import argparse -from sets import Set - -# only works for single-threaded programs - -def convert_to_hex(x): - converted = [] - for i in x: - converted.append(hex(i)) - return converted - -def display_violation(ib_src, ib_seen, allowed): - print 'IBT violation detected at: ', hex(ib_src), '(src) --> ', hex(ib_seen), '(tgt) | allowed targets: ', convert_to_hex(allowed) - -def display_violations(violations, ibtargets): - for src in violations: - for v in violations[src]: - display_violation(src, v, ibtargets[src]['targets']) - - -if __name__ == "__main__": - - parser = argparse.ArgumentParser(description='Validate STARS IB COMPLETE annotations') - parser.add_argument('stars_xrefs', type=file, - help='STARS Xrefs annotation file') - parser.add_argument('trace_file', type=file, - help='QEMU-style instructions') - - args = parser.parse_args(); - -# stash away the annotations -# cols 0 1 2 3 4 5 6 7 -# 465d0f 1 INSTR XREF IBT FROMIB 465c72 RETURNTARGET -# 465de1 1 INSTR XREF IBT FROMIB 465c72 RETURNTARGET -# 465c72 1 INSTR XREF FROMIB COMPLETE 2 - ibtargets = {} - for line in args.stars_xrefs: - cols = line.split() - if (len(cols) < 5): - continue - if cols[5] == 'FROMIB': - src = long(cols[6], 16) - dst = long(cols[0], 16) - - if not src in ibtargets: - ibtargets[src] = {} - - if not 'targets' in ibtargets[src]: - ibtargets[src]['targets'] = [] - - if not 'complete' in ibtargets[src]: - ibtargets[src]['complete'] = False - - ibtargets[src]['targets'].append(dst) - elif cols[5] == 'COMPLETE': - src = long(cols[0], 16) - - if not src in ibtargets: - ibtargets[src] = {} - - ibtargets[src]['complete'] = True - - -# 0x000000000045d7b9: retq -# 0x00000040013575e0: push %r13 - - violations = {} - - line_no = -1 - to_check = -1L - for line in args.trace_file: - line_no+=1 - - if not line.startswith('0x'): - continue - - try: - cols = line.split(':') - if len(cols) > 0: - # handle 2 formats: - # 0x004000f0: push %r11 - # 0x004000f0 <address> <some_function_here+xxx>: push %r11 - instr = cols[0].split(' ')[0] - instr = long(instr, 16) - else: - instr = long(cols[0], 16) - except: - print 'warning: parse error on line: ', line_no, ' ', line - - if to_check >= 0: - if not instr in ibtargets[to_check]['targets']: - print 'Detected ibtarget violation at ', hex(to_check), ' --> ', hex(instr), '(', len(ibtargets[to_check]['targets']), ')', convert_to_hex(ibtargets[to_check]['targets']) - if not to_check in violations: - violations[to_check] = Set() - violations[to_check].add(instr) - else: - if not 'covered' in ibtargets[to_check]: - ibtargets[to_check]['covered'] = Set() - - ibtargets[to_check]['covered'].add(instr) - - to_check = -1L - - # did STARS mark complete? - # if yes check the next instruction - if instr in ibtargets and ibtargets[instr]['complete'] == True: - to_check = instr - - # get some statistics - total_ibtargets = 0 - ibtargets_covered = 0 - icfs_coverage_count = 0 - for src_instr in ibtargets: - total_ibtargets += len(ibtargets[src_instr]['targets']) - if 'covered' in ibtargets[src_instr]: - icfs_coverage_count += 1 - ibtargets_covered += len(ibtargets[src_instr]['covered']) - - if len(violations) > 0: - print '===========================================' - display_violations(violations, ibtargets) - print '===========================================' - else: - print 'No ICFS violations detected' - - print '#icfs_covered: ', icfs_coverage_count, '/', len(ibtargets), ' ratio: ', icfs_coverage_count * 1.0 / len(ibtargets) - - print '#ibtargets_covered: ', ibtargets_covered, '/', total_ibtargets, ' ratio: ', 1.0*ibtargets_covered / total_ibtargets - - if len(violations) > 0: - exit(1) - else: - exit(0) - diff --git a/tools/ibtcheck/test_cal.sh b/tools/ibtcheck/test_cal.sh deleted file mode 100755 index 54be56403..000000000 --- a/tools/ibtcheck/test_cal.sh +++ /dev/null @@ -1,85 +0,0 @@ -#!/bin/bash -# analyze cal program - -PIN_HOME=~/pin-2.14-71313-gcc.4.4.7-linux - -PROG=/usr/bin/cal -PROG_BASE=$(basename ${PROG}) -TMPDIR=peasoup.${PROG_BASE}.tmp -TRACE_FILE=${PROG_BASE}.trace -XREFS=${PROG_BASE}.xrefs -PROG_SCFI=${PROG_BASE}.zipr.scfi.color - -if [ -e "$TMPDIR" ]; then - rm -fr $TMPDIR -fi - -FIX_CALLS_FIX_ALL_CALLS=1 $PEASOUP_HOME/tools/ps_analyze.sh $PROG $PROG_SCFI --backend zipr --tempdir ${TMPDIR} --step selective_cfi=on --step-option selective_cfi:--color # --stop_after pdb_register - -cp ${TMPDIR}/a.ncexe.STARSxrefs $XREFS - -# invoke QEMU to get trace rm $TRACE_FILE - -# arguments for cal -ARGS=("" "-h" "-bogus" "2000" "-w 2000" "-3 5 2001" "1 2000" "1 1999" "-j 2000" "-J 2000" "-S 1000" "-M 1015" "-J -o 12 9999" "-e -p -y 2000" "-M -y -B9 -A5 2000" "-S -y -B10 -A10 2000" "-1" "-A-20 -B-5 1000" "-w -m 3 1111" "-N 2000" "-N -w 2000" "-N -3 8 2001" "-N 1 2000" "-N 1 1999" "-N -j 2000" "-N -J 2000" "-N -S 1000" "-N -M 1015" "-N -J -o 12 9999" "-N -e -p -y 2000" "-N -M -y -B9 -A5 2000" "-N -S -y -B10 -A10 2000" "-N -1" "-N -A-20 -B-5 1000" "-N -w -m 3 1111" "-N -y 1999 -m 3" "-N -y -b" "-N -s GB 2000") - -for ix in ${!ARGS[*]} -do - echo "args: ${ARGS[$ix]}" > ${TRACE_FILE}.${ix} - -# QEMU -# qemu-x86_64 -singlestep -d in_asm $PROG ${ARGS[$ix]} >/dev/null 2>> tmp.$$ -# grep "0x" tmp.$$ >> ${TRACE_FILE}.${ix} -# rm tmp.$$ - -# PIN version - $PIN_HOME/pin -injection child -t $PIN_HOME/source/tools/ManualExamples/obj-intel64/itrace.so -- ${PROG} ${ARGS[$ix]} - cat itrace.out >> ${TRACE_FILE}.${ix} - - ${PROG} ${ARGS[$ix]} >tmp.orig.out 2>tmp.orig.err - ./${PROG_SCFI} ${ARGS[$ix]} >tmp.cfi.out 2>tmp.cfi.err - diff tmp.orig.out tmp.cfi.out >/dev/null 2>&1 - if [ ! $? -eq 0 ]; then - echo "SCFI FAILURE" - exit 1 - fi - -done - -# check IB Targets traced against spec in STARS xref file -if [ -e $TRACE_FILE ]; then - rm $TRACE_FILE -fi -touch $TRACE_FILE - -TRACE_FAILED="" -for t in `ls ${TRACE_FILE}.*` -do - cat $t >> $TRACE_FILE - args=$(head -1 $t) - echo - echo IBT Check for inputs: trace_file: $t invoked with: $args - python ibtcheck.py $XREFS $t - if [ ! $? -eq 0 ]; then - echo FAILED: $args trace_file: $t - TRACE_FAILED="$TRACE_FAILED [$t $args]" - fi - -done - -echo -echo "Aggregate Statistics (please be patient)" -python ibtcheck.py $XREFS $TRACE_FILE - -if [ ! -z "$TRACE_FAILED" ]; then - echo - echo "===============================================" - echo "IBT check on trace failed: $TRACE_FAILED" - echo "===============================================" - echo - exit 1 -fi - - -exit 0 - diff --git a/tools/inferfn/Makefile b/tools/inferfn/Makefile deleted file mode 100644 index f2e658da1..000000000 --- a/tools/inferfn/Makefile +++ /dev/null @@ -1,39 +0,0 @@ -CC=g++ -CFLAGS= -g -Wall -DCGC -INCLUDE=-I. -I../include -I../xform -I../../beaengine/include -I../../libIRDB/include/ -I../../libMEDSannotation/include/ -I../libtransform/include/ -I../transforms -I../../include -LIBS=-L../../lib -lxform -lIRDB-core -lIRDB-cfg -lIRDB-util -lIRDB-syscall -lBeaEngine_s_d -lpqxx -lMEDSannotation -ltransform ../transforms/Rewrite_Utility.o - -program=inferfn.exe - -all: $(program) - @echo "-----------------------------------------------" - @echo "- CGC libc dynamic inference engine -- Build complete -" - @echo "-----------------------------------------------" - -OBJS=inferfn.o inferfn_driver.o - - -.SUFFIXES: .o .c .exe .cpp .hpp - --include $(OBJS:.o=.d) - -%.o: %.cpp - $(CC) $(INCLUDE) $(CFLAGS) -c $< - @# - @# build dependencies -- http://scottmcpeak.com/autodepend/autodepend.html - @# - $(CC) -MM $(INCLUDE) $(CFLAGS) $*.cpp > $*.d - @cp -f $*.d $*.d.tmp - @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $*.d - @rm -f $*.d.tmp - - -clean: - rm -f *.o core *.exe *.d - -$(program): ../../lib/*.a - - -$(program): $(OBJS) - $(CC) $(CFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - diff --git a/tools/inferfn/SConscript b/tools/inferfn/SConscript deleted file mode 100644 index 0de687a24..000000000 --- a/tools/inferfn/SConscript +++ /dev/null @@ -1,30 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="inferfn.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util transform MEDSannotation ") -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install) - - - -Return('install') diff --git a/tools/inferfn/SConstruct b/tools/inferfn/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/inferfn/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/inferfn/inferfn.cpp b/tools/inferfn/inferfn.cpp deleted file mode 100644 index 69fd94ad9..000000000 --- a/tools/inferfn/inferfn.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include "Rewrite_Utility.hpp" -#include "inferfn.hpp" - -using namespace std; - -#define SPRI_AVAIL_ADDRESS 0xff08ff00 - -InferFn::InferFn(FileIR_t *p_firp) -{ - m_firp = p_firp; - - m_cg.AddFile(m_firp); -// m_cg.Dump(cout); - - int elfoid=m_firp->GetFile()->GetELFOID(); - pqxx::largeobject lo(elfoid); - libIRDB::pqxxDB_t *interface=dynamic_cast<libIRDB::pqxxDB_t*>(libIRDB::BaseObj_t::GetInterface()); - assert(interface); - lo.to_file(interface->GetTransaction(),"tmp.exe"); - - m_elfiop=new ELFIO::elfio; - m_elfiop->load("tmp.exe"); - ELFIO::dump::header(std::cout,*m_elfiop); - ELFIO::dump::section_headers(std::cout,*m_elfiop); - ELFIO::dump::segment_headers(std::cout,*m_elfiop); -} - -void InferFn::pinAllFunctionEntryPoints() -{ - Function_t* fn=NULL; - for(FunctionSet_t::iterator it=m_firp->GetFunctions().begin(); - it!=m_firp->GetFunctions().end(); - ++it - ) - { - fn=*it; - if (!fn) continue; - Instruction_t *insn = fn->GetEntryPoint(); - - if(insn && insn->GetAddress() && insn->GetAddress()->GetVirtualOffset() > 0) - { - insn->SetIndirectBranchTargetAddress(insn->GetAddress()); -printf("inferfn: pinning function entry point: %p\n", insn->GetAddress()->GetVirtualOffset()); - } - } -} - -void InferFn::addInferenceCallback(Instruction_t *site) -{ - virtual_offset_t postCallbackReturn = SPRI_AVAIL_ADDRESS; - char tmpbuf[200]; - sprintf(tmpbuf,"push 0x%x", postCallbackReturn); - - Instruction_t *tmp=site, *callback=NULL, *post_callback=NULL; -// Instruction_t *fallthrough = site->GetFallthrough(); - tmp=insertAssemblyAfter(m_firp,tmp,"lea esp, [esp-4096]"); - tmp=insertAssemblyAfter(m_firp,tmp,"pushf"); - tmp=insertAssemblyAfter(m_firp,tmp,"pusha"); - tmp=insertAssemblyAfter(m_firp,tmp,tmpbuf); // push <ret addr> - callback=tmp=insertAssemblyAfter(m_firp,tmp,"nop"); - post_callback=tmp=insertAssemblyAfter(m_firp,tmp,"popa"); - tmp=insertAssemblyAfter(m_firp,tmp,"popf"); - tmp=insertAssemblyAfter(m_firp,tmp,"lea esp, [esp+4096]"); - post_callback->GetAddress()->SetVirtualOffset(postCallbackReturn); - callback->SetCallback("inference_handler"); - -// tmp->SetFallthrough(fallthrough); -} - -Instruction_t* InferFn::findEntryPoint() -{ - Instruction_t* insn=NULL; - for(InstructionSet_t::iterator it=m_firp->GetInstructions().begin(); - it!=m_firp->GetInstructions().end(); - ++it - ) - { - insn=*it; - if(insn->GetIndirectBranchTargetAddress() && - insn->GetIndirectBranchTargetAddress()->GetVirtualOffset()==(virtual_offset_t)m_elfiop->get_entry()) - { - cout << "mallard: entry point is at 0x" << hex << m_elfiop->get_entry() << dec << endl; - return insn; - } - - } - - return NULL; -} - -bool InferFn::execute() -{ - Instruction_t *entryPoint = findEntryPoint(); - assert(entryPoint); - - insertAssemblyBefore(m_firp, entryPoint, "nop"); - addInferenceCallback(entryPoint); - - // pin functions - pinAllFunctionEntryPoints(); - - return true; -} diff --git a/tools/inferfn/inferfn.hpp b/tools/inferfn/inferfn.hpp deleted file mode 100644 index 80e81b484..000000000 --- a/tools/inferfn/inferfn.hpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#ifndef inferfn_h -#define inferfn_h - -#include <libIRDB-core.hpp> -#include <libIRDB-cfg.hpp> - -#include "elfio/elfio.hpp" -#include "elfio/elfio_dump.hpp" - -using namespace libIRDB; - -class InferFn { - public: - InferFn(FileIR_t *p_firp); - bool execute(); - - private: - Instruction_t* findEntryPoint(); - void addInferenceCallback(Instruction_t *); - void pinAllFunctionEntryPoints(); - - private: - FileIR_t *m_firp; - ELFIO::elfio* m_elfiop; - Callgraph_t m_cg; -}; - -#endif diff --git a/tools/inferfn/inferfn_driver.cpp b/tools/inferfn/inferfn_driver.cpp deleted file mode 100644 index 04765febe..000000000 --- a/tools/inferfn/inferfn_driver.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2014 - Zephyr Software - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "inferfn.hpp" - -using namespace std; -using namespace libIRDB; - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id>\n"; -} - -int main(int argc, char **argv) -{ - if(argc != 2) - { - usage(argv[0]); - exit(1); - } - - string programName(argv[0]); - int variantID = atoi(argv[1]); - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - try - { - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - cout<<"Mallard: Transforming "<<this_file->GetURL()<<endl; - - assert(firp && pidp); - - InferFn inferfn(firp); - - bool success=inferfn.execute(); - - if (success) - { - one_success = true; - firp->WriteToDB(); - } - delete firp; - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - if (one_success) - { - cout<<"Mallard: Commiting changes...\n"; - pqxx_interface.Commit(); - } - - return 0; -} - diff --git a/tools/memcover/General_Utility.cpp b/tools/memcover/General_Utility.cpp deleted file mode 100644 index d7b094293..000000000 --- a/tools/memcover/General_Utility.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2013, 2014 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include "General_Utility.hpp" -#include <limits.h> -#include <cstdlib> -#include <cerrno> - -using namespace std; - -STR2NUM_ERROR str2int (int &i, char const *s, int base) -{ - char *end; - long l; - errno = 0; - l = strtol(s, &end, base); - if ((errno == ERANGE && l == LONG_MAX) || l > INT_MAX) { - return s2n_OVERFLOW; - } - if ((errno == ERANGE && l == LONG_MIN) || l < INT_MIN) { - return s2n_UNDERFLOW; - } - if (*s == '\0' || *end != '\0') { - return s2n_INCONVERTIBLE; - } - i = l; - return s2n_SUCCESS; -} - -//TODO: what if the string represents a negative number? Currently -//the number will be translated into an unsigned int. I could make this -//and incovertible situation. -STR2NUM_ERROR str2uint (unsigned int &i, char const *s, int base) -{ - char *end; - unsigned long l; - errno = 0; - l = strtol(s, &end, base); - if ((errno == ERANGE && l == ULONG_MAX) || l > UINT_MAX) { - return s2n_OVERFLOW; - } - if (*s == '\0' || *end != '\0') { - return s2n_INCONVERTIBLE; - } - i = l; - return s2n_SUCCESS; -} - -void trim(string& str) -{ - string::size_type pos = str.find_last_not_of(" \t\f\v\n\r"); - if(pos != string::npos) - { - str.erase(pos + 1); - pos = str.find_first_not_of(" \t\f\v\n\r"); - if(pos != string::npos) str.erase(0, pos); - } - else - str.erase(str.begin(), str.end()); -} - - -void tokenize(vector<string>& tokens, const string& str,const string& delimiters) -{ - tokens.clear(); - // Skip delimiters at beginning. - string::size_type lastPos = str.find_first_not_of(delimiters, 0); - // Find first "non-delimiter". - string::size_type pos = str.find_first_of(delimiters, lastPos); - - while (string::npos != pos || string::npos != lastPos) - { - // Found a token, add it to the vector. - tokens.push_back(str.substr(lastPos, pos - lastPos)); - - // Skip delimiters. Note the "not_of" - lastPos = str.find_first_not_of(delimiters, pos); - // Find next "non-delimiter" - pos = str.find_first_of(delimiters, lastPos); - } -} - diff --git a/tools/memcover/General_Utility.hpp b/tools/memcover/General_Utility.hpp deleted file mode 100644 index 63a06a38c..000000000 --- a/tools/memcover/General_Utility.hpp +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2013, 2014 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#ifndef _GENERAL_UTILITY -#define _GENERAL_UTILITY - -#include <string> -#include <vector> -#include <map> - -typedef enum STR2NUM_ERROR_t { s2n_SUCCESS, s2n_OVERFLOW, s2n_UNDERFLOW, s2n_INCONVERTIBLE } STR2NUM_ERROR; -STR2NUM_ERROR str2int (int &i, char const *s, int base = 0); -STR2NUM_ERROR str2uint (unsigned int &i, char const *s, int base = 0); -void trim(std::string &str); -void tokenize(std::vector<std::string> &tokens, const std::string &str,const std::string& delimiters=" \t\n\r"); - -template <class k, class v> -void getKeys(const std::map<k,v> &m, std::vector<k> &keys) -{ - - for(typename std::map<k,v>::const_iterator it = m.begin(); it !=m.end(); ++it) - { - keys.push_back(it->first); - } -} - -#endif diff --git a/tools/memcover/Makefile b/tools/memcover/Makefile deleted file mode 100644 index 2786ca172..000000000 --- a/tools/memcover/Makefile +++ /dev/null @@ -1,42 +0,0 @@ -# -# Makefile.in - DESCRIPTION. -# -# Copyright (c) 2011 - University of Virginia -# -# This file may be used and modified for non-commercial purposes as long as -# all copyright, permission, and nonwarranty notices are preserved. -# Redistribution is prohibited without prior written consent from the University of Virginia -# -# Please contact the authors for restrictions applying to commercial use. -# -# THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED -# WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF -# MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. -# - - -PROGS=memcover.exe - -CFLAGS= -g -# -O3 -Wall -INCLUDE=-I. -I../../include -I../../xform -I../../beaengine/include -I../../libIRDB/include/ -I../../libMEDSannotation/include/ -I../../libtransform/include/ -LIBS=-L../../lib -L../../xform -lxform -lELFIO -L../../libIRDB/lib/ -lIRDB-core -lIRDB-cfg -L../../beaengine/lib/Linux.gnu.Debug -lBeaEngine_s_d -lpqxx -L../../libMEDSannotation/lib -lMEDSannotation -L../../libtransform/lib -ltransform -OBJS=transformutils.o - -.SUFFIXES: .o .c .exe .cpp - -all: memcover $(OBJS) $(PROGS) - echo memcover build complete - -.o: $< - $(CXX) -g -c $@ - -.cpp.exe: $< - $(CXX) -g $< $(INCLUDE) $(LIBS) $(OBJS) -o $@ - -clean: - rm -f *.o core $(PROGS) - - -memcover: - $(CXX) $(CFLAGS) memcover.cpp General_Utility.cpp Rewrite_Utility.cpp $(INCLUDE) $(LIBS) -o memcover.exe diff --git a/tools/memcover/SConscript b/tools/memcover/SConscript deleted file mode 100644 index df8aa29db..000000000 --- a/tools/memcover/SConscript +++ /dev/null @@ -1,32 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="memcover.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util transform MEDSannotation ") -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -myenv.Alias("install", "$SECURITY_TRANSFORMS_HOME/bin/") -Default(install) - - - -Return('install') diff --git a/tools/memcover/SConstruct b/tools/memcover/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/memcover/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/memcover/memcover.cpp b/tools/memcover/memcover.cpp deleted file mode 100644 index d1fc70fd4..000000000 --- a/tools/memcover/memcover.cpp +++ /dev/null @@ -1,634 +0,0 @@ -/* - * Copyright (c) 2013, 2014 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include <iostream> -#include <cstdlib> -#include <cstdio> -#include <string> -#include <fstream> -#include <libIRDB-core.hpp> -#include "General_Utility.hpp" -#include "Rewrite_Utility.hpp" -#include <sstream> -#include <bea_deprecated.hpp> - - -#define ARG_CNT 3 -#define INPUT_ERR_NUM 1 -#define DB_ERR_NUM 2 -#define UNDEFINED 0x0 - -#define LOWORD(a) ((0x0000FFFF)&(a)) - -#define EAX 0x1 -#define ECX 0x2 -#define EDX 0x3 -#define EBX 0x4 -#define ESP 0x5 -#define EBP 0x6 -#define ESI 0x7 -#define EDI 0x8 - -#define SCALE_ONE 0x1 -#define SCALE_TWO 0x2 -#define SCALE_FOUR 0x3 -#define SCALE_EIGHT 0x4 - -#define SIZE_BYTE 0x1 -#define SIZE_WORD 0x2 -#define SIZE_DWORD 0x3 -#define SIZE_QWORD 0x4 -#define SIZE_TWORD 0x5 -#define SIZE_128 0x6 - -#define LEA_INSTRUCTION 0x44 -#define PUSH_INSTRUCTION 0x45 -#define POP_INSTRUCTION 0x46 -#define LEAVE_INSTRUCTION 0x47 -#define RET_INSTRUCTION 0x48 - -using namespace std; -using namespace libIRDB; - -static string prog_name; -static ofstream annot_ofstream; - -static string URLToFile(string url) -{ - unsigned int loc=0; - - loc=url.find('/'); - while(loc!=string::npos) - { - url=url.substr(loc+1,url.length()-loc-1); - - loc=url.find('/'); - } - // maybe need to check filename for odd characters - - return url; -} - -void usage() -{ - cerr<<"Usage: "<<prog_name<<" <DB_Variant_ID> <output annot file>"<<endl; -} - -/* - As defined by the beaengine disassembler. - - REG0 = 0x1, EAX 1 - REG1 = 0x2, ECX 2 - REG2 = 0x4, EDX 3 - REG3 = 0x8, EBX 4 - REG4 = 0x10, ESP 5 - REG5 = 0x20, EBP 6 - REG6 = 0x40, ESI 7 - REG7 = 0x80, EDI 8 - REG8 = 0x100, - REG9 = 0x200, - REG10 = 0x400, - REG11 = 0x800, - REG12 = 0x1000, - REG13 = 0x2000, - REG14 = 0x4000, - REG15 = 0x8000 -*/ -unsigned int encode_reg(unsigned int reg) -{ - switch(reg) - { - case REG0: - return EAX; - break; - case REG1: - return ECX; - break; - case REG2: - return EDX; - break; - case REG3: - return EBX; - break; - case REG4: - return ESP; - break; - case REG5: - return EBP; - break; - case REG6: - return ESI; - break; - case REG7: - return EDI; - break; - case 0: - return UNDEFINED; - break; - default: - assert(false); - break; - } - -} - -unsigned int encode_scale(unsigned int scale) -{ - switch(scale) - { - case 1: - return SCALE_ONE; - break; - case 2: - return SCALE_TWO; - break; - case 4: - return SCALE_FOUR; - break; - case 8: - return SCALE_EIGHT; - break; - case 0: - return UNDEFINED; - break; - default: - assert(false); - break; - } - -} - -//Size is encoded in bits in beaengine. -unsigned int encode_size(unsigned int size) -{ - switch(size) - { - case 0: - return UNDEFINED; - break; - case 8: - return SIZE_BYTE; - break; - case 16: - return SIZE_WORD; - break; - case 32: - return SIZE_DWORD; - break; - case 64: - return SIZE_QWORD; - break; - case 80: - return SIZE_TWORD; - break; - case 128: - return SIZE_128; - break; - default: - assert(false); - break; - } -} - - -unsigned int encode_operand(const ARGTYPE &arg) -{ - int encoding; - - if((arg.ArgType&0xFFFF0000) != MEMORY_TYPE) - { - return 0; - } - - //TODO: make this optimization optional - //for the stack, absolute accesses are not useful. - if(arg.Memory.BaseRegister == 0 && arg.Memory.IndexRegister == 0 && arg.Memory.Displacement != 0) - return 0; - - encoding = encode_size(arg.ArgSize); - - //TODO: warn if size is 0 -/* - if(encoding == 0) - { - cerr<<lib_name<<"+"<<addr<<":"<<disasm.CompleteInstr<<" no access size provided"<<endl; - } -*/ - encoding = encoding <<4; - encoding |= arg.AccessMode; - encoding <<= 4; - encoding |= encode_reg(arg.Memory.BaseRegister); - encoding <<= 4; - encoding |= encode_reg(arg.Memory.IndexRegister); - encoding <<= 4; - encoding |= encode_scale(arg.Memory.Scale); - encoding <<= 4; - if(arg.Memory.Displacement != 0) - encoding |= 0x1; - - return encoding; -} - -inline bool is_esp_dest(ARGTYPE &arg) -{ - return ((arg.ArgType&0xFFFF0000) == (REGISTER_TYPE+GENERAL_REG) && (LOWORD(arg.ArgType)==REG4)&& arg.AccessMode==WRITE); -} - -static int counter = -16; -virtual_offset_t get_next_addr() -{ - counter += 16; - //If we ever get to FF000000 then - //this could cause serious problems. - assert(counter != 0x0F000000); - - return 0xf0000000 + counter; -} - -void process_instructions(FileIR_t *fir_p) -{ - //using maps since I believe inserting instructions while iterating - //will cause issues. - map<Instruction_t*,DISASM> post_esp_checks; - map<Instruction_t*,DISASM> ret_esp_checks; - map<Instruction_t*,DISASM> mem_refs; - map<Instruction_t*,DISASM> func_entries; - map<Instruction_t*,DISASM> post_rep_checks; - - for( - set<Instruction_t*>::const_iterator it=fir_p->GetInstructions().begin(); - it!=fir_p->GetInstructions().end(); - ++it - ) - { - Instruction_t* instr = *it; - assert(instr); - - DISASM disasm; - Disassemble(instr,disasm); //calls memset for me, no worries - string instr_mn = disasm.Instruction.Mnemonic; - trim(instr_mn); - PREFIXINFO prefix = disasm.Prefix; - - //is esp a destination, or is esp implicitly modified? - //NOTE: leaves are now special cased and shadowed in the - //memref callback. No need to check esp after leave instructions - //anymore. - if(instr_mn.compare("leave") != 0 && - (is_esp_dest(disasm.Argument1) || - is_esp_dest(disasm.Argument2) || - disasm.Instruction.ImplicitModifiedRegs == REGISTER_TYPE+GENERAL_REG+REG4 || - instr_mn.compare("call") == 0)) - { - assert(instr_mn.compare("ret") != 0); - post_esp_checks[instr] = disasm; - } - - //Leaves were never considered mem references by beaengine. - //They are mem references here, special cased inside the mem_ref call - //back so they are appropriately shadowed. - //TODO: I could encode leave prior to the callback to make the callback - //more efficient. - if(instr_mn.compare("leave")==0 || - (disasm.Argument1.ArgType&0xFFFF0000) == MEMORY_TYPE || - (disasm.Argument2.ArgType&0xFFFF0000) == MEMORY_TYPE) - mem_refs[instr] = disasm; - - if(prefix.RepPrefix == InUsePrefix ||prefix.RepnePrefix == InUsePrefix) - { - post_rep_checks[instr] = disasm; - } - } - - for( - set<Function_t*>::const_iterator it=fir_p->GetFunctions().begin(); - it!=fir_p->GetFunctions().end(); - ++it - ) - { - Function_t *func = *it; - - /* - ControlFlowGraph_t cfg(func); - BasicBlock_t *block = cfg.GetEntry(); - */ - - //TODO: I am not sure if this is as reliable as using the control flow graph. - Instruction_t *first_instr = func->GetEntryPoint(); - - DISASM disasm; - Disassemble(first_instr,disasm); //calls memset for me, no worries - - func_entries[first_instr] = disasm; - } - - //NOTE: post checks must be placed first. - for( - map<Instruction_t*,DISASM>::const_iterator it=post_rep_checks.begin(); - it!=post_rep_checks.end(); - ++it - ) - { - Instruction_t *instr = it->first; - Instruction_t *tmp; - - unsigned int addr = instr->GetAddress()->GetVirtualOffset(); - stringstream ss; - ss.str(""); - unsigned int ra = get_next_addr(); - - tmp = insertAssemblyAfter(fir_p,instr,"pushad"); - tmp = insertAssemblyAfter(fir_p,tmp,"pushfd"); - ss<<hex<<addr; - tmp = insertAssemblyAfter(fir_p,tmp,"push 0x"+ss.str()); - ss.str(""); - ss<<hex<<ra; - tmp = insertAssemblyAfter(fir_p,tmp,"push 0x"+ss.str()); - tmp = insertAssemblyAfter(fir_p,tmp,"pop eax"); - tmp->SetCallback("post_rep_check"); - tmp->GetAddress()->SetVirtualOffset(ra); - tmp->SetIndirectBranchTargetAddress(tmp->GetAddress()); - tmp = insertAssemblyAfter(fir_p,tmp,"popfd"); - tmp = insertAssemblyAfter(fir_p,tmp,"popad"); - } - - - for( - map<Instruction_t*,DISASM>::const_iterator it=post_esp_checks.begin(); - it!=post_esp_checks.end(); - ++it - ) - { - Instruction_t *instr = it->first; - Instruction_t *tmp; - - unsigned int addr = instr->GetAddress()->GetVirtualOffset(); - stringstream ss; - ss.str(""); - unsigned int ra = get_next_addr(); - - tmp = insertAssemblyAfter(fir_p,instr,"pushad"); - tmp = insertAssemblyAfter(fir_p,tmp,"pushfd"); - ss<<hex<<addr; - tmp = insertAssemblyAfter(fir_p,tmp,"push 0x"+ss.str()); - ss.str(""); - ss<<hex<<ra; - tmp = insertAssemblyAfter(fir_p,tmp,"push 0x"+ss.str()); - - tmp = insertAssemblyAfter(fir_p,tmp,"pop eax"); - tmp->SetCallback("post_esp_check"); - tmp->GetAddress()->SetVirtualOffset(ra); - tmp->SetIndirectBranchTargetAddress(tmp->GetAddress()); - tmp = insertAssemblyAfter(fir_p,tmp,"popfd"); - tmp = insertAssemblyAfter(fir_p,tmp,"popad"); - } - - - //TODO: should I give ret a different access value? To do so requires - //setting an operand for ret, which really doesn't work. Presently, - //the callback handles special casing ret and using a special - //access type. - for( - map<Instruction_t*,DISASM>::const_iterator it=mem_refs.begin(); - it!=mem_refs.end(); - ++it - ) - { - Instruction_t *instr = it->first; - Instruction_t *tmp; - DISASM disasm = it->second; - - PREFIXINFO prefix = disasm.Prefix; - unsigned int addr = 0; - unsigned int func_addr = 0; - unsigned int op1_code=0,op2_code=0; - unsigned int displ = 0; - string instr_mn = disasm.Instruction.Mnemonic; - trim(instr_mn); - string lib_name = URLToFile(fir_p->GetFile()->GetURL()); - - assert(instr->GetAddress()); - addr = instr->GetAddress()->GetVirtualOffset(); - - //I am not sure if any of these situations exist, but I want to avoid yucky segfaults - if(instr->GetFunction() && instr->GetFunction()->GetEntryPoint() && - instr->GetFunction()->GetEntryPoint()->GetAddress()) - { - //TODO: this might not work for dyn libs - func_addr = instr->GetFunction()->GetEntryPoint()->GetAddress()->GetVirtualOffset(); - } - - op1_code = encode_operand(disasm.Argument1); - op2_code = encode_operand(disasm.Argument2); - - assert(!(((op1_code&0x00000001)==0x1)&&((op2_code&0x00000001)==0x1))); - - if(disasm.Argument1.Memory.Displacement != 0) - displ = (unsigned int)disasm.Argument1.Memory.Displacement; - else if(disasm.Argument2.Memory.Displacement != 0) - displ = (unsigned int)disasm.Argument2.Memory.Displacement; - else - displ = 0; - - if(instr_mn.compare("lea") == 0) - disasm.Instruction.Category = (disasm.Instruction.Category&0xFFFF0000)|LEA_INSTRUCTION; - else if(instr_mn.find("push") != string::npos) - disasm.Instruction.Category = (disasm.Instruction.Category&0xFFFF0000)|PUSH_INSTRUCTION; - else if(instr_mn.find("pop") != string::npos) - disasm.Instruction.Category = (disasm.Instruction.Category&0xFFFF0000)|POP_INSTRUCTION; - else if(instr_mn.compare("leave")==0) - disasm.Instruction.Category = (disasm.Instruction.Category&0xFFFF0000) | LEAVE_INSTRUCTION; - else if(instr_mn.compare("ret")==0) - { - disasm.Instruction.Category = (disasm.Instruction.Category&0xFFFF0000) | RET_INSTRUCTION; - } - - if(prefix.RepPrefix == InUsePrefix) - disasm.Instruction.Category = (disasm.Instruction.Category&0xFFFF3FFF)|(0x1<<14); - else if(prefix.RepnePrefix == InUsePrefix) - disasm.Instruction.Category = (disasm.Instruction.Category&0xFFFF3FFF)|(0x2<<14); - - //TODO: if rep, should I have a post rep check? - - - stringstream ss; - ss.str(""); - //TODO: addr can equal 0 make sure its handled. - -//Note the use of insertAssemblyBefore, before the use of insertAssemblyAfter - insertAssemblyBefore(fir_p,instr,"pushad"); - - tmp = insertAssemblyAfter(fir_p,instr,"pushfd"); - - ss<<hex<<displ; - tmp = insertAssemblyAfter(fir_p,tmp,"push 0x"+ss.str()); - ss.str(""); - - ss<<hex<<op2_code; - tmp = insertAssemblyAfter(fir_p,tmp,"push 0x"+ss.str()); - ss.str(""); - - ss<<hex<<op1_code; - tmp = insertAssemblyAfter(fir_p,tmp,"push 0x"+ss.str()); - ss.str(""); - - ss<<hex<<disasm.Instruction.Category; - tmp = insertAssemblyAfter(fir_p,tmp,"push 0x"+ss.str()); - ss.str(""); - - ss<<hex<<func_addr; - tmp = insertAssemblyAfter(fir_p,tmp,"push 0x"+ss.str()); - ss.str(""); - - ss<<hex<<addr; - tmp = insertAssemblyAfter(fir_p,tmp,"push 0x"+ss.str()); - ss.str(""); - - unsigned int ra = get_next_addr(); - ss<<hex<<ra; - tmp = insertAssemblyAfter(fir_p,tmp,"push 0x"+ss.str()); - ss.str(""); - tmp = insertAssemblyAfter(fir_p,tmp,"add esp, 0x18"); - tmp->SetCallback("mem_ref"); - tmp->GetAddress()->SetVirtualOffset(ra); - tmp->SetIndirectBranchTargetAddress(tmp->GetAddress()); - tmp = insertAssemblyAfter(fir_p,tmp,"popfd"); - tmp = insertAssemblyAfter(fir_p,tmp,"popad"); - } - - - //TODO: do I need to loop again for this? - - //NOTE: this must be done after all other instrumentation (since it inserts before). - for( - map<Instruction_t*,DISASM>::const_iterator it=func_entries.begin(); - it!=func_entries.end(); - ++it - ) - { - Instruction_t *instr = it->first; - Instruction_t *tmp; - - stringstream ss; - ss.str(""); - unsigned int ra = get_next_addr(); - unsigned int func_addr = instr->GetAddress()->GetVirtualOffset();//instr->GetFunction()->GetEntryPoint()->GetAddress()->GetVirtualOffset(); - - insertAssemblyBefore(fir_p,instr,"pushad"); - - tmp = insertAssemblyAfter(fir_p,instr,"pushfd"); - ss<<hex<<func_addr; - tmp = insertAssemblyAfter(fir_p,tmp,"push 0x"+ss.str()); - ss.str(""); - ss<<hex<<ra; - tmp = insertAssemblyAfter(fir_p,tmp,"push 0x"+ss.str()); - ss.str(""); - tmp = insertAssemblyAfter(fir_p,tmp,"pop eax"); - tmp->SetCallback("func_entry"); - tmp->GetAddress()->SetVirtualOffset(ra); - tmp->SetIndirectBranchTargetAddress(tmp->GetAddress()); - tmp = insertAssemblyAfter(fir_p,tmp,"popfd"); - tmp = insertAssemblyAfter(fir_p,tmp,"popad"); - } -} - - -int main(int argc, char **argv) -{ - prog_name = argv[0]; - - if(argc != ARG_CNT) - { - usage(); - exit(INPUT_ERR_NUM); - } - - int vid; - if(str2int(vid,argv[1]) != s2n_SUCCESS) - { - cerr<<"Variant ID ("<<argv[1]<<") could not be parsed as an integer."<<endl; - exit(INPUT_ERR_NUM); - } - - - annot_ofstream.open(argv[2]); - - if(!annot_ofstream.is_open()) - { - cerr<<"Could not open file "<<argv[2]<<" for writing"<<endl; - exit(INPUT_ERR_NUM); - } - - - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - VariantID_t *vid_p; - - try - { - cout<<"Getting VariantID..."; - vid_p = new VariantID_t(vid); - assert(vid_p && vid_p->IsRegistered()); - cout<<"Done!"<<endl; - - cout<<vid_p->GetFiles().size()<<" Files to Analyze"<<endl; - int file_cnt =1; - //Get each file - for(set<File_t*>::const_iterator it=vid_p->GetFiles().begin(); - it != vid_p->GetFiles().end(); - ++it,++file_cnt - ) - { - stringstream ss; - ss.str(""); - File_t* this_file_p=*it; - assert(this_file_p); - cout<<"File "<<file_cnt<<endl; - - cout<<"Getting FileIR..."; - FileIR_t *fir_p = new FileIR_t(*vid_p,this_file_p); - assert(fir_p); - cout<<"Done!"<<endl; - - cout<<"Processing FileIR..."; - process_instructions(fir_p); - cout<<"Done!"<<endl; - ss<<file_cnt; - //annot_ofstream.open(string("annot_test"+ss.str()).c_str()); - fir_p->GenerateSPRI(annot_ofstream,false); - //annot_ofstream.close(); - - delete fir_p; - } - annot_ofstream.close(); - - pqxx_interface.Commit(); - } - catch(DatabaseError_t dberr) - { - cerr<<"Unexpected database error: "<<dberr<<endl; - exit(DB_ERR_NUM); - } - - - - return 0; -} diff --git a/tools/prince/Makefile b/tools/prince/Makefile deleted file mode 100644 index b1263e795..000000000 --- a/tools/prince/Makefile +++ /dev/null @@ -1,36 +0,0 @@ -CC=g++ -CFLAGS= -g -Wall -DCGC -#INCLUDE=-I. -I../include -I../xform -I../../beaengine/include -I../../libIRDB/include/ -I../../libMEDSannotation/include/ -I../libtransform/include/ -I../transforms -I../../include -INCLUDE=-I. -I$(SECURITY_TRANSFORMS_HOME)/include -I$(SECURITY_TRANSFORMS_HOME)/libIRDB/include -I$(SECURITY_TRANSFORMS_HOME)/beaengine/include -I$(ZIPR_CALLBACKS)/inferfn -LIBS=-L$(SECURITY_TRANSFORMS_HOME)/lib -lxform -lIRDB-core -lIRDB-cfg -lIRDB-util -lIRDB-syscall -lBeaEngine_s_d -lpqxx -lMEDSannotation -ltransform $(SECURITY_TRANSFORMS_HOME)/tools/transforms/Rewrite_Utility.o - -program=prince_driver.exe - -all: $(program) - @echo "-----------------------------------------------" - @echo "- CGC libc dynamic inference engine -- Build complete -" - @echo "-----------------------------------------------" - -OBJS=prince_driver.o prince.o - -.SUFFIXES: .o .c .exe .cpp .hpp - --include $(OBJS:.o=.d) - -%.o: %.cpp - $(CC) $(INCLUDE) $(CFLAGS) -c $< - @# - @# build dependencies -- http://scottmcpeak.com/autodepend/autodepend.html - @# - $(CC) -MM $(INCLUDE) $(CFLAGS) $*.cpp > $*.d - @cp -f $*.d $*.d.tmp - @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $*.d - @rm -f $*.d.tmp - - -clean: - rm -f *.o core *.exe *.d - -$(program): $(OBJS) - $(CC) $(CFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - diff --git a/tools/prince/SConscript b/tools/prince/SConscript deleted file mode 100644 index 97ac3ea4d..000000000 --- a/tools/prince/SConscript +++ /dev/null @@ -1,31 +0,0 @@ -import os - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) -myenv.Replace(ZIPR_CALLBACKS=os.environ['ZIPR_CALLBACKS']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - $ZIPR_CALLBACKS/inferfn - ''' - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="prince_driver.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util MEDSannotation ") -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install) - - - -Return('install') diff --git a/tools/prince/SConstruct b/tools/prince/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/prince/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/prince/prince.cpp b/tools/prince/prince.cpp deleted file mode 100644 index 3039a75a3..000000000 --- a/tools/prince/prince.cpp +++ /dev/null @@ -1,1375 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include <stdlib.h> -#include <stdint.h> -#include <stdio.h> -#include <string.h> -// #include <libgen.h> -#include <unistd.h> -#include <signal.h> -#include <string> -#include <assert.h> -#include <sys/wait.h> - -#include "inferutil.h" - -#include <libIRDB-core.hpp> - -using namespace std; -using namespace libIRDB; - -#define BOGUS_VALUE 2000000000 -#define BOGUS_VALUE_2 -2 - -uintptr_t malloc_address = 0L; - -int success = 0; - -#define EXIT_CODE_TEST_SUCCESS 0 -#define EXIT_CODE_TEST_FAILURE 1 -#define EXIT_CODE_TEST_INVALID 2 - - -static void send_request(int fd, struct request *req) -{ - int bytes_written; - - bytes_written = write(fd, req, sizeof(struct request)); -} - -static void send_quit_command(int fd) -{ - struct request req; - clear_request(&req); - req.command = CMD_QUIT; - send_request(fd, &req); -} - -static void get_response(int fd, struct response *res) -{ - int bytes_read; - - bytes_read = read(fd, res, sizeof(struct response)); -// cout << "get_response(): bytes_read = " << bytes_read << endl; -} - -static void set_argument_int(struct argument *arg, int val) -{ - if (arg) { - arg->type = ARG_INT; - arg->val.num = val; - } -} - -static void set_argument_ptr(struct argument *arg, const uintptr_t address) -{ - if (arg) { - arg->type = ARG_PTR; - arg->val.addr = address; - } -} - -static void set_argument_str(struct argument *arg, char *str) -{ - if (arg) { - arg->type = ARG_BYTES; - arg->val.bytes.num_bytes = strlen(str)+1; - strcpy(arg->val.bytes.bytes, str); - } -} - -int call_proto_i_pbb(uintptr_t fn, uintptr_t rptr, int bogus1, int bogus2, int *ok) -{ - struct request req; - struct response res; - - clear_request(&req); - clear_response(&res); - - req.command = CMD_CALL; - req.num_args = 4; - set_argument_ptr(&req.arg1, fn); - set_argument_ptr(&req.arg2, rptr); - set_argument_int(&req.arg3, bogus1); - set_argument_int(&req.arg4, bogus2); - req.outarg_type = ARG_INT; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; - return res.ok ? res.outarg.val.addr : (uintptr_t) NULL; -} - -int call_proto_i_p(uintptr_t fn, uintptr_t rptr, int *ok) -{ - return call_proto_i_pbb(fn, rptr, BOGUS_VALUE, BOGUS_VALUE_2, ok); -} - -int call_proto_i_ppb(uintptr_t fn, uintptr_t rptr1, uintptr_t rptr2, int bogus, int *ok) -{ - struct request req; - struct response res; - - clear_request(&req); - clear_response(&res); - - req.command = CMD_CALL; - req.num_args = 4; - set_argument_ptr(&req.arg1, fn); - set_argument_ptr(&req.arg2, rptr1); - set_argument_ptr(&req.arg3, rptr2); - set_argument_int(&req.arg4, bogus); - req.outarg_type = ARG_PTR; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; - return res.ok ? res.outarg.val.addr : (uintptr_t) NULL; -} - -int call_proto_i_pp(uintptr_t fn, uintptr_t rptr1, uintptr_t rptr2, int *ok) -{ - return call_proto_i_ppb(fn, rptr1, rptr2, BOGUS_VALUE, ok); -} - -uintptr_t call_proto_p_p(uintptr_t fn, uintptr_t p, int *ok) -{ - struct request req; - struct response res; - - clear_request(&req); - clear_response(&res); - - req.command = CMD_CALL; - req.num_args = 4; - set_argument_ptr(&req.arg1, fn); - set_argument_ptr(&req.arg2, p); - set_argument_int(&req.arg3, BOGUS_VALUE); - set_argument_int(&req.arg4, BOGUS_VALUE); - req.outarg_type = ARG_PTR; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; - return res.ok ? res.outarg.val.addr : (uintptr_t) NULL; -} - -uintptr_t call_proto_p_s(uintptr_t fn, char *str, int *ok) -{ - struct request req; - struct response res; - - clear_request(&req); - clear_response(&res); - - req.command = CMD_CALL; - req.num_args = 4; - set_argument_ptr(&req.arg1, fn); - set_argument_str(&req.arg2, str); - set_argument_int(&req.arg3, BOGUS_VALUE); - set_argument_int(&req.arg4, BOGUS_VALUE); - req.outarg_type = ARG_PTR; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; - return res.ok ? res.outarg.val.addr : (uintptr_t) NULL; -} - -uintptr_t call_proto_p_si(uintptr_t fn, char *str, int i, int *ok) -{ - struct request req; - struct response res; - - clear_request(&req); - clear_response(&res); - - req.command = CMD_CALL; - req.num_args = 4; - set_argument_ptr(&req.arg1, fn); - set_argument_str(&req.arg2, str); - set_argument_int(&req.arg3, i); - set_argument_int(&req.arg4, BOGUS_VALUE); - req.outarg_type = ARG_PTR; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; - return res.ok ? res.outarg.val.addr : (uintptr_t) NULL; -} - -uintptr_t call_proto_p_pp(uintptr_t fn, uintptr_t p1, uintptr_t p2, int *ok) -{ - struct request req; - struct response res; - - clear_request(&req); - clear_response(&res); - - req.command = CMD_CALL; - req.num_args = 4; - set_argument_ptr(&req.arg1, fn); - set_argument_ptr(&req.arg2, p1); - set_argument_ptr(&req.arg3, p2); - set_argument_int(&req.arg4, BOGUS_VALUE); - req.outarg_type = ARG_PTR; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; - return res.ok ? res.outarg.val.addr : (uintptr_t) NULL; -} - -uintptr_t call_proto_p_i(uintptr_t fn, int i, int *ok) -{ - struct request req; - struct response res; - - clear_request(&req); - clear_response(&res); - - req.command = CMD_CALL; - req.num_args = 4; - set_argument_ptr(&req.arg1, fn); - set_argument_int(&req.arg2, i); - set_argument_int(&req.arg3, BOGUS_VALUE); - set_argument_int(&req.arg4, BOGUS_VALUE_2); - req.outarg_type = ARG_PTR; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; - return res.ok ? res.outarg.val.addr : (uintptr_t) NULL; -} - -uintptr_t call_proto_p_ii(uintptr_t fn, int i1, int i2, int *ok) -{ - struct request req; - struct response res; - - clear_request(&req); - clear_response(&res); - - req.command = CMD_CALL; - req.num_args = 4; - set_argument_ptr(&req.arg1, fn); - set_argument_int(&req.arg2, i1); - set_argument_int(&req.arg3, i2); - set_argument_int(&req.arg4, BOGUS_VALUE); - req.outarg_type = ARG_PTR; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; - return res.ok ? res.outarg.val.addr : (uintptr_t) NULL; -} - -int call_proto_i_ppi(uintptr_t fn, uintptr_t rptr1, uintptr_t rptr2, int i, int *ok) -{ - struct request req; - struct response res; - - clear_request(&req); - clear_response(&res); - - req.command = CMD_CALL; - req.num_args = 4; - set_argument_ptr(&req.arg1, fn); - set_argument_ptr(&req.arg2, rptr1); - set_argument_ptr(&req.arg3, rptr2); - set_argument_int(&req.arg4, i); - req.outarg_type = ARG_PTR; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; - return res.ok ? res.outarg.val.addr : (uintptr_t) NULL; -} - -uintptr_t call_proto_p_pib(uintptr_t fn, uintptr_t ptr, int i, int bogus, int *ok) -{ - struct request req; - struct response res; - clear_request(&req); - clear_response(&res); - - req.command = CMD_CALL; - req.num_args = 4; - set_argument_ptr(&req.arg1, fn); - set_argument_ptr(&req.arg2, ptr); - set_argument_int(&req.arg3, i); - set_argument_int(&req.arg4, bogus); // bogus value on purpose - req.outarg_type = ARG_PTR; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; - return res.ok ? res.outarg.val.addr : (uintptr_t) NULL; -} - -uintptr_t call_proto_p_pi(uintptr_t fn, uintptr_t ptr, int i, int *ok) -{ - return call_proto_p_pib(fn, ptr, i, BOGUS_VALUE, ok); -} - -uintptr_t call_proto_p_pii(uintptr_t fn, uintptr_t ptr, int i1, int i2, int *ok) -{ - struct request req; - struct response res; - clear_request(&req); - clear_response(&res); - - req.command = CMD_CALL; - req.num_args = 4; - set_argument_ptr(&req.arg1, fn); - set_argument_ptr(&req.arg2, ptr); - set_argument_int(&req.arg3, i1); - set_argument_int(&req.arg4, i2); - req.outarg_type = ARG_PTR; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; - return res.ok ? res.outarg.val.addr : (uintptr_t) NULL; -} - -int find_free(const int infd, const int outfd, const uintptr_t malloc_address, const uintptr_t fn) -{ - struct request req; - struct response res; - uintptr_t newaddress = 0L; - - clear_request(&req); - clear_response(&res); - - req.command = CMD_CALL; - req.num_args = 2; - set_argument_ptr(&req.arg1, malloc_address); - set_argument_int(&req.arg2, 20000); - req.outarg_type = ARG_PTR; - - send_request(outfd, &req); - get_response(infd, &res); - - if (res.ok) - { - newaddress = res.outarg.val.addr; - printf("malloc(20000) returned %p\n", newaddress); - } - else - { - fprintf(stderr, "something went wrong with malloc call\n"); - return 0; - } - - printf("find_free(): now call maybe free: %p with arg: %p\n", fn, newaddress); - clear_request(&req); - clear_response(&res); - - req.command = CMD_CALL; - req.num_args = 2; - set_argument_ptr(&req.arg1, fn); - set_argument_ptr(&req.arg2, newaddress); - req.outarg_type = ARG_NONE; - - printf("find_free(): send_request\n"); - send_request(outfd, &req); - printf("find_free(): get_response\n"); - get_response(infd, &res); - - printf("find_free(): result = %d\n", res.ok); - return res.ok; -} - -uintptr_t call_memset(uintptr_t maybe_memset, uintptr_t ptr, int c, int size, int *ok) -{ - return call_proto_p_pii(maybe_memset, ptr, c, size, ok); -} - -uintptr_t call_memchr(uintptr_t maybe_memchr, uintptr_t ptr, int c, int size, int *ok) -{ - return call_proto_p_pii(maybe_memchr, ptr, c, size, ok); -} - -uintptr_t call_strchr(uintptr_t maybe_strchr, uintptr_t ptr, int c, int *ok) -{ - uintptr_t p1 = call_proto_p_pib(maybe_strchr, ptr, c, 0, ok); - assert(*ok); - uintptr_t p2 = call_proto_p_pib(maybe_strchr, ptr, c, -1, ok); - assert(*ok); - uintptr_t p3 = call_proto_p_pib(maybe_strchr, ptr, c, BOGUS_VALUE, ok); - assert(*ok); - - assert(p1 == p2); - assert(p2 == p3); - - return p1; -} - -uintptr_t call_strrchr(uintptr_t maybe_strrchr, uintptr_t ptr, int c, int *ok) -{ - uintptr_t p1 = call_proto_p_pib(maybe_strrchr, ptr, c, 0, ok); - assert(*ok); - uintptr_t p2 = call_proto_p_pib(maybe_strrchr, ptr, c, -1, ok); - assert(*ok); - uintptr_t p3 = call_proto_p_pib(maybe_strrchr, ptr, c, BOGUS_VALUE, ok); - assert(*ok); - - assert(p1 == p2); - assert(p2 == p3); - - return p1; -} - -uintptr_t call_malloc(uintptr_t maybe_malloc, int size, int *ok) -{ - return call_proto_p_i(maybe_malloc, size, ok); -} - -uintptr_t call_calloc(uintptr_t maybe_calloc, int count, int size, int *ok) -{ - return call_proto_p_ii(maybe_calloc, count, size, ok); -} - -// char* strdup(const char *s1); -uintptr_t call_strdup(uintptr_t maybe_strdup, char *str, int *ok) -{ - return call_proto_p_s(maybe_strdup, str, ok); -} - -// char* strndup(const char *s1, size); -uintptr_t call_strndup(uintptr_t maybe_strdup, char *str, int size, int *ok) -{ - return call_proto_p_si(maybe_strdup, str, size, ok); -} - -int call_strlen(uintptr_t maybe_strlen, uintptr_t ptr, int *ok) -{ - int i1 = call_proto_i_pbb(maybe_strlen, ptr, 2, BOGUS_VALUE, ok); - assert(*ok); - int i2 = call_proto_i_pbb(maybe_strlen, ptr, BOGUS_VALUE, -5, ok); - assert(*ok); - int i3 = call_proto_i_pbb(maybe_strlen, ptr, -2, BOGUS_VALUE, ok); - assert(*ok); - - assert (i1 == i2); - assert (i2 == i3); - - return i1; -} - -uintptr_t call_strtok(uintptr_t maybe_strtok, uintptr_t str, uintptr_t sep, int *ok) -{ - return call_proto_p_pp(maybe_strtok, str, sep, ok); -} - -int call_strcmp(uintptr_t maybe_strcmp, uintptr_t s1, uintptr_t s2, int *ok) -{ - int r1 = call_proto_i_ppb(maybe_strcmp, s1, s2, 2, ok); - assert(*ok); - int r2 = call_proto_i_ppb(maybe_strcmp, s1, s2, 200000, ok); - assert(*ok); - int r3 = call_proto_i_ppb(maybe_strcmp, s1, s2, -2, ok); - assert(*ok); - assert (r1==r2); - assert (r2==r3); - return r1; -} - -int call_strncmp(uintptr_t maybe_strncmp, uintptr_t s1, uintptr_t s2, int n, int *ok) -{ - return call_proto_i_ppi(maybe_strncmp, s1, s2, n, ok); -} - -int call_memcpy(uintptr_t maybe_memcpy, uintptr_t dst, uintptr_t src, int size, int *ok) -{ - return call_proto_i_ppi(maybe_memcpy, dst, src, size, ok); -} - -int call_strlcpy(uintptr_t maybe_strlcpy, uintptr_t dst, uintptr_t src, int size, int *ok) -{ - return call_proto_i_ppi(maybe_strlcpy, dst, src, size, ok); -} - -int call_strlcat(uintptr_t maybe_strlcat, uintptr_t dst, uintptr_t src, int size, int *ok) -{ - return call_proto_i_ppi(maybe_strlcat, dst, src, size, ok); -} - -int call_strncat(uintptr_t maybe_strncat, uintptr_t dst, uintptr_t src, int size, int *ok) -{ - return call_proto_i_ppi(maybe_strncat, dst, src, size, ok); -} - -int call_strspn(uintptr_t maybe_strspn, uintptr_t s1, uintptr_t s2, int *ok) -{ - int i1 = call_proto_i_ppb(maybe_strspn, s1, s2, 0, ok); - assert (*ok); - int i2 = call_proto_i_ppb(maybe_strspn, s1, s2, -2, ok); - assert (*ok); - int i3 = call_proto_i_ppb(maybe_strspn, s1, s2, BOGUS_VALUE, ok); - assert (*ok); - - assert(i1 == i2); - assert(i2 == i3); - - return i1; -} - -int call_strcspn(uintptr_t maybe_strcspn, uintptr_t s1, uintptr_t s2, int *ok) -{ - int i1 = call_proto_i_ppb(maybe_strcspn, s1, s2, 0, ok); - assert (*ok); - int i2 = call_proto_i_ppb(maybe_strcspn, s1, s2, -2, ok); - assert (*ok); - int i3 = call_proto_i_ppb(maybe_strcspn, s1, s2, BOGUS_VALUE, ok); - assert (*ok); - - assert(i1 == i2); - assert(i2 == i3); - - return i1; -} - -// void* realloc(void *ptr, size_t size); -uintptr_t call_realloc(uintptr_t maybe_realloc, uintptr_t ptr, int size, int *ok) -{ - return call_proto_p_pi(maybe_realloc, ptr, size, ok); -} - -void call_read(char *buf, uintptr_t addr, int numbytes, int *ok) -{ - struct request req; - struct response res; - - clear_request(&req); - clear_response(&res); - - req.command = CMD_READ; - req.num_args = 4; - set_argument_ptr(&req.arg1, addr); - set_argument_int(&req.arg2, numbytes); - set_argument_int(&req.arg3, -50000000); // bogus on purpose - set_argument_int(&req.arg3, 20000000); // bogus on purpose - req.outarg_type = ARG_BYTES; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; - if (*ok) - memcpy(buf, res.outarg.val.bytes.bytes, numbytes); -} - -uintptr_t call_allocate(int size, int init_value, int *ok) -{ - struct request req; - struct response res; - - clear_request(&req); - clear_response(&res); - - req.command = CMD_ALLOC; - req.num_args = 2; - set_argument_int(&req.arg1, size); - set_argument_int(&req.arg2, init_value); - req.outarg_type = ARG_PTR; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; - return res.ok ? res.outarg.val.addr : (uintptr_t) NULL; -} - -void call_write(const uintptr_t address, char *str, int *ok) -{ - struct request req; - struct response res; - - clear_request(&req); - clear_response(&res); - - req.command = CMD_WRITE; - req.num_args = 2; - set_argument_ptr(&req.arg1, address); - set_argument_str(&req.arg2, str); - req.outarg_type = ARG_NONE; - - send_request(CINDERELLA_DRIVER_WRITE, &req); - get_response(CINDERELLA_DRIVER_READ, &res); - - *ok = res.ok; -} - -int test_for_strlen(const uintptr_t maybe_strlen) -{ - char buf[1024]; - int ok; - int len = 0; - uintptr_t ptr = call_allocate(1000, 28, &ok); - if (!ok) return 0; - - call_write(ptr, "h", &ok); - - len = call_strlen(maybe_strlen, ptr, &ok); - assert(len == 1); - - call_write(ptr, "the quick brown fox", &ok); - len = call_strlen(maybe_strlen, ptr, &ok); - assert(len == strlen("the quick brown fox")); - - char *str = "hello %s %d %c zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"; - call_write(ptr, str, &ok); - len = call_strlen(maybe_strlen, ptr, &ok); - assert(len == strlen(str)); - - int len5 = call_strlen(maybe_strlen, ptr+5, &ok); - assert(len == (len5 + 5)); - - return 1; -} - -int test_for_strdup(const uintptr_t maybe_strdup) -{ - char buf[2048]; - char buf2[2048]; - char *str = "the quick brown fox %s %c %d xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; - char *str2 = "abcdefgh13242314132432 %s %d %c1zzfadfadsfdsafdsafdsafdfdsfsdafdaf"; - int ok; - - uintptr_t ptr = call_allocate(1000, 0, &ok); - - call_write(ptr, str, &ok); - uintptr_t new_str = call_strdup(maybe_strdup, str, &ok); -printf("test_for_strdup(): allocated[%p] new_str[%p]\n", ptr, new_str); - assert(new_str != ptr); - assert(new_str != (uintptr_t) NULL); - - call_read(buf, (uintptr_t) new_str, strlen(str)+1, &ok); - assert(strncmp(buf, str, strlen(str))==0); - - call_write(new_str, str2, &ok); - call_read(buf, (uintptr_t) new_str, strlen(str2)+1, &ok); - call_read(buf2, (uintptr_t) ptr, strlen(str)+1, &ok); - assert(strncmp(buf, buf2, strlen(str2))!=0); - - return ok; -} - -int test_for_strndup(const uintptr_t maybe_strdup) -{ - char buf[2048]; - char *str = "the quick brown fox %s %c %d xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; - int ok; - int i; - - printf("test_for_strndup(): enter\n"); - uintptr_t ptr = call_allocate(1000, 0, &ok); - - call_write(ptr, str, &ok); - uintptr_t new_str = call_strndup(maybe_strdup, str, 5, &ok); - - assert(new_str != ptr); - assert(new_str != (uintptr_t) NULL); - - call_read(buf, (uintptr_t) new_str, 6, &ok); - printf("test_for_strndup(): buf[%s] str[%s]\n"); - assert(strncmp(buf,"the q", 5) == 0); - - printf("test_for_strndup(): exit\n"); - return 1; -} - -int test_for_malloc(const uintptr_t address) -{ - char *str = "%s xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxhello how %s %d are %c %% you? \n %s"; - int ok = 0; - uintptr_t malloc_address = call_malloc(address, 2000, &ok); - if (!ok || !malloc_address) return 0; - - call_write(malloc_address, str, &ok); - if (!ok) return 0; - - char buf[2000]; - call_read(buf, malloc_address, strlen(str)+1, &ok); - assert(strncmp(buf,str,strlen(str)) == 0); - - // try larger value of malloc - char str2[10000]; - uintptr_t ptr = call_malloc(address, 2000000, &ok); - memset(str2, 'x', 500); - str2[500] = '\0'; - if (!ok) return 0; - - call_write(ptr, str2, &ok); - call_read(buf, ptr, strlen(str2)+1, &ok); - assert(strncmp(buf,str2,500) == 0); - - // can only write max 512 byte at a time (infer.h) - // so advance pointer within malloc'ed region and try writing - - // write on remote site starting at malloc'ed[25000] - uintptr_t ptr2 = ptr + 25000; - call_write(ptr2, str2, &ok); - call_read(buf, ptr2, strlen(str2)+1, &ok); - assert(strncmp(buf,str2,500) == 0); - - // write on remote site starting at malloc'ed[100000] - ptr2 = ptr + 100000; - call_write(ptr2, str2, &ok); - call_read(buf, ptr2, strlen(str2)+1, &ok); - assert(strncmp(buf,str2,500) == 0); - - // write on remote site starting at malloc'ed[1000000] - ptr2 = ptr + 1000000; - call_write(ptr2, str2, &ok); - call_read(buf, ptr2, strlen(str2)+1, &ok); - assert(strncmp(buf,str2,500) == 0); - - return ok; -} - -int test_for_calloc(const uintptr_t maybe_calloc) -{ - int ok = 0; - int i; - int count = 10; - int size = 20; - char buf[1024]; - - // call calloc - uintptr_t rptr = call_calloc(maybe_calloc, count, size, &ok); - - // verify memory returned is zeroed out - call_read(buf, rptr, count*size, &ok); - for (i = 0; i < count*size; i++) - assert(buf[i] == 0); - - char *str = (char*)malloc(count*size); - for (i = 0; i < count*size; i+=2) - { - str[i]= 'a'; - str[i+1]= 'b'; - } - str[count*size-1] = '\0'; - - call_write(rptr, str, &ok); - call_read(buf, rptr, strlen(str)+1, &ok); - assert(strncmp(buf,str,strlen(str)) == 0); - assert(buf[10]=='a'); - assert(buf[11]=='b'); - assert(buf[12]=='a'); - - return ok; -} - -int test_for_memset(const uintptr_t address) -{ - int ok; - char buf[1024]; - - uintptr_t ptr = call_allocate(256, 61, &ok); // 0..255: 61 - uintptr_t ptr2 = call_memset(address, ptr+246, 54, 1, &ok); // 246: 54 - uintptr_t ptr3 = call_memset(address, ptr+254, 56, 1, &ok); // 254: 56 - - assert(ptr != (uintptr_t) NULL); - assert(ptr2 == ptr + 246); - assert(ptr3 == ptr + 254); - - call_read(buf, ptr, 256, &ok); - assert(ok == 1); - - assert(buf[0] == 61); - assert(buf[246] == 54); - assert(buf[254] == 56); - assert(buf[255] == 61); - - return 1; -} - -int test_for_memcpy(const uintptr_t maybe_memcpy) -{ - int ok; - char buf[1024]; - - char *str = "hello how are you?"; - uintptr_t src = call_allocate(256, 61, &ok); - uintptr_t dst = call_allocate(256, 62, &ok); - - assert(src); - assert(dst); - assert(src != dst); - - call_write(src, str, &ok); - assert(ok); - - uintptr_t r = call_memcpy(maybe_memcpy, dst, src, strlen(str)+1, &ok); - assert(r == dst); - - call_read(buf, dst, 256, &ok); - assert(strncmp(buf,str,strlen(str))==0); - - return 1; -} - -// void strclpy(dst,src,size); -// dst will be NULL terminated -// src is a C-string -// size is size of the buffer -int test_for_strlcpy(const uintptr_t maybe_strlcpy) -{ - int ok; - char buf[1024] = ""; - - char *str = "12345678abcdefghijkl"; - uintptr_t src = call_allocate(256, 61, &ok); - uintptr_t dst = call_allocate(8, 62, &ok); - - assert(src); - assert(dst); - assert(src != dst); - - call_write(src, str, &ok); - assert(ok); - - int src_len = call_strlcpy(maybe_strlcpy, dst, src, 8, &ok); - assert(ok); -// assert(src_len == strlen(str)); // unreliable -- CGC examplar doesn't comply w/ API - - call_read(buf, dst, 8, &ok); - assert(strcmp(buf,"1234567")==0); - - return 1; -} - -// void strclpy(dst,src,size); -// dst will be NULL terminated -// src is a C-string -// size is size of the buffer -int test_for_strlcat(const uintptr_t maybe_strlcat) -{ - int ok; - char buf[1024] = ""; - - char *s1 = "hello, "; - char *s2 = "how are you? yo yo yo yo"; - uintptr_t src = call_allocate(256, 61, &ok); - uintptr_t dst = call_allocate(256, 62, &ok); - - call_write(src, s2, &ok); - call_write(dst, s1, &ok); - - int src_len = call_strlcat(maybe_strlcat, dst, src, 200, &ok); - call_read(buf, dst, 200, &ok); - assert(strcmp(buf,"hello, how are you? yo yo yo yo")==0); - - // strlcat guarantees null termination - call_write(dst, s1, &ok); - src_len = call_strlcat(maybe_strlcat, dst, src, 11, &ok); - call_read(buf, dst, 200, &ok); - assert(strcmp(buf,"hello, how") == 0); - - return 1; -} - -// void strclpy(dst,src,size); -// dst will not be NULL terminated necessarily -// src is a C-string -// size is size of the buffer -int test_for_strncat(const uintptr_t maybe_strncat) -{ - int ok; - char buf[1024] = ""; - - char *s1 = "hello, "; - char *s2 = "how are you? yo yo yo yo"; - uintptr_t src = call_allocate(256, 61, &ok); - uintptr_t dst = call_allocate(256, 62, &ok); - - call_write(src, s2, &ok); - call_write(dst, s1, &ok); - - int src_len = call_strlcat(maybe_strncat, dst, src, 200, &ok); - call_read(buf, dst, 200, &ok); - assert(strcmp(buf,"hello, how are you? yo yo yo yo")==0); - - // strncat does not guarantees null termination - call_write(dst, s1, &ok); - src_len = call_strlcat(maybe_strncat, dst, src, 12, &ok); - call_read(buf, dst, 200, &ok); - assert(strcmp(buf,"hello, how are you?") == 0); - - return 1; -} - -int test_for_strcmp(const uintptr_t maybe_strcmp) -{ - int ok; - - char *s1 = "hello me 1"; - char *s2 = "hello me 2"; - char *s3 = "hello me 3"; - - uintptr_t s1a = call_allocate(256, 61, &ok); - uintptr_t s2a = call_allocate(256, 62, &ok); - uintptr_t s3a = call_allocate(256, 63, &ok); - - call_write(s1a, s1, &ok); - call_write(s2a, s2, &ok); - call_write(s3a, s3, &ok); - - int r; - - r = call_strcmp(maybe_strcmp, s1a, s1a, &ok); - assert(r == 0); - - r = call_strcmp(maybe_strcmp, s1a, s2a, &ok); - assert(r < 0); - - r = call_strcmp(maybe_strcmp, s1a, s3a, &ok); - assert(r < 0); - - r = call_strcmp(maybe_strcmp, s2a, s3a, &ok); - assert(r < 0); - - r = call_strcmp(maybe_strcmp, s3a, s2a, &ok); - assert(r > 0); - - return 1; -} - -int test_for_strchr(const uintptr_t maybe_strchr) -{ - int ok; - - char *s1 = "hello me 1"; - int c = (int) 'e'; - - uintptr_t rptr_s1 = call_allocate(256, 61, &ok); - - call_write(rptr_s1, s1, &ok); - - uintptr_t rptr = call_strchr(maybe_strchr, rptr_s1, c, &ok); - - char buf[128]; - call_read(buf, rptr, 1, &ok); - assert(buf[0] == c); - assert((rptr - rptr_s1) == 1); - - return 1; -} - -int test_for_memchr(const uintptr_t maybe_memchr) -{ - int ok; - - char *s1 = "hello me 1"; - int m = (int) 'm'; - - uintptr_t rptr_s1 = call_allocate(256, 61, &ok); - - call_write(rptr_s1, s1, &ok); - - uintptr_t rptr = call_memchr(maybe_memchr, rptr_s1, m, 8, &ok); - - char buf[128]; - call_read(buf, rptr, 1, &ok); - assert(buf[0] == m); - assert((rptr - rptr_s1) == 6); - - rptr = call_memchr(maybe_memchr, rptr_s1, m, 1, &ok); - assert(rptr == 0); - - return 1; -} - -// last occurence -int test_for_strrchr(const uintptr_t maybe_strrchr) -{ - int ok; - - char *s1 = "heleo me 1"; - int c = (int) 'e'; - - uintptr_t rptr_s1 = call_allocate(256, 61, &ok); - - call_write(rptr_s1, s1, &ok); - - uintptr_t rptr = call_strchr(maybe_strrchr, rptr_s1, c, &ok); - - char buf[128]; - call_read(buf, rptr, 1, &ok); - assert(buf[0] == c); - assert((rptr - rptr_s1) == 7); - - return 1; -} - -int test_for_strncmp(const uintptr_t maybe_strncmp) -{ - int ok; - - char *s1 = "hello me 1"; - char *s2 = "hello me 2"; - char *s3 = "hello me 3"; - - uintptr_t s1a = call_allocate(256, 61, &ok); - uintptr_t s2a = call_allocate(256, 62, &ok); - uintptr_t s3a = call_allocate(256, 63, &ok); - - call_write(s1a, s1, &ok); - call_write(s2a, s2, &ok); - call_write(s3a, s3, &ok); - - int r; - - r = call_strncmp(maybe_strncmp, s1a, s1a, 100, &ok); - assert(r == 0); - - r = call_strncmp(maybe_strncmp, s1a, s2a, 100, &ok); - assert(r < 0); - - r = call_strncmp(maybe_strncmp, s1a, s3a, 100, &ok); - assert(r < 0); - - r = call_strncmp(maybe_strncmp, s2a, s3a, 100, &ok); - assert(r < 0); - - r = call_strncmp(maybe_strncmp, s3a, s2a, 100, &ok); - assert(r > 0); - - r = call_strncmp(maybe_strncmp, s1a, s2a, 5, &ok); - assert(r == 0); - - return 1; -} - -int test_for_strspn(const uintptr_t maybe_strspn) -{ - int ok; - - char *s1 = "hello jane"; - char *s2 = "hello bob"; - char *s3 = "llo"; - char *s4 = "bob"; - - uintptr_t rptr_s1 = call_allocate(256, 61, &ok); - uintptr_t rptr_s2 = call_allocate(256, 62, &ok); - uintptr_t rptr_s3 = call_allocate(256, 63, &ok); - uintptr_t rptr_s4 = call_allocate(256, 64, &ok); - - call_write(rptr_s1, s1, &ok); - call_write(rptr_s2, s2, &ok); - call_write(rptr_s3, s3, &ok); - call_write(rptr_s4, s4, &ok); - - int span; - - span = call_strspn(maybe_strspn, rptr_s1, rptr_s2, &ok); - assert(span == strspn(s1,s2)); - - span = call_strspn(maybe_strspn, rptr_s2, rptr_s1, &ok); - assert(span == strspn(s2,s1)); - - span = call_strspn(maybe_strspn, rptr_s2, rptr_s3, &ok); - assert(span == strspn(s2,s3)); - - span = call_strspn(maybe_strspn, rptr_s3, rptr_s4, &ok); - assert(span == strspn(s3,s4)); - - return 1; -} - -int test_for_strcspn(const uintptr_t maybe_strcspn) -{ - int ok; - - char *s1 = "abcde jane"; - char *s2 = "abcde bob"; - char *s3 = "bob"; - char *s4 = "bcd"; - - uintptr_t rptr_s1 = call_allocate(256, 61, &ok); - uintptr_t rptr_s2 = call_allocate(256, 62, &ok); - uintptr_t rptr_s3 = call_allocate(256, 63, &ok); - uintptr_t rptr_s4 = call_allocate(256, 64, &ok); - - call_write(rptr_s1, s1, &ok); - call_write(rptr_s2, s2, &ok); - call_write(rptr_s3, s3, &ok); - call_write(rptr_s4, s4, &ok); - - int span; - - span = call_strcspn(maybe_strcspn, rptr_s1, rptr_s2, &ok); - assert(span == strcspn(s1,s2)); - - span = call_strcspn(maybe_strcspn, rptr_s2, rptr_s1, &ok); - assert(span == strcspn(s2,s1)); - - span = call_strcspn(maybe_strcspn, rptr_s2, rptr_s3, &ok); - assert(span == strcspn(s2,s3)); - - span = call_strcspn(maybe_strcspn, rptr_s3, rptr_s4, &ok); - assert(span == strcspn(s3,s4)); - - return 1; -} - -int test_for_strtok(const uintptr_t maybe_strtok) -{ - int ok; - - char *s = "i am very hungry"; - char *tok = " "; - - uintptr_t rptr_s1 = call_allocate(256, 61, &ok); - call_write(rptr_s1, s, &ok); - - uintptr_t rptr_tok = call_allocate(256, 62, &ok); - call_write(rptr_tok, tok, &ok); - - char buf[128]; - uintptr_t rptr = call_strtok(maybe_strtok, rptr_s1, rptr_tok, &ok); - call_read(buf, rptr, 10, &ok); - printf("test_for_strtok(): buf[%s]\n", buf); - assert(strcmp(buf,"i") == 0); - - rptr = call_strtok(maybe_strtok, 0, rptr_tok, &ok); - call_read(buf, rptr, 10, &ok); - printf("test_for_strtok(): buf[%s]\n", buf); - assert(strcmp(buf,"am") == 0); - - rptr = call_strtok(maybe_strtok, 0, rptr_tok, &ok); - call_read(buf, rptr, 10, &ok); - printf("test_for_strtok(): buf[%s]\n", buf); - assert(strcmp(buf,"very") == 0); - - rptr = call_strtok(maybe_strtok, 0, rptr_tok, &ok); - call_read(buf, rptr, 10, &ok); - printf("test_for_strtok(): buf[%s]\n", buf); - assert(strcmp(buf,"hungry") == 0); - - rptr = call_strtok(maybe_strtok, 0, rptr_tok, &ok); - assert(rptr == 0); - - return 1; -} - - - -// void *realloc(void *ptr, size_t size); -int test_for_realloc(const uintptr_t malloc_adddress, const uintptr_t maybe_realloc) -{ - int ok = 0; - uintptr_t oldptr = call_malloc(malloc_address, 20, &ok); - if (oldptr && ok) - { - char buf[1024]; - char *str = "bonzai! %c %f %s %d"; - call_write(oldptr, str, &ok); - - uintptr_t newptr = call_realloc(maybe_realloc, oldptr, 200, &ok); - - assert(newptr != (uintptr_t) NULL); - assert(newptr != oldptr); - - call_read(buf, newptr, strlen(str), &ok); - assert(strncmp(buf, str, strlen(str))==0); - - return ok; - } - - return ok; -} - -void sig_chld(int signo) -{ - fprintf(stderr, "prince: SIGNAL %d raised: exit: success = %d\n", signo, success); - - if (success) - exit(EXIT_CODE_TEST_SUCCESS); - else - exit(EXIT_CODE_TEST_FAILURE); -} - -int test_prince(string executable, string libcFunction, Function_t *functionToTest) { - int pipefd[2]; - int pipefd2[2]; - pid_t pid; - int status, died; - struct sigaction act; - - /* We don't want to block any other signals in this example */ - sigemptyset(&act.sa_mask); - - /* - * We're only interested in children that have terminated, not ones - * which have been stopped (eg user pressing control-Z at terminal) - */ - act.sa_flags = SA_NOCLDSTOP; - act.sa_handler = sig_chld; - - if (sigaction(SIGCHLD, &act, NULL) < 0) - { - fprintf(stderr, "sigaction failed\n"); - return EXIT_CODE_TEST_FAILURE; - } - - const char *target = executable.c_str(); - const char *fn = libcFunction.c_str(); - uintptr_t address = functionToTest->GetEntryPoint()->GetAddress()->GetVirtualOffset(); - - pipe (pipefd); - pipe (pipefd2); - - printf("pipes: %d %d\n", pipefd[0], pipefd[1]); - int p1, p2; - p1 = dup2(pipefd[0], CINDERELLA_READ); - p2 = dup2(pipefd[1], CINDERELLA_DRIVER_WRITE); - printf("dup pipes (driver->cinderella): %d %d\n", p1, p2); - p1 = dup2(pipefd2[0], CINDERELLA_DRIVER_READ); - p2 = dup2(pipefd2[1], CINDERELLA_WRITE); - printf("dup pipes (cinderella->driver): %d %d\n", p1, p2); - - close(pipefd[0]); - close(pipefd[1]); - close(pipefd2[0]); - close(pipefd2[1]); - - switch(pid=fork()) { - case -1: fprintf(stderr, "can't fork\n"); - exit(-1); - - case 0 : // this is the code the child runs - close(0); // close stdin - close(CINDERELLA_DRIVER_READ); - close(CINDERELLA_DRIVER_WRITE); -// execl(target, target, (char*)0); - execl(target, basename((char*)target), (char*)0); - break; - - default: // this is the code the parent runs - close(CINDERELLA_READ); - close(CINDERELLA_WRITE); - fprintf(stderr, "closing pipes %d %d\n", pipefd[0], pipefd[1]); - success = 0; - if (strcmp(fn, "malloc") == 0) - success = test_for_malloc(address); - else if (strcmp(fn, "free") == 0) - { - success = find_free(CINDERELLA_DRIVER_READ, CINDERELLA_DRIVER_WRITE, malloc_address, address); - if (!success) break; - } - else if (strcmp(fn, "calloc") == 0) - { - success = test_for_calloc(address); - } - else if (strcmp(fn, "realloc") == 0) - { - success = test_for_realloc(malloc_address, address); - } - else if (strcmp(fn, "strlen") == 0) - { - success = test_for_strlen(address); - } - else if (strcmp(fn, "strdup") == 0) - { - success = test_for_strdup(address); - } - else if (strcmp(fn, "strndup") == 0) - { - success = test_for_strndup(address); - } - else if (strcmp(fn, "memset") == 0) - { - success = test_for_memset(address); - } - else if (strcmp(fn, "memcpy") == 0) - { - success = test_for_memcpy(address); - } - else if (strcmp(fn, "memchr") == 0) - { - success = test_for_memchr(address); - } - else if (strcmp(fn, "strlcpy") == 0) - { - success = test_for_strlcpy(address); - } - else if (strcmp(fn, "strlcat") == 0) - { - success = test_for_strlcat(address); - } - else if (strcmp(fn, "strncat") == 0) - { - success = test_for_strncat(address); - } - else if (strcmp(fn, "strcmp") == 0) - { - success = test_for_strcmp(address); - } - else if (strcmp(fn, "strncmp") == 0) - { - success = test_for_strncmp(address); - } - else if (strcmp(fn, "strchr") == 0) - { - success = test_for_strchr(address); - } - else if (strcmp(fn, "strrchr") == 0) - { - success = test_for_strrchr(address); - } - else if (strcmp(fn, "strspn") == 0) - { - success = test_for_strspn(address); - } - else if (strcmp(fn, "strcspn") == 0) - { - success = test_for_strcspn(address); - } - else if (strcmp(fn, "strtok") == 0) - { - success = test_for_strtok(address); - } - - fprintf(stderr, "waiting for child to exit: success = %d\n", success); - - kill(pid, SIGKILL); - -// waitpid(pid, &status, 0); - } - - return success ? EXIT_CODE_TEST_SUCCESS : EXIT_CODE_TEST_FAILURE; -} diff --git a/tools/prince/prince.sh b/tools/prince/prince.sh deleted file mode 100755 index c37660358..000000000 --- a/tools/prince/prince.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/bash -x -# -# Find <libc_function> in <binary> using functions in <filename> as candidates -# - -variant_id=$1 -binary=$2 # binary augmented via test loop -libc_function=$3 # what libc function are we looking for? -filename=$4 # file containing names of candidate functions in binary -malloc=$5 # (optional) assume $4 is malloc - -tmp=$filename.tmp.$$ - - -# prepend process id so that it's safer to use killall -binarycopy=$$.$(basename $binary) -cp $binary $binarycopy -binary=$binarycopy - -prince_driver=$SECURITY_TRANSFORMS_HOME/bin/prince_driver.exe - -tr -s '\r\n' ' ' < $filename | sed -e 's/ $/\n/' > $tmp -functions_to_test=`cat $tmp` -rm $tmp - -echo "functions_to_test: $functions_to_test" - -for function_to_test in $functions_to_test -do - echo "=== Investigating maybe $libc_function with function $function_to_test" - if [ -z $malloc ]; then - cmd="timeout 2 $prince_driver $variant_id $binary $libc_function $function_to_test" - else - cmd="timeout 2 $prince_driver $variant_id $binary $libc_function $function_to_test --malloc $malloc" - if [ "$function_to_test" = "$malloc" ]; then - echo "prince negative $libc_function $function_to_test" - continue - fi - fi - echo $cmd - $cmd - if [ $? -eq 0 ]; then - echo "prince positive $libc_function $function_to_test" - else - if [ $? -eq 1 ]; then - echo "prince negative $libc_function $function_to_test" - else - echo "prince invalid $libc_function $function_to_test" - fi - fi - killall $binary -done - -killall $binary -rm $binary &> /dev/null -echo "Done processing libc_function $libc_function with filename $filename" diff --git a/tools/prince/prince_driver.cpp b/tools/prince/prince_driver.cpp deleted file mode 100644 index ddd048ff8..000000000 --- a/tools/prince/prince_driver.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -using namespace std; -using namespace libIRDB; - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id> <target_cinderella_executable> <libc_function> <function_to_test>\n"; -} - -Function_t* findFunction(FileIR_t* firp, string functionName) -{ - FunctionSet_t functions = firp->GetFunctions(); - for (FunctionSet_t::iterator it = functions.begin(); it != functions.end(); ++it) - { - Function_t *fn = *it; - if (fn && fn->GetName() == functionName) - return fn; - } - return NULL; -} - -extern int test_prince(string targetName, string functionName, Function_t* fn); - -int main(int argc, char **argv) -{ - if(argc != 5) - { - usage(argv[0]); - exit(1); - } - - string programName(argv[0]); - int variantID = atoi(argv[1]); - string cinderellaExecutable(argv[2]); - string libcFunction(argv[3]); - string functionName(argv[4]); - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - try - { - FileIR_t *firp = new FileIR_t(*pidp, this_file); - assert(firp && pidp); - - Function_t *fn = findFunction(firp, functionName); - if (fn) { - cout << "prince_driver: cinderella_exec: " << cinderellaExecutable << " libc_function: " << functionName << " candidate_fn: " << fn->GetName() << endl; - return test_prince(cinderellaExecutable, libcFunction, fn); - } - else - return 1; - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } - - return 1; // error -} - diff --git a/tools/print_cfi_stats/Makefile.in b/tools/print_cfi_stats/Makefile.in deleted file mode 100644 index 521dc2c07..000000000 --- a/tools/print_cfi_stats/Makefile.in +++ /dev/null @@ -1,42 +0,0 @@ - - -PROGS=fix_rets.exe - -CXX=@CXX@ -CXXFLAGS= -INCLUDE=-I. -I../include -I../xform -I../../beaengine/include -I../../libIRDB/include/ -I../../libMEDSannotation/include/ -I../libtransform/include/ -I../transforms -CXXFLAGS= @EXTRA_CXXFLAGS@ $(INCLUDE) -Wall -LIBS=-L../../lib -lxform -lIRDB-core -lIRDB-cfg -lBeaEngine_s_d -lpqxx -lMEDSannotation -ltransform -lpq - - -OBJS=fix_rets.o fix_rets_driver.o -programs=fix_rets.exe - -.SUFFIXES: .o .c .exe .cpp .hpp - -all: $(programs) - @echo "---------------------------------------------" - @echo "- Fix Rets directory -- Build complete -" - @echo "---------------------------------------------" - - --include $(OBJS:.o=.d) - -%.o: %.cpp - $(CXX) -c $(CXXFLAGS) $*.cpp - @# - @# build dependencies -- http://scottmcpeak.com/autodepend/autodepend.html - @# - @cpp -M $(CXXFLAGS) $*.cpp > $*.d || true - @cp -f $*.d $*.d.tmp - @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $*.d - @rm -f $*.d.tmp - -clean: - rm -f *.o core *.exe - -$(programs): ../../lib/*.a - -fix_rets.exe: $(OBJS) - $(CXX) $(CXXFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - diff --git a/tools/print_cfi_stats/SConscript b/tools/print_cfi_stats/SConscript deleted file mode 100644 index d6c1e1736..000000000 --- a/tools/print_cfi_stats/SConscript +++ /dev/null @@ -1,29 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="print_cfi_stats_driver.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util transform MEDSannotation ") -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -#install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/plugins_install/", pgm) -Default(install) -Return('install') diff --git a/tools/print_cfi_stats/SConstruct b/tools/print_cfi_stats/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/print_cfi_stats/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/print_cfi_stats/print_cfi_stats_driver.cpp b/tools/print_cfi_stats/print_cfi_stats_driver.cpp deleted file mode 100644 index 9117d47f3..000000000 --- a/tools/print_cfi_stats/print_cfi_stats_driver.cpp +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright (c) 2014, 2015 - University of Virginia - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from the University - * of Virginia. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: University of Virginia - * e-mail: jwd@virginia.com - * URL : http://www.cs.virginia.edu/ - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - - -using namespace std; -using namespace libIRDB; - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id>\n"; -} - - -void print_cfi_stats(FileIR_t* firp) -{ - InstructionSet_t total_call_targets, total_jmp_targets, total_ret_targets, total_ib_targets; - int calls=0, jmps=0, rets=0, ibs=0; - int act_call_targs=0, act_jmp_targs=0, act_ret_targs=0, act_ib_targs=0; - int insn_count=0; - int insn_byte_count=0; - - - for( - InstructionSet_t::iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); - ++it - ) - { - Instruction_t* insn=*it; - assert(insn); - - // count total insns - insn_count++; - insn_byte_count+=insn->GetDataBits().size(); - - ICFS_t* icfs_set= insn->GetIBTargets(); - - // skip if not ib. - if(!icfs_set) continue; - - string dis=insn->getDisassembly(); - - // record IB stats. - ibs++; - act_ib_targs+=icfs_set->size(); - total_ib_targets.insert(icfs_set->begin(), icfs_set->end()); - - - if(dis.find("call")!=string::npos) - { - calls++; - act_call_targs+=icfs_set->size(); - total_call_targets.insert(icfs_set->begin(), icfs_set->end()); - } - else if(dis.find("jmp")!=string::npos) - { - jmps++; - act_jmp_targs+=icfs_set->size(); - total_jmp_targets.insert(icfs_set->begin(), icfs_set->end()); - } - else if(dis.find("ret")!=string::npos) - { - rets++; - act_ret_targs+=icfs_set->size(); - total_ret_targets.insert(icfs_set->begin(), icfs_set->end()); - } - } - - float act_targs_per_ib=(float)act_ib_targs/(float)ibs; - float act_targs_per_call=(float)act_call_targs/(float)calls; - float act_targs_per_jmp=(float)act_jmp_targs/(float)jmps; - float act_targs_per_ret=(float)act_ret_targs/(float)rets; - - cout<<"# ATTRIBUTE Control_Flow_Integrity::actual_targs_per_ib_no_cfi="<<insn_byte_count<<endl; -// cout<<"# ATTRIBUTE Control_Flow_Integrity::actual_targs_per_call_no_cfi="<<insn_byte_count<<endl; - cout<<"# ATTRIBUTE Control_Flow_Integrity::actual_targs_per_jmp_no_cfi="<<insn_byte_count<<endl; - cout<<"# ATTRIBUTE Control_Flow_Integrity::actual_targs_per_ret_no_cfi="<<insn_byte_count<<endl; - - cout<<"# ATTRIBUTE Control_Flow_Integrity::possible_targs_per_ib_basic_cfi="<<total_ib_targets.size()<<endl; -// cout<<"# ATTRIBUTE Control_Flow_Integrity::possible_targs_per_call_basic_cfi="<<total_call_targets.size()<<endl; - cout<<"# ATTRIBUTE Control_Flow_Integrity::possible_targs_per_jmp_basic_cfi="<<total_jmp_targets.size()<<endl; - cout<<"# ATTRIBUTE Control_Flow_Integrity::possible_targs_per_ret_basic_cfi="<<total_ret_targets.size()<<endl; - - cout<<"# ATTRIBUTE Control_Flow_Integrity::actual_targs_per_ib_refined_cfi="<<act_targs_per_ib<<endl; -// cout<<"# ATTRIBUTE Control_Flow_Integrity::actual_targs_per_call_refined_cfi="<<act_targs_per_call<<endl; - cout<<"# ATTRIBUTE Control_Flow_Integrity::actual_targs_per_jmp_refined_cfi="<<act_targs_per_jmp<<endl; - cout<<"# ATTRIBUTE Control_Flow_Integrity::actual_targs_per_ret_refined_cfi="<<act_targs_per_ret<<endl; - - - float basic_cfi_ib_percent_reduction=1-( (float)total_ib_targets.size() / insn_byte_count); - float basic_cfi_call_percent_reduction=1-( (float)total_call_targets.size() / insn_byte_count); - float basic_cfi_jmp_percent_reduction=1-( (float)total_jmp_targets.size() / insn_byte_count); - float basic_cfi_ret_percent_reduction=1-( (float)total_ret_targets.size() / insn_byte_count); - - cout<<"# ATTRIBUTE Control_Flow_Integrity::basic_cfi_ib_percent_reduction="<<basic_cfi_ib_percent_reduction*100.00<<"%"<<endl; - cout<<"# ATTRIBUTE Control_Flow_Integrity::basic_cfi_call_percent_reduction="<<basic_cfi_call_percent_reduction*100.00<<"%"<<endl; - cout<<"# ATTRIBUTE Control_Flow_Integrity::basic_cfi_jmp_percent_reduction="<<basic_cfi_jmp_percent_reduction*100.00<<"%"<<endl; - cout<<"# ATTRIBUTE Control_Flow_Integrity::basic_cfi_ret_percent_reduction="<<basic_cfi_ret_percent_reduction*100<<"%"<<endl; - - float refined_cfi_ib_percent_reduction=1-( act_targs_per_ib / total_ib_targets.size() ); - float refined_cfi_call_percent_reduction=1-( act_targs_per_call / total_call_targets.size() ); - float refined_cfi_jmp_percent_reduction=1-( act_targs_per_jmp / total_jmp_targets.size() ); - float refined_cfi_ret_percent_reduction=1-( act_targs_per_ret / total_ret_targets.size() ); - - cout<<"# ATTRIBUTE Control_Flow_Integrity::refined_cfi_ib_percent_reduction_over_basic="<<refined_cfi_ib_percent_reduction*100.00<<"%"<<endl; - cout<<"# ATTRIBUTE Control_Flow_Integrity::refined_cfi_call_percent_reduction_over_basic="<<refined_cfi_call_percent_reduction*100.00<<"%"<<endl; - cout<<"# ATTRIBUTE Control_Flow_Integrity::refined_cfi_jmp_percent_reduction_over_basic="<<refined_cfi_jmp_percent_reduction*100.00<<"%"<<endl; - cout<<"# ATTRIBUTE Control_Flow_Integrity::refined_cfi_ret_percent_reduction_over_basic="<<refined_cfi_ret_percent_reduction*100.00<<"%"<<endl; - -} - -int main(int argc, char **argv) -{ - if(argc != 2) - { - usage(argv[0]); - exit(1); - } - - string programName(argv[0]); - int variantID = atoi(argv[1]); - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - cout<<"ret_shadow_stack.exe started\n"; - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - try - { - - - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - cout<<"Transforming "<<this_file->GetURL()<<endl; - - assert(firp && pidp); - - - print_cfi_stats(firp); - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - // if any integer transforms for any files succeeded, we commit - if (one_success) - { - cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); - } - - return 0; -} - diff --git a/tools/ret_shadow_stack/LICENSE.txt b/tools/ret_shadow_stack/LICENSE.txt deleted file mode 100644 index ec345cd21..000000000 --- a/tools/ret_shadow_stack/LICENSE.txt +++ /dev/null @@ -1,11 +0,0 @@ -The software in this directory and its subdirectories was developed -with SBIR funding and is subject to SBIR Data Rights, as detailed -below. - -SBIR DATA RIGHTS - -Contract No. __N00014-14-C-0197___W31P4Q-14-C-0086________. -Contractor Name __Zephyr Software LLC_____________________. -Address __2040 Tremont Road, Charlottesville, VA 22911____. -Expiration of SBIR Data Rights Period __16-JUNE-2021______. - diff --git a/tools/ret_shadow_stack/Makefile.in b/tools/ret_shadow_stack/Makefile.in deleted file mode 100644 index 3e33c9665..000000000 --- a/tools/ret_shadow_stack/Makefile.in +++ /dev/null @@ -1,36 +0,0 @@ - - -PROGS=ret_shadow_stack.exe - -CC=@CC@ -CXX=@CXX@ -CFLAGS= -g -INCLUDE=-I. -I../include -I../xform -I../../beaengine/include -I../../libIRDB/include/ -I../../libMEDSannotation/include/ -I../libtransform/include/ -I../transforms -LIBS=-L../../lib -lxform -lIRDB-core -lIRDB-cfg -lBeaEngine_s_d -lpqxx -lMEDSannotation -ltransform ../transforms/Rewrite_Utility.o -lpq - - -programs=ret_shadow_stack.exe - -.SUFFIXES: .o .c .exe .cpp .hpp - -all: $(programs) - @echo "---------------------------------------------------" - @echo "- Return Shadow Stack directory -- Build complete -" - @echo "---------------------------------------------------" - -$(all_objs): *.hpp - -*.o: *.hpp - -.cpp.o: - $(CXX) $(INCLUDE) $(CFLAGS) -c $< - -clean: - rm -f *.o core *.exe - -$(programs): ../../lib/*.a - - -ret_shadow_stack.exe: rss_driver.o rss_instrument.o - $(CXX) $(CFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - diff --git a/tools/ret_shadow_stack/SConscript b/tools/ret_shadow_stack/SConscript deleted file mode 100644 index ce403bd82..000000000 --- a/tools/ret_shadow_stack/SConscript +++ /dev/null @@ -1,28 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="ret_shadow_stack.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util transform MEDSannotation ") -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install) - -Return('install') diff --git a/tools/ret_shadow_stack/SConstruct b/tools/ret_shadow_stack/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/ret_shadow_stack/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/ret_shadow_stack/rss_driver.cpp b/tools/ret_shadow_stack/rss_driver.cpp deleted file mode 100644 index bc5665737..000000000 --- a/tools/ret_shadow_stack/rss_driver.cpp +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (c) 2014 - Zephyr Software - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "MEDS_AnnotationParser.hpp" -#include "rss_instrument.hpp" - -using namespace std; -using namespace libIRDB; -using namespace MEDS_Annotation; - - -/* options */ -bool do_zipr=false; -int varid=-1; - - -#define BINARY_NAME "a.ncexe" -#define SHARED_OBJECTS_DIR "shared_objects" - - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id>\n"; -} - -int parse_args(int p_argc, char* p_argv[]) -{ - int option = 0; - char options[] = "v:z"; - struct option long_options[] = { - {"varid", required_argument, NULL, 'v'}, - {"zipr", no_argument, NULL, 'z'}, - {NULL, no_argument, NULL, '\0'}, // end-of-array marker - }; - - while ((option = getopt_long( - p_argc, - p_argv, - options, - long_options, - NULL)) != -1) - { - printf("Found option %c\n", option); - switch (option) - { - case 'v': - { - varid=atoi(::optarg); - cout<<"Transforming variant "<<dec<<varid<<endl; - break; - } - case 'z': - { - do_zipr=true; - break; - } - default: - return 1; - - } - } - - // varid is required. - if(varid==-1) - return 1; - return 0; -} - - -int main(int argc, char **argv) -{ - if(parse_args(argc,argv)!=0) - { - usage(argv[0]); - exit(1); - } - - string programName(argv[0]); - int variantID =varid; - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - cout<<"ret_shadow_stack.exe started\n"; - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - FileIR_t *firp = new FileIR_t(*pidp, this_file); - char *fileBasename = basename((char*)this_file->GetURL().c_str()); - - cout<<"Transforming "<<this_file->GetURL()<<endl; - - assert(firp && pidp); - - try - { - MEDS_AnnotationParser annotationParser; - string annotationFilename; - // need to map filename to integer annotation file produced by STARS - // this should be retrieved from the IRDB but for now, we use files to store annotations - // convention from within the peasoup subdirectory is: - // a.ncexe.infoannot - // shared_objects/<shared-lib-filename>.infoannot - if (strcmp(fileBasename, BINARY_NAME) == 0) - annotationFilename = string(BINARY_NAME); - else - annotationFilename = string(SHARED_OBJECTS_DIR) + "/" + fileBasename ; - - cerr << "annotation file: " << annotationFilename << endl; - annotationParser.parseFile(annotationFilename+".annot"); - annotationParser.parseFile(annotationFilename+".infoannot"); - annotationParser.parseFile(annotationFilename+".STARScallreturn"); - - - RSS_Instrument rssi(firp, &annotationParser, do_zipr); - - - int exitcode=rssi.execute(); - - if (exitcode == 0) - { - cout<<"Writing changes for "<<this_file->GetURL()<<endl; - one_success = true; - firp->WriteToDB(); - delete firp; - } - else - { - cout<<"Skipping (no changes) "<<this_file->GetURL()<<endl; - } - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - // if any integer transforms for any files succeeded, we commit - if (one_success) - { - cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); - } - - return 0; -} - diff --git a/tools/ret_shadow_stack/rss_instrument.cpp b/tools/ret_shadow_stack/rss_instrument.cpp deleted file mode 100644 index f93337546..000000000 --- a/tools/ret_shadow_stack/rss_instrument.cpp +++ /dev/null @@ -1,595 +0,0 @@ -/* - * Copyright (c) 2014 - Zephyr Software - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - - -#include "rss_instrument.hpp" -#include "MEDS_SafeFuncAnnotation.hpp" -#include "FuncExitAnnotation.hpp" -#include "MEDS_ProblemFuncAnnotation.hpp" -#include "Rewrite_Utility.hpp" -#include <stdlib.h> - - - -using namespace std; -using namespace libIRDB; -using namespace MEDS_Annotation; - -virtual_offset_t getAvailableAddress(FileIR_t *p_virp) -{ -/* - // traverse all instructions - // grab address - - // @todo: lookup instruction size so that we don't waste any space - // for some reason the max available address is incorrect! was ist los? - - virtual_offset_t availableAddressOffset = 0; - for( - set<Instruction_t*>::const_iterator it=p_virp->GetInstructions().begin(); - it!=p_virp->GetInstructions().end(); - ++it - ) - { - Instruction_t* insn=*it; - if (!insn) continue; - - AddressID_t* addr = insn->GetAddress(); - virtual_offset_t offset = addr->GetVirtualOffset(); - - if (offset > availableAddressOffset) - { - availableAddressOffset = offset; - } - } -// availableAddressOffset + 16; -*/ - - static int counter = -16; - counter += 16; - return 0xf0010000 + counter; -} - - - -#if 0 -// moved to Rewrite_Utility.cpp -static Instruction_t* addNewAssembly(FileIR_t* firp, Instruction_t *p_instr, string p_asm) -{ - Instruction_t* newinstr; - if (p_instr) - newinstr = allocateNewInstruction(firp,p_instr->GetAddress()->GetFileID(), p_instr->GetFunction()); - else - newinstr = allocateNewInstruction(firp,BaseObj_t::NOT_IN_DATABASE, NULL); - - firp->RegisterAssembly(newinstr, p_asm); - - if (p_instr) - { - newinstr->SetFallthrough(p_instr->GetFallthrough()); - p_instr->SetFallthrough(newinstr); - } - - return newinstr; -} -#endif - - -static Instruction_t* registerCallbackHandler64(FileIR_t* firp, Instruction_t *p_orig, string p_callbackHandler, int p_numArgs) -{ - - Instruction_t *instr; - Instruction_t *first; - char tmpbuf[1024]; - - // save flags and 16 registers (136 bytes) - // call pushes 8 bytes - // Total: 8 * 18 = 144 - first = instr = addNewAssembly(firp,NULL, "push rsp"); - instr = addNewAssembly(firp,instr, "push rbp"); - instr = addNewAssembly(firp,instr, "push rdi"); - instr = addNewAssembly(firp,instr, "push rsi"); - instr = addNewAssembly(firp,instr, "push rdx"); - instr = addNewAssembly(firp,instr, "push rcx"); - instr = addNewAssembly(firp,instr, "push rbx"); - instr = addNewAssembly(firp,instr, "push rax"); - instr = addNewAssembly(firp,instr, "push r8"); - instr = addNewAssembly(firp,instr, "push r9"); - instr = addNewAssembly(firp,instr, "push r10"); - instr = addNewAssembly(firp,instr, "push r11"); - instr = addNewAssembly(firp,instr, "push r12"); - instr = addNewAssembly(firp,instr, "push r13"); - instr = addNewAssembly(firp,instr, "push r14"); - instr = addNewAssembly(firp,instr, "push r15"); - instr = addNewAssembly(firp,instr, "pushf"); - - // handle the arguments (if any): rdi, rsi, rdx, rcx, r8, r9 - // first arg starts at byte +144 - instr = addNewAssembly(firp,instr, "mov rdi, rsp"); - - if (p_numArgs >= 1) - instr = addNewAssembly(firp,instr, "mov rsi, [rsp+144]"); - if (p_numArgs >= 2) - instr = addNewAssembly(firp,instr, "mov rdx, [rsp+152]"); - if (p_numArgs >= 3) - instr = addNewAssembly(firp,instr, "mov rcx, [rsp+160]"); - if (p_numArgs >= 4) - instr = addNewAssembly(firp,instr, "mov r8, [rsp+168]"); - if (p_numArgs > 4) - assert(0); // only handle up to 5 args - - // pin the instruction that follows the callback handler - Instruction_t* postCallback = allocateNewInstruction(firp, BaseObj_t::NOT_IN_DATABASE, NULL); - virtual_offset_t postCallbackReturn = getAvailableAddress(firp); - postCallback->GetAddress()->SetVirtualOffset(postCallbackReturn); - - // push the address to return to once the callback handler is invoked - sprintf(tmpbuf,"mov rax, 0x%x", postCallbackReturn); - instr = addNewAssembly(firp,instr, tmpbuf); - - instr = addNewAssembly(firp,instr, "push rax"); - - // use a nop instruction for the actual callback - instr = addNewAssembly(firp,instr, "nop"); - instr->SetComment(" -- callback: " + p_callbackHandler); - instr->SetCallback(p_callbackHandler); - instr->SetFallthrough(postCallback); - - - // need to make sure the post callback address is pinned - // (so that ILR and other transforms do not relocate it) - AddressID_t *indTarg = new AddressID_t(); - firp->GetAddresses().insert(indTarg); - indTarg->SetVirtualOffset(postCallback->GetAddress()->GetVirtualOffset()); - indTarg->SetFileID(BaseObj_t::NOT_IN_DATABASE); // SPRI global namespace - postCallback->SetIndirectBranchTargetAddress(indTarg); - - // restore registers - firp->RegisterAssembly(postCallback, "popf"); - - - instr = addNewAssembly(firp,postCallback, "pop r15"); - instr = addNewAssembly(firp,instr, "pop r14"); - instr = addNewAssembly(firp,instr, "pop r13"); - instr = addNewAssembly(firp,instr, "pop r12"); - instr = addNewAssembly(firp,instr, "pop r11"); - instr = addNewAssembly(firp,instr, "pop r10"); - instr = addNewAssembly(firp,instr, "pop r9"); - instr = addNewAssembly(firp,instr, "pop r8"); - instr = addNewAssembly(firp,instr, "pop rax"); - instr = addNewAssembly(firp,instr, "pop rbx"); - instr = addNewAssembly(firp,instr, "pop rcx"); - instr = addNewAssembly(firp,instr, "pop rdx"); - instr = addNewAssembly(firp,instr, "pop rsi"); - instr = addNewAssembly(firp,instr, "pop rdi"); - instr = addNewAssembly(firp,instr, "pop rbp"); - instr = addNewAssembly(firp,instr, "lea rsp, [rsp+8]"); - - instr = addNewAssembly(firp,instr, "ret"); - - // return first instruction in the callback handler chain - return first; - -} - - -// x86-64 -// 20140421 -static void ConvertCallToCallbackHandler64(FileIR_t* firp, Instruction_t *p_orig, string p_callbackHandler, int p_numArgs) -{ - static std::map<std::string, Instruction_t*> m_handlerMap; - // nb: if first time, register and cache callback handler sequence - if (m_handlerMap.count(p_callbackHandler) == 0) - { - m_handlerMap[p_callbackHandler] = registerCallbackHandler64(firp,p_orig, p_callbackHandler, p_numArgs); - } - - if (p_orig) - p_orig->SetTarget(m_handlerMap[p_callbackHandler]); -} - - -static Instruction_t* addCallbackHandlerSequence - ( - FileIR_t* firp, - Instruction_t *p_orig, - bool before, - std::string p_detector - ) -{ - - if(before) - insertAssemblyBefore(firp,p_orig,"lea rsp, [rsp-128]"); - else - assert(0); // add handling for inserting lea after given insn - - p_orig->SetComment("callback: " + p_detector); - - - Instruction_t* call =insertAssemblyAfter(firp,p_orig,"call 0"); - - ConvertCallToCallbackHandler64(firp, call, p_detector, 0); // no args for now - - insertAssemblyAfter(firp,call,"lea rsp, [rsp + 128 + 0]"); // no args for nwo - - return p_orig; -} - -static Instruction_t* addCallbackHandlerSequence_ret_addr_param - ( - FileIR_t* firp, - Instruction_t *p_orig, - bool before, - std::string p_detector - ) -{ - - if(before) - insertAssemblyBefore(firp,p_orig,"lea rsp, [rsp-128]"); - else - assert(0); // add handling for inserting lea after given insn - - p_orig->SetComment("callback: " + p_detector); - - - Instruction_t* tmp =insertAssemblyAfter(firp,p_orig,"push qword [rsp+128]"); // push ret addr for shadow stack callbacks - Instruction_t* call =insertAssemblyAfter(firp,tmp,"call 0"); - - ConvertCallToCallbackHandler64(firp, call, p_detector, 1); // 1 arg - - insertAssemblyAfter(firp,call,"lea rsp, [rsp + 128 + 8]"); // no args for nwo - - return p_orig; -} - - -static void create_tls_reloc(FileIR_t* firp, Instruction_t* insn) -{ - Relocation_t* reloc=new Relocation_t; - reloc->SetOffset(0); - reloc->SetType("tls_ss_start"); - insn->GetRelocations().insert(reloc); - firp->GetRelocations().insert(reloc); -} - - -bool RSS_Instrument::add_rss_push(FileIR_t* firp, Instruction_t* insn) -{ - - if(getenv("RSS_VERBOSE")!=NULL) - { - //DISASM d; - //Disassemble(insn,d); - cout<<"Adding push instrumentation at 0x"<<std::hex<<insn->GetAddress()->GetVirtualOffset() - << " disasm="<<insn->getDisassembly() <<endl; - } - - if(do_zipr) - { - addCallbackHandlerSequence_ret_addr_param(firp,insn,true,"zipr_push_stack"); - } - else - { - /* this moves insn to a new instructiona fter insn, and then overwrites insn */ - insertAssemblyBefore(firp,insn,"push rax"); - - /* now we insert after that insn */ - Instruction_t* tmp=insertAssemblyAfter(firp,insn,"push rcx"); - tmp=insertAssemblyAfter(firp,tmp,"mov rcx, [rsp+16]"); // load return address - tmp=insertAssemblyAfter(firp,tmp,"mov rax, [fs:0x12345678] "); - create_tls_reloc(firp,tmp); - tmp=insertAssemblyAfter(firp,tmp,"mov [rax], rcx"); - tmp=insertAssemblyAfter(firp,tmp,"lea rax, [rax+8]"); - tmp=insertAssemblyAfter(firp,tmp,"mov [fs:0x12345678], rax "); - create_tls_reloc(firp,tmp); - tmp=insertAssemblyAfter(firp,tmp,"pop rcx"); - tmp=insertAssemblyAfter(firp,tmp,"pop rax"); - - - if(getenv("tss_print_stack")!=NULL) - addCallbackHandlerSequence (firp,tmp,true,"tss_print_stack"); - } - - return true; - - -} - - -bool RSS_Instrument::add_rss_pop(FileIR_t* firp, Instruction_t* insn) -{ - - if(getenv("RSS_VERBOSE")!=NULL) - { - //DISASM d; - //Disassemble(insn,d); - cout<<"Adding pop instrumentation at 0x"<<std::hex<<insn->GetAddress()->GetVirtualOffset() - << " disasm="<<insn->getDisassembly() <<endl; - } - if(do_zipr) - { - addCallbackHandlerSequence_ret_addr_param(firp,insn,true,"zipr_pop_stack"); - } - else - { - Instruction_t *jmp_insn=NULL, *ret_to_app=NULL, *tmp=NULL, *pop_chk=NULL; - Instruction_t *jmp_insn2=NULL, *hlt_insn=NULL; - - /* this moves insn to a new instructiona fter insn, and then overwrites insn */ - insertAssemblyBefore(firp,insn,"push rcx"); - - /* now we insert after that insn */ - tmp=insertAssemblyAfter(firp,insn,"pushfq"); - pop_chk=tmp=insertAssemblyAfter(firp,tmp,"mov rcx, [fs:0x12345678] "); create_tls_reloc(firp,tmp); - tmp=insertAssemblyAfter(firp,tmp,"lea rcx, [rcx-8]"); - tmp=insertAssemblyAfter(firp,tmp,"mov [fs:0x12345678], rcx "); create_tls_reloc(firp,tmp); - - /* if tss_print_stack is on, we want to zero the old location just for easy printing. */ - /* doing so requires an extra register */ - if(getenv("tss_print_stack")!=NULL) - { - tmp=insertAssemblyAfter(firp,tmp,"push rax"); - tmp=insertAssemblyAfter(firp,tmp,"mov rax, rcx"); - } - - // load the old value - tmp=insertAssemblyAfter(firp,tmp,"mov rcx, [rcx]"); - - /* if tss_print_stack is on, we want to zero the old location just for easy printing. */ - if(getenv("tss_print_stack")!=NULL) - { - tmp=insertAssemblyAfter(firp,tmp,"mov dword [rax], 0"); - tmp=insertAssemblyAfter(firp,tmp,"pop rax"); - } - tmp=insertAssemblyAfter(firp,tmp,"sub rcx, [rsp+16]"); - jmp_insn=tmp=insertDataBitsAfter(firp,tmp,getJecxzDataBits()); // jecxz L1 - - /* - * here we've failed the fast check, try the slow check for longjmp and exception handling. - */ - /* reload rcx */ - tmp=insertAssemblyAfter(firp,tmp,"mov rcx, [fs:0x12345678] "); create_tls_reloc(firp,tmp); - tmp=insertAssemblyAfter(firp,tmp,"mov rcx, [rcx]"); // reload the TOS pointer - jmp_insn2=tmp=insertDataBitsAfter(firp,tmp,getJecxzDataBits()); // jecxz L2 - /*L2*/ hlt_insn=tmp=insertAssemblyAfter(firp,tmp,"hlt"); - /*L1*/ ret_to_app= - tmp=insertAssemblyAfter(firp,tmp,"popfq"); - tmp=insertAssemblyAfter(firp,tmp,"pop rcx"); - - /* link jump instruction to restore code */ - jmp_insn->SetTarget(ret_to_app); - - /* link jmp2 instruction to hlt if rcx is zero, and back to pop another value if non-zero */ - jmp_insn2->SetTarget(hlt_insn); - jmp_insn2->SetFallthrough(pop_chk); - - - /* add a call to print_stack after the push */ - if(getenv("tss_print_stack")!=NULL) - addCallbackHandlerSequence (firp,tmp,true,"tss_print_stack"); - - } - return true; -} - -static bool is_exit_instruction(Instruction_t *insn, MEDS_AnnotationParser *meds_ap) -{ - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); - if(d.isReturn()) // strstr(d.CompleteInstr,"ret")!=0) - return true; - - assert(meds_ap); - std::pair<MEDS_Annotations_t::iterator,MEDS_Annotations_t::iterator> ret; - - virtual_offset_t irdb_vo = insn->GetAddress()->GetVirtualOffset(); - VirtualOffset vo(irdb_vo); - - /* find it in the annotations */ - ret = meds_ap->getAnnotations().equal_range(vo); - MEDS_FuncExitAnnotation annotation; - MEDS_FuncExitAnnotation* p_annotation; - - /* for each annotation for this instruction */ - for (MEDS_Annotations_t::iterator it = ret.first; it != ret.second; ++it) - { - /* is this annotation a funcSafe annotation? */ - p_annotation=dynamic_cast<MEDS_FuncExitAnnotation*>(it->second); - if(p_annotation==NULL) - continue; - - annotation = *p_annotation; - - /* bad annotation? */ - if(!annotation.isValid()) - continue; - - return true; - } - - /* couldn't find this insn as a function exit. */ - return false; -} - -bool RSS_Instrument::add_rss_instrumentation(FileIR_t* firp, Function_t* func, MEDS_AnnotationParser *meds_ap) -{ - bool success=true; - if(func->GetEntryPoint()==NULL) - return false; - - if(getenv("RSS_VERBOSE")!=NULL) - cout<<"Transforming function "<<func->GetName()<<endl; - - - for( - set<Instruction_t*>::iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it - ) - { - Instruction_t* insn=*it; - if(is_exit_instruction(insn, meds_ap)) - success&=add_rss_pop(firp, insn); - } - - /* need to do this second, as the function entry may actually change due to popping that may happen */ - success&=add_rss_push(firp, func->GetEntryPoint()); - - return success; -} - - -static bool is_safe_func(Function_t* func, MEDS_AnnotationParser* meds_ap) -{ - assert(meds_ap); - if(!func->GetEntryPoint()) - return false; - - std::pair<MEDS_FuncAnnotations_t::iterator,MEDS_FuncAnnotations_t::iterator> ret; - - /* find it in the annotations */ - ret = meds_ap->getFuncAnnotations().equal_range(func->GetName()); - MEDS_SafeFuncAnnotation annotation; - MEDS_SafeFuncAnnotation* p_annotation; - - /* for each annotation for this instruction */ - for (MEDS_FuncAnnotations_t::iterator it = ret.first; it != ret.second; ++it) - { - /* is this annotation a funcSafe annotation? */ - p_annotation=dynamic_cast<MEDS_SafeFuncAnnotation*>(it->second); - if(p_annotation==NULL) - continue; - annotation = *p_annotation; - - /* bad annotation? */ - if(!annotation.isValid()) - continue; - - /* that marks the function safe? */ - if(annotation.isSafe()) - return true; - } - - /* couldn't find the func marked as safe */ - return false; - -} - -static bool is_problem_func(Function_t* func, MEDS_AnnotationParser* meds_ap) -{ - assert(meds_ap); - if(!func->GetEntryPoint()) - return false; - - - std::pair<MEDS_FuncAnnotations_t::iterator,MEDS_FuncAnnotations_t::iterator> ret; - - /* find it in the annotations */ - ret = meds_ap->getFuncAnnotations().equal_range(func->GetName()); - MEDS_ProblemFuncAnnotation annotation; - MEDS_ProblemFuncAnnotation* p_annotation; - - /* for each annotation for this instruction */ - for (MEDS_FuncAnnotations_t::iterator it = ret.first; it != ret.second; ++it) - { - /* is this annotation a funcSafe annotation? */ - p_annotation=dynamic_cast<MEDS_ProblemFuncAnnotation*>(it->second); - if(p_annotation==NULL) - continue; - annotation = *p_annotation; - - /* bad annotation? */ - if(!annotation.isValid()) - continue; - - /* that marks the function safe? */ - return true; - } - - /* couldn't find the func marked as safe */ - return false; - -} - -static int safe_funcs=0,problem_funcs=0, instr_funcs=0; - -static bool needs_rss_instrumentation(Function_t* func, MEDS_AnnotationParser* meds_ap) -{ - if(is_safe_func(func,meds_ap)) - { - safe_funcs++; - return false; // safe functions need no instrumentation - } - - if(is_problem_func(func,meds_ap)) - { - problem_funcs++; - return false; // problem funcs can't have instrumentation - } - - - /* otherwise, we need to instrument */ - instr_funcs++; - return true; - -} - -bool RSS_Instrument::execute() -{ - - bool success=false; - - for(set<Function_t*>::iterator it=firp->GetFunctions().begin(); - it!=firp->GetFunctions().end(); - ++it - ) - { - Function_t* func=*it; - if(needs_rss_instrumentation(func,meds_ap)) - { - cout<<"Function "<<func->GetName()<<" gets instrumentation!"; - if(func->GetEntryPoint()) - cout<<"( "<<std::hex<<func->GetEntryPoint()->GetAddress()->GetVirtualOffset()<<")"; - cout<<endl; - success|=add_rss_instrumentation(firp,func, meds_ap); - } - else - { - cout<<"Function "<<func->GetName()<<" no instrumentation!\n"; - } - - } - - cout << "# ATTRIBUTE Return_Shadow_Stack::total_funcs=" <<std::dec<<safe_funcs+problem_funcs+instr_funcs<<endl; - cout << "# ATTRIBUTE Return_Shadow_Stack::safe_funcs=" <<std::dec<<safe_funcs<<endl; - cout << "# ATTRIBUTE Return_Shadow_Stack::problem_funcs=" <<problem_funcs<<endl; - cout << "# ATTRIBUTE Return_Shadow_Stack::instr_funcs=" <<instr_funcs<<endl; - cout << "# ATTRIBUTE Return_Shadow_Stack::pct_funcs_instrumented=" <<((float)instr_funcs/(float)(safe_funcs+problem_funcs+instr_funcs))*100.00<<"%"<<endl; - - - /* return an exit code */ - if(success) - return 0; /* success? */ - - return 1; -} - - diff --git a/tools/ret_shadow_stack/rss_instrument.hpp b/tools/ret_shadow_stack/rss_instrument.hpp deleted file mode 100644 index 15b38785f..000000000 --- a/tools/ret_shadow_stack/rss_instrument.hpp +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2014 - Zephyr Software - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - -#ifndef rss_instrument_hpp -#define rss_instrument_hpp - -#include "MEDS_AnnotationParser.hpp" -#include <libIRDB-core.hpp> -#include <getopt.h> - - -class RSS_Instrument -{ - public: - RSS_Instrument(libIRDB::FileIR_t *the_firp, MEDS_Annotation::MEDS_AnnotationParser* the_meds_ap, bool p_do_zipr) : - firp(the_firp), meds_ap(the_meds_ap), do_zipr(p_do_zipr) { }; - bool execute(); - - virtual ~RSS_Instrument() {} - - private: - bool add_rss_push(libIRDB::FileIR_t* firp, libIRDB::Instruction_t* insn); - bool add_rss_pop(libIRDB::FileIR_t* firp, libIRDB::Instruction_t* insn); - bool add_rss_instrumentation(libIRDB::FileIR_t* firp, libIRDB::Function_t* func, MEDS_Annotation::MEDS_AnnotationParser *meds_ap); - - - - libIRDB::FileIR_t* firp; - MEDS_Annotation::MEDS_AnnotationParser* meds_ap; - bool do_zipr; -}; - -#endif - diff --git a/tools/safefn/LICENSE.txt b/tools/safefn/LICENSE.txt deleted file mode 100644 index ec345cd21..000000000 --- a/tools/safefn/LICENSE.txt +++ /dev/null @@ -1,11 +0,0 @@ -The software in this directory and its subdirectories was developed -with SBIR funding and is subject to SBIR Data Rights, as detailed -below. - -SBIR DATA RIGHTS - -Contract No. __N00014-14-C-0197___W31P4Q-14-C-0086________. -Contractor Name __Zephyr Software LLC_____________________. -Address __2040 Tremont Road, Charlottesville, VA 22911____. -Expiration of SBIR Data Rights Period __16-JUNE-2021______. - diff --git a/tools/safefn/Makefile.in b/tools/safefn/Makefile.in deleted file mode 100644 index dedf0185f..000000000 --- a/tools/safefn/Makefile.in +++ /dev/null @@ -1,26 +0,0 @@ - - -CC=@CC@ -CXX=@CXX@ - -INCLUDES= -I $(SECURITY_TRANSFORMS_HOME)/include -I$(SECURITY_TRANSFORMS_HOME)/beaengine/include -I $(SECURITY_TRANSFORMS_HOME)/libIRDB/include/ -I$(SECURITY_TRANSFORMS_HOME)/libMEDSannotation/include/ -LIBS= -L$(SECURITY_TRANSFORMS_HOME)/lib -lIRDB-core -lIRDB-cfg -lpqxx -L $(SECURITY_TRANSFORMS_HOME)/beaengine/lib/Linux.gnu.Debug -lBeaEngine_s_d -lMEDSannotation -lpq - -OPT=-g -.SUFFIXES: .exe .cpp - -PROGS=fill_in_safefn.exe - -all: $(PROGS) - -$(PROGS): ../../lib/* - - -.o.exe: $< $(SECURITY_TRANSFORMS_HOME)/lib/*.a - $(CXX) $< $(INCLUDES) $(LIBS) $(OPT) -o $@ - -.cpp.o: $< - $(CXX) $< $(INCLUDES) $(LIBS) $(OPT) -o $@ -c - -clean: - rm -f $(PROGS) *.o diff --git a/tools/safefn/SConscript b/tools/safefn/SConscript deleted file mode 100644 index 48212fccd..000000000 --- a/tools/safefn/SConscript +++ /dev/null @@ -1,29 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="fill_in_safefn.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util MEDSannotation ") -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install) - -Return('install') diff --git a/tools/safefn/SConstruct b/tools/safefn/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/safefn/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/safefn/fill_in_safefn.cpp b/tools/safefn/fill_in_safefn.cpp deleted file mode 100644 index a2d6f66c4..000000000 --- a/tools/safefn/fill_in_safefn.cpp +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (c) 2016 - Zephyr Software - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - - - -#include <libIRDB-core.hpp> -#include <iostream> -#include <fstream> -#include <stdlib.h> -#include <cctype> -#include <assert.h> -#include <libgen.h> - -#include "MEDS_AnnotationParser.hpp" -#include "MEDS_SafeFuncAnnotation.hpp" - -using namespace libIRDB; -using namespace std; -using namespace MEDS_Annotation; - - -#define BINARY_NAME "a.ncexe" -#define SHARED_OBJECTS_DIR "shared_objects" - -static void add_annotations(FileIR_t* firp) -{ - int num_safe_functions = 0; - char *fileBasename = basename((char*)firp->GetFile()->GetURL().c_str()); - - cout<<"Adding FR annotations to "<<firp->GetFile()->GetURL()<<endl; - - MEDS_AnnotationParser annotationParser; - string annotationFilename; - if (strcmp(fileBasename, BINARY_NAME) == 0) - annotationFilename = string(BINARY_NAME); - else - annotationFilename = string(SHARED_OBJECTS_DIR) + "/" + fileBasename ; - - cerr << "annotation file: " << annotationFilename << endl; - annotationParser.parseFile(annotationFilename+".annot.full"); - - // now, look through each instruction and match the insn to the annotation. - cout<< "Annot size is "<<std::dec<< annotationParser.getAnnotations().size() << endl; - - for(set<Instruction_t*>::iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); - ++it - ) - { - Instruction_t* insn=*it; - assert(insn); - - - /* find annotations for this insn */ - std::pair<MEDS_Annotations_t::iterator,MEDS_Annotations_t::iterator> ret; - VirtualOffset vo(insn->GetAddress()->GetVirtualOffset()); - - cout<<"Checking annotations for "<<std::hex<<vo.to_string()<<endl; - - /* find it in the annotations */ - ret = annotationParser.getAnnotations().equal_range(vo); - MEDS_SafeFuncAnnotation* p_annotation; - - /* for each annotation for this instruction */ - for (MEDS_Annotations_t::iterator it2 = ret.first; it2 != ret.second; ++it2) - { - p_annotation=dynamic_cast<MEDS_SafeFuncAnnotation*>(it2->second); - if(p_annotation==NULL) - continue; - - cout<<"Found Func SAFE annotation for "<<std::hex<<insn->GetAddress()->GetVirtualOffset()<<endl; - if (p_annotation->isSafe()) - { - Relocation_t* reloc=new Relocation_t; - reloc->SetOffset(0); - reloc->SetType("stars::safefn"); - insn->GetRelocations().insert(reloc); - firp->GetRelocations().insert(reloc); - num_safe_functions++; - } - } - } - - cout << "# ATTRIBUTE Fill_In_Safe_Functions::num_safe_functions=" << dec << num_safe_functions << endl; -} - - -main(int argc, char* argv[]) -{ - - if(argc!=2) - { - cerr<<"Usage: fill_in_safefn <id>"<<endl; - exit(-1); - } - - VariantID_t *pidp=NULL; - FileIR_t *firp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - cout<<"Reading variant "<<string(argv[1])<<" from database." << endl; - try - { - - pidp=new VariantID_t(atoi(argv[1])); - assert(pidp->IsRegistered()==true); - - - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it - ) - { - File_t* this_file=*it; - assert(this_file); - - // read the db - firp=new FileIR_t(*pidp,this_file); - - add_annotations(firp); - - firp->WriteToDB(); - - delete firp; - } - - - pqxx_interface.Commit(); - - } - catch (DatabaseError_t pnide) - { - cout<<"Unexpected database error: "<<pnide<<endl; - exit(-1); - } - - cout<<"Done!"<<endl; - - delete pidp; -} - diff --git a/tools/safefr/LICENSE.txt b/tools/safefr/LICENSE.txt deleted file mode 100644 index ec345cd21..000000000 --- a/tools/safefr/LICENSE.txt +++ /dev/null @@ -1,11 +0,0 @@ -The software in this directory and its subdirectories was developed -with SBIR funding and is subject to SBIR Data Rights, as detailed -below. - -SBIR DATA RIGHTS - -Contract No. __N00014-14-C-0197___W31P4Q-14-C-0086________. -Contractor Name __Zephyr Software LLC_____________________. -Address __2040 Tremont Road, Charlottesville, VA 22911____. -Expiration of SBIR Data Rights Period __16-JUNE-2021______. - diff --git a/tools/safefr/Makefile.in b/tools/safefr/Makefile.in deleted file mode 100644 index a840e220a..000000000 --- a/tools/safefr/Makefile.in +++ /dev/null @@ -1,26 +0,0 @@ - - -CC=@CC@ -CXX=@CXX@ - -INCLUDES= -I $(SECURITY_TRANSFORMS_HOME)/include -I$(SECURITY_TRANSFORMS_HOME)/beaengine/include -I $(SECURITY_TRANSFORMS_HOME)/libIRDB/include/ -I$(SECURITY_TRANSFORMS_HOME)/libMEDSannotation/include/ -LIBS= -L$(SECURITY_TRANSFORMS_HOME)/lib -lIRDB-core -lIRDB-cfg -lpqxx -L $(SECURITY_TRANSFORMS_HOME)/beaengine/lib/Linux.gnu.Debug -lBeaEngine_s_d -lMEDSannotation -lpq - -OPT=-g -.SUFFIXES: .exe .cpp - -PROGS=fill_in_safefr.exe - -all: $(PROGS) - -$(PROGS): ../../lib/* - - -.o.exe: $< $(SECURITY_TRANSFORMS_HOME)/lib/*.a - $(CXX) $< $(INCLUDES) $(LIBS) $(OPT) -o $@ - -.cpp.o: $< - $(CXX) $< $(INCLUDES) $(LIBS) $(OPT) -o $@ -c - -clean: - rm -f $(PROGS) *.o diff --git a/tools/safefr/SConscript b/tools/safefr/SConscript deleted file mode 100644 index b8345c801..000000000 --- a/tools/safefr/SConscript +++ /dev/null @@ -1,29 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="fill_in_safefr.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util MEDSannotation ") -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install) - -Return('install') diff --git a/tools/safefr/SConstruct b/tools/safefr/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/safefr/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/safefr/fill_in_safefr.cpp b/tools/safefr/fill_in_safefr.cpp deleted file mode 100644 index ea4a5afd1..000000000 --- a/tools/safefr/fill_in_safefr.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2014 - Zephyr Software - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - - - -#include <libIRDB-core.hpp> -#include <iostream> -#include <fstream> -#include <stdlib.h> -#include <cctype> -#include <assert.h> -#include <libgen.h> - -#include "MEDS_AnnotationParser.hpp" -#include "MEDS_FRSafeAnnotation.hpp" - -using namespace libIRDB; -using namespace std; -using namespace MEDS_Annotation; - - -#define BINARY_NAME "a.ncexe" -#define SHARED_OBJECTS_DIR "shared_objects" - -static void add_annotations(FileIR_t* firp) -{ - char *fileBasename = basename((char*)firp->GetFile()->GetURL().c_str()); - - cout<<"Adding FR annotations to "<<firp->GetFile()->GetURL()<<endl; - - - MEDS_AnnotationParser annotationParser; - string annotationFilename; - // need to map filename to integer annotation file produced by STARS - // this should be retrieved from the IRDB but for now, we use files to store annotations - // convention from within the peasoup subdirectory is: - // a.ncexe.infoannot - // shared_objects/<shared-lib-filename>.infoannot - if (strcmp(fileBasename, BINARY_NAME) == 0) - annotationFilename = string(BINARY_NAME); - else - annotationFilename = string(SHARED_OBJECTS_DIR) + "/" + fileBasename ; - - cerr << "annotation file: " << annotationFilename << endl; - annotationParser.parseFile(annotationFilename+".STARScallreturn"); - - // now, look through each instruction and match the insn to the annotation. - - cout<< "Annot size is "<<std::dec<< annotationParser.getAnnotations().size() << endl; - - for(set<Instruction_t*>::iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); - ++it - ) - { - Instruction_t* insn=*it; - assert(insn); - - - /* find annotations for this insn */ - std::pair<MEDS_Annotations_t::iterator,MEDS_Annotations_t::iterator> ret; - VirtualOffset vo(insn->GetAddress()->GetVirtualOffset()); - - cout<<"Checking annotations for "<<std::hex<<vo.to_string()<<endl; - - /* find it in the annotations */ - ret = annotationParser.getAnnotations().equal_range(vo); - MEDS_FRSafeAnnotation* p_annotation; - - /* for each annotation for this instruction */ - for (MEDS_Annotations_t::iterator it2 = ret.first; it2 != ret.second; ++it2) - { - p_annotation=dynamic_cast<MEDS_FRSafeAnnotation*>(it2->second); - if(p_annotation==NULL) - continue; - - cout<<"Found safe FR annotation for "<<std::hex<<insn->GetAddress()->GetVirtualOffset()<<endl; - Relocation_t* reloc=new Relocation_t; - reloc->SetOffset(0); - reloc->SetType("safefr"); - insn->GetRelocations().insert(reloc); - firp->GetRelocations().insert(reloc); - } - } -} - - -int main(int argc, char* argv[]) -{ - - if(argc!=2) - { - cerr<<"Usage: ilr <id>"<<endl; - exit(-1); - } - - VariantID_t *pidp=NULL; - FileIR_t *firp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - cout<<"Reading variant "<<string(argv[1])<<" from database." << endl; - try - { - - pidp=new VariantID_t(atoi(argv[1])); - assert(pidp->IsRegistered()==true); - - - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it - ) - { - File_t* this_file=*it; - assert(this_file); - - // read the db - firp=new FileIR_t(*pidp,this_file); - - add_annotations(firp); - - firp->WriteToDB(); - - delete firp; - } - - - pqxx_interface.Commit(); - - } - catch (DatabaseError_t pnide) - { - cout<<"Unexpected database error: "<<pnide<<endl; - exit(-1); - } - - cout<<"Done!"<<endl; - - delete pidp; - return 0; -} - diff --git a/tools/simple_cdi/Makefile.in b/tools/simple_cdi/Makefile.in deleted file mode 100644 index 704007c0c..000000000 --- a/tools/simple_cdi/Makefile.in +++ /dev/null @@ -1,42 +0,0 @@ - - -PROGS=selective_cfi.exe - -CXX=@CXX@ -CXXFLAGS= -INCLUDE=-I. -I../include -I../xform -I../../beaengine/include -I../../libIRDB/include/ -I../../libMEDSannotation/include/ -I../libtransform/include/ -I../transforms -CXXFLAGS= @EXTRA_CXXFLAGS@ $(INCLUDE) -LIBS=-L../../lib -lxform -lIRDB-core -lIRDB-cfg -lBeaEngine_s_d -lpqxx -lMEDSannotation -ltransform ../transforms/Rewrite_Utility.o -lpq - - -OBJS=scdi_driver.o scdi_instr.o -programs=simple_cdi.exe - -.SUFFIXES: .o .c .exe .cpp .hpp - -all: $(programs) - @echo "------------------------------------------" - @echo "- Simple CDI directory -- Build complete -" - @echo "------------------------------------------" - - --include $(OBJS:.o=.d) - -%.o: %.cpp - $(CXX) -c $(CXXFLAGS) $*.cpp - @# - @# build dependencies -- http://scottmcpeak.com/autodepend/autodepend.html - @# - @cpp -MM $(CXXFLAGS) $*.cpp > $*.d 2> /dev/null || true # might fail on solaris with CXX=sun's CC. - @cp -f $*.d $*.d.tmp - @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $*.d - @rm -f $*.d.tmp - -clean: - rm -f *.o core *.exe - -$(programs): ../../lib/*.a - -$(PROGRAMS): $(OBJS) - $(CXX) $(CXXFLAGS) $^ $(INCLUDE) $(LIBS) -o $@ - diff --git a/tools/simple_cdi/SConscript b/tools/simple_cdi/SConscript deleted file mode 100644 index 988e0df58..000000000 --- a/tools/simple_cdi/SConscript +++ /dev/null @@ -1,27 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - ''' - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="simple_cdi.exe" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util MEDSannotation ") -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/plugins_install/", pgm) -Default(install) -Return('install') diff --git a/tools/simple_cdi/SConstruct b/tools/simple_cdi/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/simple_cdi/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/simple_cdi/scdi_driver.cpp b/tools/simple_cdi/scdi_driver.cpp deleted file mode 100644 index 4a0ce5dd7..000000000 --- a/tools/simple_cdi/scdi_driver.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2014-2015 - Zephyr Software LLC - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - -#include <stdlib.h> -#include <fstream> -#include <libIRDB-core.hpp> -#include <libgen.h> - -#include "scdi_instr.hpp" - -using namespace std; -using namespace libIRDB; - - -#define BINARY_NAME "a.ncexe" -#define SHARED_OBJECTS_DIR "shared_objects" - - -void usage(char* name) -{ - cerr<<"Usage: "<<name<<" <variant_id> --threshold <return_set_threshold> (default=1)\n"; -} - -int main(int argc, char **argv) -{ - if(argc != 2) - { - usage(argv[0]); - exit(1); - } - - string programName(argv[0]); - int variantID = atoi(argv[1]); - uint32_t threshold = 1; - - // FIXME: implement getting threshold value from arguments - - VariantID_t *pidp=NULL; - - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); - - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); - - cout<<argv[0]<<" started\n"; - - bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) - { - File_t* this_file = *it; - FileIR_t *firp = new FileIR_t(*pidp, this_file); - - cout<<"Transforming "<<this_file->GetURL()<<endl; - - assert(firp && pidp); - - try - { - SimpleCDI_Instrument scdii(firp, threshold); - - int success=scdii.execute(); - - if (success) - { - cout<<"Writing changes for "<<this_file->GetURL()<<endl; - one_success = true; - firp->WriteToDB(); - delete firp; - } - else - { - cout<<"Skipping (no changes) "<<this_file->GetURL()<<endl; - } - } - catch (DatabaseError_t pnide) - { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; - } - catch (...) - { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; - } - } // end file iterator - - // if any integer transforms for any files succeeded, we commit - if (one_success) - { - cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); - } - - return 0; -} - diff --git a/tools/simple_cdi/scdi_instr.cpp b/tools/simple_cdi/scdi_instr.cpp deleted file mode 100644 index 532eeaaa0..000000000 --- a/tools/simple_cdi/scdi_instr.cpp +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (c) 2014-2015 - Zephyr Software LLC - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - - -#include <stdlib.h> -#include <cmath> - -#include "utils.hpp" -#include "scdi_instr.hpp" -#include "Rewrite_Utility.hpp" -//#include <bea_deprecated.hpp> - -using namespace std; -using namespace libIRDB; - - -template< typename T > -std::string int_to_hex_string( T i ) -{ - std::stringstream stream; - stream << "0x" - << std::hex << i; - return stream.str(); -} - -bool SimpleCDI_Instrument::add_scdi_instrumentation(Instruction_t* insn) -{ - bool success=true; - - if(getenv("SimpleCDI_VERBOSE")!=NULL) - { - cout<<"Found that "<<insn->GetBaseID()<<":"<<insn->getDisassembly()<<" can be converted to CDI"<<endl; - } - - ICFS_t* ibts=insn->GetIBTargets(); - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); - - if(getenv("SimpleCDI_VERBOSE")!=NULL && ibts) - { - cout <<"["<<d.getDisassembly()<<"] [" << d.getMnemonic()<< "] IBTargets size: " << ibts->size() << " analysis_status: " << ibts->GetAnalysisStatus() << endl; - } - - if (is_return(insn)) - { - // instrumentation must be coordinated with needs_scdi_instrumentation() - if (ibts && ibts->IsComplete() && ibts->size() == 1) - { - Instruction_t *return_site = NULL; - for(ICFS_t::iterator it=ibts->begin(); it!=ibts->end(); ++it) - { - return_site=*it; - } - - Instruction_t *ret; - if (firp->GetArchitectureBitWidth() == 64) - ret = insertAssemblyBefore(firp,insn,"lea rsp, [rsp+8]"); - else if (firp->GetArchitectureBitWidth() == 32) - ret = insertAssemblyBefore(firp,insn,"lea esp, [esp+4]"); - else - assert(0); - - ret->Assemble("jmp 0"); - ret->SetFallthrough(NULL); - ret->SetTarget(return_site); - ret->SetIBTargets(NULL); - - cout<<hex<<insn->GetAddress()->GetVirtualOffset(); - cout<<": Converted ret into a direct jmp: "<<insn->getDisassembly(); - cout<<" jmp back to: "<<ret->GetTarget()->GetAddress()->GetVirtualOffset()<<": "<<ret->GetTarget()->getDisassembly()<<dec<<endl; - single_target_set_returns++; - return true; - } - } - - //assert(strstr("ret ", d.Instruction.Mnemonic)==NULL); - //assert(strstr("retn ", d.Instruction.Mnemonic)==NULL); - assert(!d.isReturn()) ; - - // pre-instrument - // push reg - // mov reg, <target> - string reg="rcx"; - //string addr_mode=(strstr(d.CompleteInstr," ")); - string addr_mode=d.getOperand(0).getString(); - - Instruction_t* tmp=insn; - insertAssemblyBefore(firp,tmp,"push "+reg); - tmp=insertAssemblyAfter(firp,tmp,"mov "+reg+", "+addr_mode); - - for(ICFS_t::iterator it=ibts->begin(); it!=ibts->end(); ++it) - { - Instruction_t* target=*it; - // add: - // <t> pop reg -> fallthrough to <target> - // insert before: - // cmp reg, <target>; - // je <t> - assert(target && target->GetIndirectBranchTargetAddress() - && target->GetIndirectBranchTargetAddress()->GetVirtualOffset()); - - if(getenv("SimpleCDI_VERBOSE")!=NULL) - cout<<"Adding check for "<<hex<<target->GetIndirectBranchTargetAddress()->GetVirtualOffset()<<endl; - - Instruction_t *t=addNewAssembly(firp,NULL, string("pop ")+reg); - t->SetFallthrough(target); - - tmp=insertAssemblyAfter(firp,tmp, "cmp "+reg+", "+ - int_to_hex_string(target->GetIndirectBranchTargetAddress()->GetVirtualOffset())); - tmp=insertAssemblyAfter(firp,tmp,"je 0x0",t); - } - - // add hlt instrution and/or controlled exit callback. - tmp=insertAssemblyAfter(firp,tmp,"hlt"); - - // leave original instruction, because i'm lazy. - return success; -} - -bool SimpleCDI_Instrument::is_return(Instruction_t* insn) -{ - if (insn) - { - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); - return d.isReturn(); // string(d.Instruction.Mnemonic) == string("ret "); - - // FIXME: handle retn immd, but this means the instrumentation should pop/lea immd - /* return (string(d.Instruction.Mnemonic) == string("ret ") || - string(d.Instruction.Mnemonic) == string("retn ")); - */ - } - - return false; -} - -// only complete returns need to be instrumented -bool SimpleCDI_Instrument::needs_scdi_instrumentation(Instruction_t* insn, uint32_t target_size_threshold) -{ - const bool isReturn = is_return(insn); - - if (isReturn) - num_returns++; - - ICFS_t* ibts=insn->GetIBTargets(); - if(!ibts) - return false; - - if (ibts->IsComplete() && ibts->size() > 0) - { - num_complete_ibts++; - if (isReturn) - num_complete_returns++; - } - - if (isReturn) - { - if (ibts->IsComplete()) - { - if (target_set_threshold < 0) - return true; - else - return ibts->size() <= target_size_threshold; - } - else - return false; - } - - return false; -} - -bool SimpleCDI_Instrument::convert_ibs() -{ - bool success=true; - - // we do this in two passes. first pass: find instructions. - for(InstructionSet_t::iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); - ++it) - { - Instruction_t* insn=*it; - if(needs_scdi_instrumentation(insn, target_set_threshold)) - success = success && add_scdi_instrumentation(insn); - } - - return success; -} - -void SimpleCDI_Instrument::display_stats(std::ostream &out) -{ - float fraction = NAN; - out << "# ATTRIBUTE Simple_Control_Data_Integrity::target_set_threshold=" << dec << target_set_threshold << endl; - out << "# ATTRIBUTE Simple_Control_Data_Integrity::complete_ibts=" << dec << num_complete_ibts << endl; - out << "# ATTRIBUTE Simple_Control_Data_Integrity::num_returns=" << num_returns << endl; - if (num_complete_returns>0) - fraction = (float)num_complete_returns/num_returns; - out << "# ATTRIBUTE Simple_Control_Data_Integrity::num_complete_returns=" << num_complete_returns << endl; - out << "# ATTRIBUTE Simple_Control_Data_Integrity::complete_returns_fraction=" << fraction << endl; - out << "# ATTRIBUTE Simple_Control_Data_Integrity::complete_returns_pct=" << fraction*100.00<<"%" << endl; - out << "# ATTRIBUTE Simple_Control_Data_Integrity::single_target_set_jumps=" << single_target_set_jumps << endl; - out << "# ATTRIBUTE Simple_Control_Data_Integrity::single_target_set_returns=" << single_target_set_returns << endl; - - fraction = NAN; - if (num_complete_ibts > 0) - fraction = (float)(single_target_set_returns)/num_returns; - out << "# ATTRIBUTE Simple_Control_Data_Integrity::single_target_set_return_fraction=" << fraction << endl; - out << "# ATTRIBUTE Simple_Control_Data_Integrity::single_target_set_return_pct=" << fraction*100.00<<"%" << endl; -} - -/* CDI: control data isolation */ -bool SimpleCDI_Instrument::execute() -{ - - bool success=true; - - success = success && convert_ibs(); - - display_stats(cout); - - return success; -} - - diff --git a/tools/simple_cdi/scdi_instr.hpp b/tools/simple_cdi/scdi_instr.hpp deleted file mode 100644 index d22146399..000000000 --- a/tools/simple_cdi/scdi_instr.hpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2014-2015 - Zephyr Software LLC - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - -#ifndef scdi_instrument_hpp -#define scdi_instrument_hpp - -#include <iostream> -#include <libIRDB-core.hpp> - - -class SimpleCDI_Instrument -{ - public: - SimpleCDI_Instrument(libIRDB::FileIR_t *the_firp, uint32_t p_target_set_threshold=1) - : - firp(the_firp), - target_set_threshold(p_target_set_threshold), - single_target_set_jumps(0), - single_target_set_returns(0), - num_complete_ibts(0), - num_returns(0), - num_complete_returns(0) - { - } - - bool execute(); - - private: // methods - - bool is_return(libIRDB::Instruction_t* insn); - bool add_scdi_instrumentation(libIRDB::Instruction_t* insn); - bool needs_scdi_instrumentation(libIRDB::Instruction_t* insn, uint32_t p_target_set_threshold); - bool convert_ibs(); - void display_stats(std::ostream &out); - - private: // data - libIRDB::FileIR_t* firp; - uint32_t target_set_threshold; - int single_target_set_jumps; - int single_target_set_returns; - int num_complete_ibts; - int num_returns; - int num_complete_returns; -}; - -#endif - diff --git a/tools/spasm/Makefile.in b/tools/spasm/Makefile.in deleted file mode 100644 index 8f2f88fc8..000000000 --- a/tools/spasm/Makefile.in +++ /dev/null @@ -1,21 +0,0 @@ - -CXX=@CXX@ -CC=@CC@ - -CFLAGS= -g -# -DUBUNTU -Wall -O3 - -INCLUDE=-I. -I../../include -I../../xform -LIBS=-L../../xform -lxform -lpq - -.cpp.o .c.o: - $(CXX) $(CFLAGS) $(INCLUDE) -c $< - -all: spasm - echo spasm build complete - -clean: - rm -f *.o core spasm *.map *.bspri *.asm *.bin - -spasm: $(OBJS) spasm.cpp Makefile spasm.h spasm_main.cpp ben_lib.cpp ben_lib.h ../../xform/libxform.a - $(CXX) -o spasm $(INCLUDE) $(CFLAGS) spasm_main.cpp spasm.cpp ben_lib.cpp $(OBJS) $(LIBS) diff --git a/tools/spasm/SConscript b/tools/spasm/SConscript deleted file mode 100644 index 6855d4f8f..000000000 --- a/tools/spasm/SConscript +++ /dev/null @@ -1,32 +0,0 @@ -import os - - - -Import('env') -myenv=env.Clone() -myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) - -cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms - $SECURITY_TRANSFORMS_HOME/third_party/elfio-code - ''' - - -files=Glob( Dir('.').srcnode().abspath+"/*.cpp") - - -pgm="spasm" - -LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util transform MEDSannotation ") -myenv=myenv.Clone(CPPPATH=Split(cpppath)) -pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) -install=myenv.Install("$SECURITY_TRANSFORMS_HOME/bin/", pgm) -Default(install) - - - -Return('install') diff --git a/tools/spasm/SConstruct b/tools/spasm/SConstruct deleted file mode 100644 index 17f632b8c..000000000 --- a/tools/spasm/SConstruct +++ /dev/null @@ -1,7 +0,0 @@ - - - -env=Environment() -Export('env') -install=SConscript("SConscript") -Return('install') diff --git a/tools/spasm/ben_lib.cpp b/tools/spasm/ben_lib.cpp deleted file mode 100644 index e11705a09..000000000 --- a/tools/spasm/ben_lib.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2014 - Zephyr Software LLC - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - -#include "ben_lib.h" - -using namespace std; - -void trim(string& str) -{ - string::size_type pos = str.find_last_not_of(" \t\f\v\n\r"); - if(pos != string::npos) - { - str.erase(pos + 1); - pos = str.find_first_not_of(" \t\f\v\n\r"); - if(pos != string::npos) str.erase(0, pos); - } - else - str.erase(str.begin(), str.end()); -} - - -void tokenize(vector<string>& tokens, const string& str,const string& delimiters) -{ - tokens.clear(); - // Skip delimiters at beginning. - string::size_type lastPos = str.find_first_not_of(delimiters, 0); - // Find first "non-delimiter". - string::size_type pos = str.find_first_of(delimiters, lastPos); - - while (string::npos != pos || string::npos != lastPos) - { - // Found a token, add it to the vector. - tokens.push_back(str.substr(lastPos, pos - lastPos)); - - // Skip delimiters. Note the "not_of" - lastPos = str.find_first_not_of(delimiters, pos); - // Find next "non-delimiter" - pos = str.find_first_of(delimiters, lastPos); - } -} - - diff --git a/tools/spasm/ben_lib.h b/tools/spasm/ben_lib.h deleted file mode 100644 index 0d1251b52..000000000 --- a/tools/spasm/ben_lib.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2014 - Zephyr Software LLC - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - -#ifndef BENLIB -#define BENLIB -#include <vector> -#include <map> -#include <string> - -void trim(std::string &str); -void tokenize(std::vector<std::string> &tokens, const std::string &str,const std::string& delimiters=" \t\n\r"); - -template <class k, class v> -void getKeys(const std::map<k,v> &m, std::vector<k> &keys) -{ - - for(typename std::map<k,v>::const_iterator it = m.begin(); it !=m.end(); ++it) - { - keys.push_back(it->first); - } -} - -#endif diff --git a/tools/spasm/do_nasm.sh b/tools/spasm/do_nasm.sh deleted file mode 100755 index cffe7933c..000000000 --- a/tools/spasm/do_nasm.sh +++ /dev/null @@ -1,4 +0,0 @@ -# -# Make sure to turn on the BITS 32 directive in the input file -# -nasm -f bin -O2 $1 -o $2 diff --git a/tools/spasm/spasm.cpp b/tools/spasm/spasm.cpp deleted file mode 100755 index 744c1b9d9..000000000 --- a/tools/spasm/spasm.cpp +++ /dev/null @@ -1,908 +0,0 @@ -/* - * Copyright (c) 2014 - Zephyr Software LLC - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - -#include "spasm.h" -#include <vector> -#include <regex.h> -#include <iostream> -#include <ios> -#include <sstream> -#include <fstream> -#include <map> -#include <cstdlib> -#include <cerrno> -#include <climits> -#include <cstring> -#include <assert.h> -#include <stdint.h> -#include <algorithm> -#include <stdio.h> -#include <string.h> -#include <stdlib.h> -#include <sys/types.h> -#include <unistd.h> -#include "elfio/elfio.hpp" -#include "ben_lib.h" - -using namespace std; - -void ignore_result(int /* res */) { } - - -static string regularAddressRegex = "0x[[:xdigit:]]+"; -static string offsetAddressRegex = "[a-zA-Z0-9\\._-]+[[:blank:]]*[+][[:blank:]]*0x[[:xdigit:]]+|[a-zA-Z0-9\\._]+[[:blank:]]*[+][[:blank:]]*[[:xdigit:]]+"; - -static string allAddressRegex = regularAddressRegex + "|" + offsetAddressRegex; - -static string commentOnlyRegex = "^[[:blank:]]*(;|#).*$"; -static string entryRedirectRegex = "^[[:blank:]]*("+allAddressRegex + ")[[:blank:]]+(->)[[:blank:]]+([.]|[a-zA-Z0-9_]*|" + allAddressRegex + ")[[:blank:]]*((;|#).*)?$"; -static string otherRedirectRegex = "^[[:blank:]]*([.]|[a-zA-Z][a-zA-Z0-9_]*)[[:blank:]]+(->)[[:blank:]]+(("+ allAddressRegex + ")|[a-zA-Z][a-zA-Z0-9_]*)[[:blank:]]*((;|#).*)?$"; -static string insertRedirectRegex = "^[[:blank:]]*([.]|[a-zA-Z][a-zA-Z0-9_]*)[[:blank:]]+([-][|])[[:blank:]]+("+allAddressRegex + ")[[:blank:]]*((;|#).*)?$"; -static string instructionRegex = "^[[:blank:]]*([.]|[a-zA-Z][a-zA-Z0-9_]*)[[:blank:]]+([*][*])[[:blank:]]+.*$"; -static string callbackRegex = "^[[:blank:]]*([.]|[a-zA-Z][a-zA-Z0-9_]*)[[:blank:]]+([(][)])[[:blank:]]+.*$"; -static string relocRegex = "^[[:blank:]]*([.]|[a-zA-Z][a-zA-Z0-9_]*)[[:blank:]]+([r][l])[[:blank:]]+.*$"; -static string ibtlRegex = "^[[:blank:]]*([a-zA-Z][a-zA-Z0-9_]*)[[:blank:]]+([I][L])[[:blank:]]+.*$"; - -static regex_t coPattern, erPattern, orPattern, irPattern, insPattern, cbPattern, rlPattern, ibtlPattern; - - -//TODO: if I am getting rid of the requirement for 0x address prefixes, make sure comments reflec this - -typedef struct spasmline { - string address; - string op; - string rhs; //represents "right hand side" - string comment; - bool commentOnly; - unsigned int lineNum; -} spasmline_t; - -typedef struct bin_instruction { - string hex_str; - unsigned int size; - //char array is not by convention null terminated. - unsigned char raw_bin[50]; -} bin_instruction_t; - - - -static uintptr_t const ORG_PC = 0xff000000; -//padding is added to the ORG_PC for the first vpc -//the padding amount is [0-PC_PADDING_MAX), i.e., not inclusive of PC_PADDING_MAX -static unsigned int const PC_PADDING_MAX = 8001; -static uint64_t vpc = ORG_PC; -static map<string,string> symMap; -static map<string,string> callbackMap; - -static ifstream sl_stream; -static unsigned int sl_line_cnt=0; - -static void initSpasmLines(const string &inputFile); -static bool getNextSpasmLine(spasmline_t &spasm_line); -static void resetSpasmLines(); - -static void assemble(const string &assemblyFile, int bits); - -static unsigned int bin_index =0; -static unsigned int bin_fsize=0; -static unsigned char *memblock = NULL; -static unsigned int assem_cnt =0; - -static const string size_label_start = "__SPASM_SIZE_LABEL_START"; -static const string size_label_end = "__SPASM_SIZE_LABEL_END"; - - -static void initBin(const string &binFile); -static bool getNextBin(bin_instruction_t &bin,unsigned int instr_count); - -static void printSPRI(const string &symbolFilename, const string &outFile); - - -//static vector<spasmline_t> getSpasmLines(const string &inputFile); -//static vector<string> getAssembly(const vector<spasmline_t> &lines); -//static void assemble(const vector<string> &assembly, const string &assemblyFile); -static void resolveSymbols(const string &mapFile); -//static vector<bin_instruction_t> parseBin(const string &binFile); -//static vector<string> getSPRI(const vector<bin_instruction_t> &bin, const vector<spasmline_t> &spasmlines, const string &symbolFilename); -//static void printVector(const string &outputFile, const vector<string> &lines); -static uintptr_t getSymbolAddress(const string &symbolFilename, const string &symbol) ; - -// -// @todo: need to cache results -// -static string getCallbackAddress(const string &symbolFilename, const string &symbol) -{ - char buf[30]; - int diff=getSymbolAddress(symbolFilename, symbol) - - getSymbolAddress(symbolFilename, "strata_init"); - sprintf(buf,"%x", diff); - string s(buf); - return s; -} - - -static uintptr_t getSymbolAddress(const string &symbolFilename, const string &symbol) -{ - string symbolFullName = symbolFilename + "+" + symbol; - map<string,string>::iterator callbackMapIterator; - if(callbackMap.find(symbolFullName) != callbackMap.end()) - { - return (uintptr_t)strtoull(callbackMap[symbolFullName].c_str(),NULL,16); - } - -// nm -a stratafier.o.exe | egrep " integer_overflow_detector$" | cut -f1 -d' ' - string command = "$PS_NM -a " + symbolFilename + " | egrep \" " + symbol + "$\" | cut -f1 -d' '"; - char* address = new char[128]; - - FILE *fp = popen(command.c_str(), "r"); - - ignore_result(fscanf(fp,"%s", address)); - string addressString = string(address); - - //TODO: throw exception if address is not found. - //for now assert the address string isn't empty - if(addressString.empty()) - { - cerr<<"Cannot find symbol "<< symbol << " in " << symbolFilename << "."<<endl; - cerr<<"Exiting spasm early."<<endl; - assert(!addressString.empty()); - } - - pclose(fp); - delete [] address; - - callbackMap[symbolFullName] = addressString; - - return (uintptr_t) strtoull(addressString.c_str(),NULL,16); -} - -bool fexists(const string &filename) -{ - ifstream ifile(filename.c_str()); - return ifile.is_open(); -} - - -//void a2bspri(const string &input, const string &output, const string &symbolFilename) -void a2bspri(const vector<string> &input,const string &outFilename, const string &exeFilename, - const string &symbolFilename) -{ - - assert(fexists(symbolFilename)); - assert(fexists(exeFilename)); - ELFIO::elfio elfiop; - elfiop.load(exeFilename); - int bits=0; - if(getenv("SPASM_SEED")) - srand(atoi(getenv("SPASM_SEED"))); - else - srand(getpid()); - - /* make start at FF0xxxxxxxxxxxxxxxxx for x86-64 */ - if(elfiop.get_class()==ELFCLASS64) - { - bits=64; - vpc += (rand() & 0x000fffff); - vpc<<=32; - vpc += rand(); - } - else - { - bits=32; - vpc += rand()%PC_PADDING_MAX; - } - - cout<<"VPC init loc: "<<hex<<nouppercase<<vpc<<endl; - - for(unsigned int i=0;i<input.size();i++) - { - symMap.clear(); - - initSpasmLines(input[i]); - - assemble(string(input[i]+".asm"), bits); - - initBin(string(input[i]+".asm.bin")); - - resolveSymbols(input[i]+".asm.map"); - - - resetSpasmLines(); - cout<<"Printing spri to file "<<outFilename<<"..."; - - printSPRI(symbolFilename,outFilename);//output); - - cout<<"Done!"<<endl; - - } - - -//TODO: cleanup, I don't currently clean up anything on exit or exception - //clean memblock, close streams -/* - regfree(&erPattern); - regfree(&irPattern); - regfree(&orPattern); - regfree(&coPattern); - regfree(&insPattern); - regfree(&rlPattern); - regfree(&ibtlPattern); - */ - -} - - -static void initSpasmLines(const string &inputFile) -{ - - sl_line_cnt = 0; - -#define COMPILE_REGEX(pattern,the_string) \ - if (regcomp(&pattern, the_string.c_str(), REG_EXTENDED) != 0) \ - { \ - throw SpasmException("ERROR: program bug, regex compilation failure for " #the_string " in getSpasmLines"); \ - } - - COMPILE_REGEX(rlPattern,relocRegex); - COMPILE_REGEX(ibtlPattern, ibtlRegex); - COMPILE_REGEX(coPattern, commentOnlyRegex); - COMPILE_REGEX(erPattern,entryRedirectRegex); - COMPILE_REGEX(orPattern,otherRedirectRegex); - COMPILE_REGEX(irPattern,insertRedirectRegex); - COMPILE_REGEX(insPattern,instructionRegex); - COMPILE_REGEX(coPattern,commentOnlyRegex); - COMPILE_REGEX(cbPattern,callbackRegex); - - - sl_stream.open(inputFile.c_str()); - - if(!sl_stream.is_open()) - { - throw SpasmException("ERROR: input file " + inputFile + " could not be opened."); - } - -} -static void resetSpasmLines() -{ - sl_line_cnt = 0; - sl_stream.seekg(0,ios::beg); - sl_stream.clear(); -} - -static bool getNextSpasmLine(spasmline_t &spasmline) -{ - - assert(sl_stream.is_open()); - - if(!sl_stream.good()) - return false; - - sl_line_cnt++; - - string line; - getline(sl_stream,line); - vector<string> tokens; - - spasmline.address = ""; - spasmline.op = ""; - spasmline.rhs = ""; - spasmline.comment = ""; - spasmline.commentOnly = false; - spasmline.lineNum = sl_line_cnt; - - regmatch_t pmatch[5]; - - trim(line); - - if(line.length() == 0) - return getNextSpasmLine(spasmline); - - //comment only line check - if(regexec(&coPattern, line.c_str(), 0, NULL, 0)==0) - { - spasmline.commentOnly = true; - //The comment is the entire line - spasmline.comment = line; - } - else if(regexec(&erPattern,line.c_str(),5,pmatch,0)==0 || - regexec(&orPattern,line.c_str(),5,pmatch,0)==0 || - regexec(&irPattern,line.c_str(),5,pmatch,0)==0 || - regexec(&insPattern,line.c_str(),5,pmatch,0)==0 || - regexec(&cbPattern, line.c_str(),5,pmatch,0)==0 || - regexec(&ibtlPattern, line.c_str(), 5, pmatch, 0) == 0 || - regexec(&rlPattern, line.c_str(), 5, pmatch, 0) == 0) - { - int mlen = pmatch[1].rm_eo - pmatch[1].rm_so; - spasmline.address = line.substr(pmatch[1].rm_so,mlen); - - mlen = pmatch[2].rm_eo - pmatch[2].rm_so; - spasmline.op = line.substr(pmatch[2].rm_so,mlen); - - spasmline.rhs = line.substr(pmatch[2].rm_eo); - - //There may be an inline comment, search rhs for ';'and split rhs accordingly - for(unsigned int i=0;i<spasmline.rhs.length();i++) - { - if(spasmline.rhs[i] == ';' || spasmline.rhs[i] == '#') - { - spasmline.comment = spasmline.rhs.substr(i); - //yea I am changing part of the guard in a loop, but I am breaking immediately - spasmline.rhs = spasmline.rhs.substr(0,i); - - break; - } - } - - } - else - { - //TODO: close stream on failure? - stringstream ss; - ss<<sl_line_cnt; - throw SpasmException("ERROR: improperly formatted spasm line at " + ss.str()); - } - - trim(spasmline.comment); - trim(spasmline.rhs); - trim(spasmline.op); - trim(spasmline.address); - - return true; -} - - - -//initSpasmLines must be called before assembly. -//Assembly in the spasm lines are placed in the given file. -//The assembly file is then -//assembled into a raw binary file using the nasm assembler. The produced -//raw binary file is assemblyFile+".bin". -//In addition to the raw binary file, a nasm produced symbol map file is -//generated with the name assemblyFile+".map". -// -//TODO: it is currently assumed the assemblyFile string will have a .asm -//postfix, perhaps a check should be done as I don't think nasm will accept -//other extensions. -// -//[in] assemblyFile the file that will hold nasm assembly -//static void assemble(const vector<string> &assembly, const string &assemblyFile) -static void assemble(const string &assemblyFile, int bits) -{ - assem_cnt = 0; - - //remove any preexisting assembly or nasm generated files - string command = "rm -f " + assemblyFile; - ignore_result(system(command.c_str())); - command = "rm -f "+assemblyFile+".bin"; - ignore_result(system(command.c_str())); - command = "rm -f "+assemblyFile+".map"; - ignore_result(system(command.c_str())); - - - ofstream asmFile; - asmFile.open(assemblyFile.c_str()); - if(!asmFile.is_open()) - { - throw SpasmException("ERROR: Could not create a prelim assembly file for writing"); - } - - - const char *nasm_bit_width=NULL; - if(bits==64) - nasm_bit_width="BITS 64"; - else - nasm_bit_width="BITS 32"; - - asmFile<<nasm_bit_width<<endl; - asmFile<<"ORG 0x"<<hex<<nouppercase<<vpc<<endl; - asmFile<<"[map symbols "<<assemblyFile<<".map]"<<endl; - - spasmline_t sline; - - while(getNextSpasmLine(sline)) - { - // skip comments, relocations and indirect branch target limitations */ - if (sline.commentOnly || (sline.op.compare("rl") == 0) || (sline.op.compare("IL") == 0)) - continue; - - string assemblyLine = ""; - - string lineAddr = sline.address; - string lineOp = sline.op; - string lineRH = sline.rhs; - - - //if lineAddr has a plus in it, if so it is an address - //optimally I would do all these checks with a regex, but - //hindsight is 20/20 - - //If not '.' or an offset address (<base> + <offset>) - //then the address is a label - //TODO: I really need to use regex for all checks like this - if(lineAddr.find("+") == string::npos && lineAddr[0] != '.' && lineAddr[0] != '0') - { - if(symMap.find(lineAddr) != symMap.end()) - { - stringstream ss; - ss << sline.lineNum; - cout<<sline.op<<endl; - throw SpasmException("ERROR: multiple symbolic destination detected for symbol "+lineAddr+ " on line " + ss.str()); - } - - symMap[lineAddr] = ""; - assemblyLine = lineAddr + ": "; - } - - if(lineOp.compare("->")==0) - { - //Check if label or . - //non-entry point redirections require one byte of space. This space is reserved with nop - if(lineAddr.find("+") == string::npos && lineAddr[0] != '0') - { - lineRH = "nop"; - } - //else this is an entry redirect which takes up no space - else - continue; - } - else if(lineOp.compare("-|")==0) - { - //terminating redirects require one byte of space which is reserved with nop - lineRH = "nop"; - } - else if(lineOp.compare("()")==0) - { - // this is a callback -/* - assemblyLine = "; "; - assemblyLine += lineAddr; - assemblyLine += " () "; - assemblyLine += " needToResolveAddressFor: "; -*/ - string callback = lineRH; - lineRH = "nop"; - lineRH += " ;"; - lineRH += callback; - } - - assemblyLine += lineRH; - - stringstream ss; - - ss<<size_label_start<<assem_cnt; - string start_lbl = ss.str(); - ss.str(""); - ss<<size_label_end<<assem_cnt; - string end_lbl = ss.str(); - ss.str(""); - - symMap[start_lbl]=""; - symMap[end_lbl]=""; - - asmFile<<start_lbl<<":"<<endl; - asmFile<<assemblyLine<<endl; - asmFile<<end_lbl<<":"<<endl; - - assem_cnt++; - } - - asmFile.close(); - -//TODO: check if system fails, make a func call to handle system - command = "nasm -O1 -w-number-overflow " + assemblyFile + " -o "+assemblyFile+".bin"; - cout<<"Running nasm ("<<command<<")..."; - ignore_result(system(command.c_str())); - cout<<"Done!"<<endl; - - - //see if the file was created - ifstream filetest; - filetest.open(string(assemblyFile+".bin").c_str()); - - if(!filetest.is_open()) - { - throw SpasmException("Nasm failed to assemble, review error output and " + assemblyFile); - } - filetest.close(); - -} - -static void resolveSymbols(const string &mapFile) -{ - ifstream mapFileStream; - mapFileStream.open(mapFile.c_str()); - - //If the map file doesn't exist, NASM must have failed since even an empty map - //is produced if no symbols are present - if(!mapFileStream.is_open()) - { - throw SpasmException("ERROR: Nasm map file "+mapFile +" does not exist. Indicates a Nasm failure."); - } - - cout<<"Resolving Symbols .... "; - - string line; - vector<string> tokens; - while(mapFileStream.good()) - { - tokens.clear(); - getline(mapFileStream,line); - trim(line); - - if(line.empty()) - continue; - - tokenize(tokens,line); - - if(tokens.size() != 3) - continue; - - //Assume we are in a symbol table entry if there are three tokens on the line - //and the first two tokens are hex numbers - //The first token represents the physical address, the second the virtual address - //and the third is the symbol. - char *endptr; - char *tok_c_str = const_cast<char*>(tokens[0].c_str()); - uintptr_t addrval; - addrval = (uintptr_t)strtoull(tok_c_str,&endptr,16); - - if((errno == ERANGE && (addrval == (uintptr_t)ULLONG_MAX || addrval == (uintptr_t)0)) - || ((errno != 0 && addrval == (uintptr_t)0) || endptr == tok_c_str)) - { - continue; - } - - tok_c_str = const_cast<char*>(tokens[1].c_str()); - addrval = (uintptr_t)strtoull(tok_c_str,&endptr,16); - - if((errno == ERANGE && (addrval == (uintptr_t)ULLONG_MAX || addrval == (uintptr_t)0)) - || ((errno != 0 && addrval == (uintptr_t)0) || endptr == tok_c_str)) - { - continue; - } - - // convert tokens[1] to lower case - transform(tokens[1].begin(), tokens[1].end(),tokens[1].begin(), ::tolower ); - - if(symMap.find(tokens[2]) != symMap.end()) - { - symMap[tokens[2]] = tokens[1]; -// cout<<"SYMBOL RESOLVED: symbol "<<tokens[2]<<" to address "<<tokens[1]<<endl; - } - } - cout<<"Done!"<<endl; - - mapFileStream.close(); -} - -static void initBin(const string &binFile) -{ - ifstream binreader; - binreader.open(binFile.c_str(),ifstream::in|ifstream::binary); - - if(!binreader.is_open()) - { - throw SpasmException("ERROR: Nasm bin file "+binFile +" does not exist. Indicates a Nasm failure."); - } - - binreader.seekg(0,ios::end); - - bin_fsize = binreader.tellg(); - - binreader.seekg(0,ios::beg); - - memblock = new unsigned char[bin_fsize]; - - binreader.read((char*)memblock,bin_fsize); - binreader.close(); - -} - -static bool hasNextBin() -{ - return bin_index < bin_fsize; -} - -static bool getNextBin(bin_instruction_t &bin,unsigned int instr_count) -{ - if(!hasNextBin()) - return false; - - stringstream ss; - - ss<<size_label_start<<instr_count; - assert(symMap.find(ss.str()) != symMap.end()); - - string start_addr = symMap[ss.str()]; - - ss.str(""); - - ss<<size_label_end<<instr_count; - assert(symMap.find(ss.str()) != symMap.end()); - - string end_addr = symMap[ss.str()]; - - bin.size = strtoul(end_addr.c_str(),NULL,16) - strtoul(start_addr.c_str(),NULL,16); - - char tempstr[50]; - sprintf(tempstr, "%x",bin.size); - bin.hex_str = string(tempstr); - for(unsigned int i=0;i<bin.size;i++) - { - bin.raw_bin[i] = memblock[bin_index+i]; - sprintf(tempstr,"%02x",(int)memblock[bin_index+i]); - bin.hex_str += " " + string(tempstr); - } - - bin_index += bin.size; - - return true; -} - - -//It is assumed the initSpasmLines and initBin has been called at some point before function entry -static void printSPRI(const string &symbolFilename, const string &outFileName) -{ - unsigned int pop_bin_cnt=0; - ofstream outFile; - outFile.open(outFileName.c_str()); - if(!outFile.is_open()) - { - throw SpasmException("ERROR: could not write to the output file " + outFileName); - } - - resetSpasmLines(); - - spasmline_t sline; - - while (getNextSpasmLine(sline)) - { - int incSize = 0; - - string comments = ""; - if(!sline.comment.empty()) - { - comments = "#"; - comments += sline.comment.substr(1); - } - - if(sline.commentOnly) - { - //The first character is a comment symbol, replace with a spri comment symbol - //and push the comment - outFile<<comments<<endl; - continue; - } - - stringstream ss; - ss<<hex<<vpc; - - string vpcstr = ss.str(); - ss.str(""); - - string address = sline.address; - string op = sline.op; - string rhs = sline.rhs; - - string spriline = ""; - - //No non-symbols are allowed as addresses in spasm except for entry points - //which require no memory space, so push the instruction alone - //no symbols are allowed on the rhs for these spasm instructions, therefore - //there is no need to resolve any symbols - //The assumption is that spasm instruction lines (** ops), do not have - //actual addresses on the left hand side. - // if (is address and not a relocaion) - if((address.find("+") != string::npos || address[0] == '0')) - { - outFile<<endl;//ensures a space separates spri entry points - //remove 0x of the address (not necessary but makes all addresses uniform) - //rhs is replaced with current vpc - //spriline = address.substr(2)+" "+op+" "; - - spriline = address + " " + op + " "; - - //rhs has a dot symbol - if(rhs[0] == '.') - spriline += vpcstr+" "; - else if(op.compare("rl") == 0 ) - spriline += rhs; - else if(rhs.find("+") != string::npos || rhs[0] == '0') - spriline += rhs; - //rhs is a user defined symbol, and must be resolved - else - { - stringstream ss; - ss <<sline.lineNum; - assert(op.compare("->")==0 || op.compare("-|")==0); - if (symMap.find(rhs) == symMap.end()) - throw SpasmException("ERROR: unresolved symbol " + rhs + " for symbol defined on aspri line " + ss.str()); - - spriline += symMap[rhs]+" "; - } - - spriline += comments; - - outFile<<spriline<<endl; - continue; - } - - //If the address is a symbol, replace with resolved symbol address - //a symbol is not '.' or a <base> + <offset> pattern. At this point - //we have already weeded out all instructions that use a non-symbolic - //address (i.e. base+offset) so we only check for '.'. - if (address[0] != '.') - { - if (symMap.find(address) == symMap.end()) - { - stringstream ss; - ss <<sline.lineNum; - - throw SpasmException("ERROR: unresolved symbol " + address + " for symbol defined on aspri line " + ss.str()); - } - - if (comments.empty()) - comments = "#"; - else - comments += " ; "; - - comments += "src addr = <" + address + ">"; - - spriline = symMap[address]+" "; - } - //else if '.' use vpc - else - { - spriline = string(vpcstr+" "); - } - - // Append the operator to the LHS string. - spriline += (op + " "); - - // handle relocations and Indirect Branch Target Limitations - bool IBTLop = (op.compare("IL") == 0); - if (op.compare("rl") == 0) - { - spriline += rhs; - spriline += ("\t" + comments); - outFile << spriline << endl; - continue; - } - else if (IBTLop) - { - // We are parsing: Label1 IL Label2, or Label1 IL file+offset. - // The Label1 was in address and was xformed to SymMap[address] above. - if (rhs.find("+") != string::npos) { - // Parsing: Label1 IL file+offset - spriline += rhs; - } - else { - if (symMap.find(rhs) == symMap.end()) - { - stringstream ss; - ss << sline.lineNum; - throw SpasmException("ERROR: unresolved symbol " + rhs + " for symbol referenced on aspri line " + ss.str()); - } - - if (comments.empty()) - comments = "#"; - else - comments += " ; "; - - comments += "dest addr = <" + rhs + ">"; - - spriline += symMap[rhs] + " "; - spriline += ("\t" + comments); - } - outFile << spriline << endl; - continue; - } - - //grabbing bin can only happen here since the above "rl" check does not use any assembly - //checking after results in buffer overrun of bin. It is assumed from this point on - //that all operators require binary in the bin, whether or not it is actually used - //to generate the spri for its corresponding spri line. - - bin_instruction_t binLine; - - assert(getNextBin(binLine,pop_bin_cnt)); - pop_bin_cnt++; - - // handle callback handlers - bool TerminatingRedirectOp = (op.compare("-|") == 0); // need to deprecate this operator - if (op.compare("()") == 0) - { - incSize = 1; - string callbackAddress = getCallbackAddress(symbolFilename, rhs); - if (callbackAddress.empty()) - throw SpasmException(string("ERROR: could not resolve address for callback handler: " + rhs + " in symbol file: " + symbolFilename)); - spriline += callbackAddress; - } - //terminating and non-terminating redirects may have symbols on the right hand side - //resolve them. - else if (op.compare("->") == 0 || TerminatingRedirectOp) - { - //If the current disassembled instruction is not nop, then something is out of sync - stringstream ss; - ss << sline.lineNum; - if (binLine.hex_str.compare("1 90") != 0) - throw SpasmException(string("ERROR: Bug detected in getSPRI, bin out of sync with spasm lines. ") + - "Expected a place holder nop (1 90) for a SPRI redirect, but found " + binLine.hex_str + ". " + - "Sync error occurs on line " + ss.str() + " of the SPASM input file"); - - //non-entry point redirects require one byte of memory - incSize = 1; - - if (rhs.find("+") != string::npos || rhs[0] == '0') - { - spriline += rhs; - } - //else the rhs must be a label - else - { - if(symMap.find(rhs) == symMap.end()) - { - stringstream ss; - ss << sline.lineNum; - throw SpasmException("ERROR: unresolved symbol " + rhs + " for symbol referenced on aspri line " + ss.str()); - } - - if (comments.empty()) - comments = "#"; - else - comments += " ; "; - - comments += "dest addr = <" + rhs + ">"; - - spriline += symMap[rhs] + " "; - } - } - else - { - assert(op.compare("**")==0); - //Add a comment indicating the assembly used for this instruction - if(comments.empty()) - comments = "#"; - else - comments += " ; "; - - comments +=rhs; - - incSize = binLine.size; - - spriline += binLine.hex_str + " "; - } - - spriline += "\t"+comments; - - outFile<<spriline<<endl; - - vpc += incSize; - } - - //At this point all binary instructions should have been covered - //double sanity checks, just in case - assert(pop_bin_cnt == assem_cnt); - assert(!hasNextBin()); - - outFile.close(); - -} - diff --git a/tools/spasm/spasm.h b/tools/spasm/spasm.h deleted file mode 100644 index 2926635cd..000000000 --- a/tools/spasm/spasm.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2014 - Zephyr Software LLC - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - - -#ifndef SPASM -#define SPASM - -#include <string> -#include <exception> -#include <vector> - -//void a2bspri(const std::string &input, const std::string &output, const std::string &elfFile) ; -void a2bspri(const std::vector<std::string> &input,const std::string &outFilename, - const std::string &exeFilename, const std::string &symbolFilename) ; - -class SpasmException: public std::exception -{ - private: - std::string message; - - public: - SpasmException(const std::string &message) throw () - { - this->message = message; - } - - SpasmException(const char* message) throw () - { - this->message = std::string(message); - } - - ~SpasmException() throw() - { - - } - - virtual const char* what() const throw() - { - return this->message.c_str(); - } -}; - -#endif diff --git a/tools/spasm/spasm_main.cpp b/tools/spasm/spasm_main.cpp deleted file mode 100644 index d162f160b..000000000 --- a/tools/spasm/spasm_main.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2014 - Zephyr Software LLC - * - * This file may be used and modified for non-commercial purposes as long as - * all copyright, permission, and nonwarranty notices are preserved. - * Redistribution is prohibited without prior written consent from Zephyr - * Software. - * - * Please contact the authors for restrictions applying to commercial use. - * - * THIS SOURCE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - * - * Author: Zephyr Software - * e-mail: jwd@zephyr-software.com - * URL : http://www.zephyr-software.com/ - * - */ - -#include "spasm.h" -#include <iostream> -#include <fstream> -#include <string> -#include <cstdlib> -#include <vector> -#include <assert.h> - -using namespace std; - -bool fexists(string filename) -{ - ifstream ifile(filename.c_str()); - return ifile.is_open(); -} - -void usage() -{ - cerr<<"SPASM usage:\n-s <symbol file> <input files> <exe>"<<endl; - exit(1); -} - - -///Utility SPASM's main -int main(int argc, char *argv[]) -{ - string input, output, elf; - - if(argc == 5) - { - elf = string(argv[4]); - if(!fexists(elf)) - { - cerr<<"Symbol file "<<elf<<" does not exist. SPASM will not be able to process callbacks properly."<<endl; - assert(false); - } - } - else if(argc == 6) - { - elf = string(argv[4]); - if(!fexists(elf)) - { - elf = string(argv[5]); - if(!fexists(elf)) - { - cerr<<"Symbol files ("<<argv[4] << " and " << argv[6] << - ") do not exist. SPASM will not be able to process callbacks properly."<<endl; - assert(false); - } - } - - } - else - { - cerr<<"SPASM Usage:\n<input file> <output file> <symbol file> [<symbol file>] \n"<<endl; - exit(1); - } - - input = string(argv[1]); - output = string(argv[2]); - string exe = string(argv[3]); - cout<<"Input:"<<input<<endl; - cout<<"Output:"<<output<<endl; - cout<<"Symbols:"<<elf<<endl; - - vector<string> input_list; - input_list.push_back(input); - try - { - a2bspri(input_list,output,exe,elf); - } - catch (SpasmException err) - { - cerr<<err.what()<<endl; - exit(1); - } - - return 0; -} diff --git a/tools/spasm/test.aspri b/tools/spasm/test.aspri deleted file mode 100644 index fe76b6118..000000000 --- a/tools/spasm/test.aspri +++ /dev/null @@ -1,29 +0,0 @@ -; -; Test ASPRI (SPAM) file -; -## -#more comment tests -# - -a.out+ 0x00000010 -> . ; Spasm entry point -. ** sub esp, 10 -L1 ** mov ebx, 10 ; -. ** nop -. ** sub esp, 15 -. ** jmp L1 -L2 -> L1 -. -> L2 -. -> a.out+0x00000029 -. -| a.out+00000013 -. ** jmp L2 -. ** nop -. ** nop -. ** nop -. ** nop -. ** nop -. ** jmp L3 -. ** nop -. ** nop -L3 ** mov esp, 19 -a.out + 0xf000 -> L3 - diff --git a/tools/spasm/tst.s b/tools/spasm/tst.s deleted file mode 100644 index 603740040..000000000 --- a/tools/spasm/tst.s +++ /dev/null @@ -1,2 +0,0 @@ -BITS 32 -sub esp, 1 -- GitLab