Beispiel #1
0
int
RSIM_Simulator::loadSpecimen(const std::vector<std::string> &args, int existingPid/*=-1*/)
{
    ASSERT_require2(exeArgs_.empty(), "specimen cannot be loaded twice");
    ASSERT_forbid2(args.empty(), "we must at least have an executable name");

    // Save arguments
    exeName_ = args[0];
    exeArgs_ = args;

    create_process();

    if (int error = process->load(existingPid))
        return error;
    SgAsmGenericHeader *fhdr = process->mainHeader();
    entry_va = process->entryPointOriginalVa();

    RSIM_Thread *mainThread = process->get_main_thread();
    initializeStackArch(mainThread, fhdr);

    process->binary_trace_start();

    if ((process->tracingFlags() & tracingFacilityBit(TRACE_MMAP))) {
        fprintf(process->tracingFile(), "memory map after program load:\n");
        process->get_memory().dump(process->tracingFile(), "  ");
    }

    mainThread->tracing(TRACE_STATE) <<"Initial state:\n"
                                     <<*mainThread->operators()->currentState()->registerState();

    return 0;
}
Beispiel #2
0
    // Detect functions that are semantically similar by running multiple iterations of partition_functions().
    void analyze() {
        RTS_Message *m = thread->tracing(TRACE_MISC);
        Functions functions = find_functions(m, thread->get_process());
        PointerDetectors pointers = detect_pointers(m, thread, functions);
        PartitionForest partition;
        while (partition.nlevels()<MAX_ITERATIONS) {
            InputValues inputs = choose_inputs(3, 3);
            size_t level = partition.new_level(inputs);
            m->mesg("####################################################################################################");
            m->mesg("%s: fuzz testing %zu function%s at level %zu", name, functions.size(), 1==functions.size()?"":"s", level);
            m->mesg("%s: using these input values:\n%s", name, inputs.toString().c_str());

            if (0==level) {
                partition_functions(m, partition, functions, pointers, inputs, NULL);
            } else {
                const PartitionForest::Vertices &parent_vertices = partition.vertices_at_level(level-1);
                for (PartitionForest::Vertices::const_iterator pvi=parent_vertices.begin(); pvi!=parent_vertices.end(); ++pvi) {
                    PartitionForest::Vertex *parent_vertex = *pvi;
                    if (parent_vertex->functions.size()>MAX_SIMSET_SIZE)
                        partition_functions(m, partition, parent_vertex->functions, pointers, inputs, parent_vertex);
                }
            }

            // If the new level doesn't contain any vertices then we must not have needed to repartition anything and we're all
            // done.
            if (partition.vertices_at_level(level).empty())
                break;
        }

        m->mesg("==========================================================================================");
        m->mesg("%s: The entire partition forest follows...", name);
        m->mesg("%s", StringUtility::prefixLines(partition.toString(), std::string(name)+": ").c_str());

        m->mesg("==========================================================================================");
        m->mesg("%s: Final function similarity sets are:", name);
        PartitionForest::Vertices leaves = partition.get_leaves();
        size_t setno=0;
        for (PartitionForest::Vertices::iterator vi=leaves.begin(); vi!=leaves.end(); ++vi, ++setno) {
            PartitionForest::Vertex *leaf = *vi;
            const Functions &functions = leaf->get_functions();
            m->mesg("%s:   set #%zu at level %zu has %zu function%s:",
                    name, setno, leaf->get_level(), functions.size(), 1==functions.size()?"":"s");
            for (Functions::const_iterator fi=functions.begin(); fi!=functions.end(); ++fi)
                m->mesg("%s:     0x%08"PRIx64" <%s>", name, (*fi)->get_entry_va(), (*fi)->get_name().c_str());
        }

        m->mesg("%s: dumping final similarity sets to clones.sql", name);
        partition.dump("clones.sql", "NO_USER", "NO_PASSWD");
    }
Beispiel #3
0
/** Main driving function for clone detection.  This is the class that chooses inputs, runs each function, and looks at the
 *  outputs to decide how to partition the functions.  It does this repeatedly in order to build a PartitionForest. The
 *  analyze() method is the main entry point. */
class CloneDetector {
protected:
    static const char *name;            /**< For --debug output. */
    RSIM_Thread *thread;                /**< Thread where analysis is running. */
    PartitionForest partition;          /**< Partitioning of functions into similarity sets. */
    enum { MAX_ITERATIONS = 10 };       /**< Maximum number of times we run the functions; max number of input sets. */
    enum { MAX_SIMSET_SIZE = 3 };       /**< Any similarity set containing more than this many functions will be partitioned. */

public:
    CloneDetector(RSIM_Thread *thread): thread(thread) {}

    // Allocate a page of memory in the process address space.
    rose_addr_t allocate_page(rose_addr_t hint=0) {
        RSIM_Process *proc = thread->get_process();
        rose_addr_t addr = proc->mem_map(hint, 4096, MemoryMap::MM_PROT_RW, MAP_ANONYMOUS, 0, -1);
        assert((int64_t)addr>=0 || (int64_t)addr<-256); // disallow error numbers
        return addr;
    }

    // Obtain a memory map for disassembly
    MemoryMap *disassembly_map(RSIM_Process *proc) {
        MemoryMap *map = new MemoryMap(proc->get_memory(), MemoryMap::COPY_SHALLOW);
        map->prune(MemoryMap::MM_PROT_READ); // don't let the disassembler read unreadable memory, else it will segfault

        // Removes execute permission for any segment whose debug name does not contain the name of the executable. When
        // comparing two different executables for clones, we probably don't need to compare code that came from dynamically
        // linked libraries since they will be identical in both executables.
        struct Pruner: MemoryMap::Visitor {
            std::string exename;
            Pruner(const std::string &exename): exename(exename) {}
            virtual bool operator()(const MemoryMap*, const Extent&, const MemoryMap::Segment &segment_) {
                MemoryMap::Segment *segment = const_cast<MemoryMap::Segment*>(&segment_);
                if (segment->get_name().find(exename)==std::string::npos) {
                    unsigned p = segment->get_mapperms();
                    p &= ~MemoryMap::MM_PROT_EXEC;
                    segment->set_mapperms(p);
                }
                return true;
            }
        } pruner(proc->get_exename());
        map->traverse(pruner);
        return map;
    }

    // Get all the functions defined for this process image.  We do this by disassembling the entire process executable memory
    // and using CFG analysis to figure out where the functions are located.
    Functions find_functions(RTS_Message *m, RSIM_Process *proc) {
        m->mesg("%s triggered; disassembling entire specimen image...\n", name);
        MemoryMap *map = disassembly_map(proc);
        std::ostringstream ss;
        map->dump(ss, "  ");
        m->mesg("%s: using this memory map for disassembly:\n%s", name, ss.str().c_str());
        SgAsmBlock *gblk = proc->disassemble(false/*take no shortcuts*/, map);
        delete map; map=NULL;
        std::vector<SgAsmFunction*> functions = SageInterface::querySubTree<SgAsmFunction>(gblk);
#if 0 /*DEBUGGING [Robb P. Matzke 2013-02-12]*/
        // Prune the function list to contain only what we want.
        for (std::vector<SgAsmFunction*>::iterator fi=functions.begin(); fi!=functions.end(); ++fi) {
            if ((*fi)->get_name().compare("_Z1fRi")!=0)
                *fi = NULL;
        }
        functions.erase(std::remove(functions.begin(), functions.end(), (SgAsmFunction*)NULL), functions.end());
#endif
        return Functions(functions.begin(), functions.end());
    }

    // Perform a pointer-detection analysis on each function. We'll need the results in order to determine whether a function
    // input should consume a pointer or a non-pointer from the input value set.
    typedef std::map<SgAsmFunction*, CloneDetection::PointerDetector> PointerDetectors;
    PointerDetectors detect_pointers(RTS_Message *m, RSIM_Thread *thread, const Functions &functions) {
        // Choose an SMT solver. This is completely optional.  Pointer detection still seems to work fairly well (and much,
        // much faster) without an SMT solver.
        SMTSolver *solver = NULL;
#if 0   // optional code
        if (YicesSolver::available_linkage())
            solver = new YicesSolver;
#endif
        PointerDetectors retval;
        CloneDetection::InstructionProvidor *insn_providor = new CloneDetection::InstructionProvidor(thread->get_process());
        for (Functions::iterator fi=functions.begin(); fi!=functions.end(); ++fi) {
            m->mesg("%s: performing pointer detection analysis for \"%s\" at 0x%08"PRIx64,
                    name, (*fi)->get_name().c_str(), (*fi)->get_entry_va());
            CloneDetection::PointerDetector pd(insn_providor, solver);
            pd.initial_state().registers.gpr[x86_gpr_sp] = SYMBOLIC_VALUE<32>(thread->policy.INITIAL_STACK);
            pd.initial_state().registers.gpr[x86_gpr_bp] = SYMBOLIC_VALUE<32>(thread->policy.INITIAL_STACK);
            //pd.set_debug(stderr);
            pd.analyze(*fi);
            retval.insert(std::make_pair(*fi, pd));
#if 1 /*DEBUGGING [Robb P. Matzke 2013-01-24]*/
            if (m->get_file()) {
                const CloneDetection::PointerDetector::Pointers plist = pd.get_pointers();
                for (CloneDetection::PointerDetector::Pointers::const_iterator pi=plist.begin(); pi!=plist.end(); ++pi) {
                    std::ostringstream ss;
                    if (pi->type & BinaryAnalysis::PointerAnalysis::DATA_PTR)
                        ss <<"data ";
                    if (pi->type & BinaryAnalysis::PointerAnalysis::CODE_PTR)
                        ss <<"code ";
                    ss <<"pointer at " <<pi->address;
                    m->mesg("   %s", ss.str().c_str());
                }
            }
#endif
        }
        return retval;
    }

    // Randomly choose a set of input values. The set will consist of the specified number of non-pointers and pointers. The
    // non-pointer values are chosen randomly, but limited to a certain range.  The pointers are chosen randomly to be null or
    // non-null and the non-null values each have one page allocated via simulated mmap() (i.e., the non-null values themselves
    // are not actually random).
    InputValues choose_inputs(size_t nintegers, size_t npointers) {
        static unsigned integer_modulus = 256;  // arbitrary;
        static unsigned nonnull_denom = 3;      // probability of a non-null pointer is 1/N
        CloneDetection::InputValues inputs;
        for (size_t i=0; i<nintegers; ++i)
            inputs.add_integer(rand() % integer_modulus);
        for (size_t i=0; i<npointers; ++i)
            inputs.add_pointer(rand()%nonnull_denom ? 0 : allocate_page());
        return inputs;
    }

    // Run a single function, look at its outputs, and insert it into the correct place in the PartitionForest
    void insert_function(SgAsmFunction *func, InputValues &inputs, CloneDetection::PointerDetector &pointers,
                         PartitionForest &partition, PartitionForest::Vertex *parent) {
        CloneDetection::Outputs<RSIM_SEMANTICS_VTYPE> *outputs = fuzz_test(func, inputs, pointers);
        OutputValues concrete_outputs = outputs->get_values();
        partition.insert(func, concrete_outputs, parent);
    }

    // Analyze a single function by running it with the specified inputs and collecting its outputs. */
    CloneDetection::Outputs<RSIM_SEMANTICS_VTYPE> *fuzz_test(SgAsmFunction *function, CloneDetection::InputValues &inputs,
                                                             const CloneDetection::PointerDetector &pointers) {
        RSIM_Process *proc = thread->get_process();
        RTS_Message *m = thread->tracing(TRACE_MISC);
        m->mesg("==========================================================================================");
        m->mesg("%s: fuzz testing function \"%s\" at 0x%08"PRIx64, name, function->get_name().c_str(), function->get_entry_va());

        // Not sure if saving/restoring memory state is necessary. I don't thing machine memory is adjusted by the semantic
        // policy's writeMemory() or readMemory() operations after the policy is triggered to enable our analysis.  But it
        // shouldn't hurt to save/restore anyway, and it's fast. [Robb Matzke 2013-01-14]
        proc->mem_transaction_start(name);
        pt_regs_32 saved_regs = thread->get_regs();

        // Trigger the analysis, resetting it to start executing the specified function using the input values and pointer
        // variable addresses we selected previously.
        thread->policy.trigger(function->get_entry_va(), &inputs, &pointers);

        // "Run" the function using our semantic policy.  The function will not "run" in the normal sense since: since our
        // policy has been triggered, memory access, function calls, system calls, etc. will all operate differently.  See
        // CloneDetectionSemantics.h and CloneDetectionTpl.h for details.
        try {
            thread->main();
        } catch (const Disassembler::Exception &e) {
            // Probably due to the analyzed function's RET instruction, but could be from other things as well. In any case, we
            // stop analyzing the function when this happens.
            m->mesg("%s: function disassembly failed at 0x%08"PRIx64": %s", name, e.ip, e.mesg.c_str());
        } catch (const CloneDetection::InsnLimitException &e) {
            // The analysis might be in an infinite loop, such as when analyzing "void f() { while(1); }"
            m->mesg("%s: %s", name, e.mesg.c_str());
        } catch (const RSIM_Semantics::InnerPolicy<>::Halt &e) {
            // The x86 HLT instruction appears in some functions (like _start) as a failsafe to terminate a process.  We need
            // to intercept it and terminate only the function analysis.
            m->mesg("%s: function executed HLT instruction at 0x%08"PRIx64, name, e.ip);
        }

        // Gather the function's outputs before restoring machine state.
        bool verbose = true;
        CloneDetection::Outputs<RSIM_SEMANTICS_VTYPE> *outputs = thread->policy.get_outputs(verbose);
        thread->init_regs(saved_regs);
        proc->mem_transaction_rollback(name);
        return outputs;
    }
Beispiel #4
0
int
RSIM_Simulator::main_loop()
{
    RSIM_Process *process = get_process();
    RSIM_Thread *thread = process->get_main_thread();

    /* The simulator's main thread is executed by the calling thread because the simulator's main thread must be a thread group
     * leader. */
    bool cb_process_status = process->get_callbacks().call_process_callbacks(RSIM_Callbacks::BEFORE, process,
                                                                             RSIM_Callbacks::ProcessCallback::START,
                                                                             true);

    // The process' main thread has already been created and initialized but has not started running yet.
    thread->start();
    thread->waitForState(RSIM_Thread::TERMINATED);

    process->get_callbacks().call_process_callbacks(RSIM_Callbacks::AFTER, process,
                                                    RSIM_Callbacks::ProcessCallback::FINISH,
                                                    cb_process_status);

    return process->get_termination_status();
}
Beispiel #5
0
    PointerDetectors detect_pointers(RTS_Message *m, RSIM_Thread *thread, const Functions &functions) {
        // Choose an SMT solver. This is completely optional.  Pointer detection still seems to work fairly well (and much,
        // much faster) without an SMT solver.
        SMTSolver *solver = NULL;
#if 0   // optional code
        if (YicesSolver::available_linkage())
            solver = new YicesSolver;
#endif
        PointerDetectors retval;
        CloneDetection::InstructionProvidor *insn_providor = new CloneDetection::InstructionProvidor(thread->get_process());
        for (Functions::iterator fi=functions.begin(); fi!=functions.end(); ++fi) {
            m->mesg("%s: performing pointer detection analysis for \"%s\" at 0x%08"PRIx64,
                    name, (*fi)->get_name().c_str(), (*fi)->get_entry_va());
            CloneDetection::PointerDetector pd(insn_providor, solver);
            pd.initial_state().registers.gpr[x86_gpr_sp] = SYMBOLIC_VALUE<32>(thread->policy.INITIAL_STACK);
            pd.initial_state().registers.gpr[x86_gpr_bp] = SYMBOLIC_VALUE<32>(thread->policy.INITIAL_STACK);
            //pd.set_debug(stderr);
            pd.analyze(*fi);
            retval.insert(std::make_pair(*fi, pd));
#if 1 /*DEBUGGING [Robb P. Matzke 2013-01-24]*/
            if (m->get_file()) {
                const CloneDetection::PointerDetector::Pointers plist = pd.get_pointers();
                for (CloneDetection::PointerDetector::Pointers::const_iterator pi=plist.begin(); pi!=plist.end(); ++pi) {
                    std::ostringstream ss;
                    if (pi->type & BinaryAnalysis::PointerAnalysis::DATA_PTR)
                        ss <<"data ";
                    if (pi->type & BinaryAnalysis::PointerAnalysis::CODE_PTR)
                        ss <<"code ";
                    ss <<"pointer at " <<pi->address;
                    m->mesg("   %s", ss.str().c_str());
                }
            }
#endif
        }
        return retval;
    }
Beispiel #6
0
 // Allocate a page of memory in the process address space.
 rose_addr_t allocate_page(rose_addr_t hint=0) {
     RSIM_Process *proc = thread->get_process();
     rose_addr_t addr = proc->mem_map(hint, 4096, MemoryMap::MM_PROT_RW, MAP_ANONYMOUS, 0, -1);
     assert((int64_t)addr>=0 || (int64_t)addr<-256); // disallow error numbers
     return addr;
 }