Пример #1
0
    def start(self):
        logger.info("YaCo.start()")
        self.YaCoUI.hook()

        try:
            self.ida_hooks.unhook()
            self.initial_load()
            idc.Wait()
            self.ida_hooks.hook()
        except:
            traceback.print_exc()
            self.YaCoUI.unhook()
            self.ida_hooks.unhook()
            logger.error('Error during load cache, YaCo is disabled !')

        idc.set_inf_attr(idc.INFFL_AUTO, False)

        for menu_item in self.yaco_menus:
            name = menu_item[0]
            text = menu_item[1]
            callback = menu_item[2]
            shortcut = menu_item[3]
            handler = YaCoHandler(self, callback)
            action = idaapi.action_desc_t(name, text, handler, shortcut, "")
            idaapi.register_action(action)
            idaapi.attach_action_to_menu("Edit/YaTools/", name,
                                         idaapi.SETMENU_APP)

        if PROFILE_YACO_LOADING:
            self.pr.disable()
            f = open("yaco-loading.profile", 'w')
            ps = pstats.Stats(self.pr, stream=f).sort_stats('time')
            ps.print_stats()
            f.close()
Пример #2
0
def FunctionAppendChunk(function_address, A, B_ex):
    # CAVEAT this function also adds successor hanging instructions!
    if idaapi.get_func(A) is not None:
        fn_print("0x%x-0x%x already in function" % (A, B_ex))
        return False

    fn_print("append chunk 0x%x-0x%x to function 0x%x" %
             (A, B_ex, function_address))

    # watch out with hanging instructions
    if (idaapi.get_func(A) is None) and (idaapi.get_func(idc.PrevHead(B_ex))
                                         is not None):
        fn_print("chunk 0x%x-0x%x is part hanging, only moving hanging part" %
                 (A, B_ex))
        B_ex = A
        while idaapi.get_func(B_ex) is None:
            B_ex = idc.NextHead(B_ex)
        fn_print("  ... instead moving 0x%x-0x%x" % (A, B_ex))

    result = idc.AppendFchunk(function_address, A, B_ex)
    if do_wait:
        idc.Wait()

    fn_print("append-chunk 0x%x-0x%x to 0x%x: %d" %
             (A, B_ex, function_address, result))

    if result:
        now_address = idc.GetFunctionAttr(A, idc.FUNCATTR_START)
        f2 = idc.GetFunctionAttr(function_address, idc.FUNCATTR_START)
        assert f2 == now_address, "0x%x/0x%x/0x%x" % (function_address,
                                                      now_address, f2)
    return result
Пример #3
0
def FunctionRemoveChunk(any_ins_in_chunk):
    chunk_function = idc.GetFunctionAttr(any_ins_in_chunk, idc.FUNCATTR_START)
    result = idc.RemoveFchunk(chunk_function, any_ins_in_chunk)
    if do_wait:
        idc.Wait()
    fn_print("remove-chunk 0x%x: %d" % (any_ins_in_chunk, result))
    return result
    def go(self):
        idaapi.set_processor_type("arm", idc.SETPROC_ALL | idc.SETPROC_FATAL)
        inf = idaapi.get_inf_structure()
        inf.af &= ~idc.AF_MARKCODE  # this is so that IDA does not find functions inside .data segments
        inf.af2 &= ~idc.AF2_FTAIL  # don't create function tails
        inf.af2 |= idc.AF2_PURDAT  # control flow to data segment is ignored

        print "0) Loading NIDs"
        self.load_nids()

        print "1) Mapping kernel VA"
        self.dump_first_level()

        print "2) Finding module table using heuristic"
        self.find_module_ptr()

        print "3) Creating segments"
        self.process_chunks()

        print "4) Resolving imports/exports"
        self.resolve_impexp()

        print "5) Waiting for IDA to analyze the program, this will take a while..."
        idc.Wait()

        print "6) Analyzing system instructions"
        from highlight_arm_system_insn import run_script
        run_script()

        print "7) Adding MOVT/MOVW pair xrefs"
        add_xrefs()
Пример #5
0
    def request(self, service, output):
        if service not in self.services:
            raise ServiceIsNotRegistered(service)

        idc.Wait()
        with open(output, 'w') as out:
            self.services[service](out)
        idc.Exit(0)
Пример #6
0
def wait_until_ready():
    '''
        first thing you should wait until IDA has parsed
        the executable.
    '''
    print "[+] Waiting for auto-analysis to finish..."
    # wait for the autoanalysis to finish
    idc.Wait()
Пример #7
0
def main():
    idc.Wait()
    if autoIsOk():
        classes = run_msvc()
        print classes
    else:
        print "Take it easy, man"
    print "Done"
    idc.Exit(0)
Пример #8
0
    def go(self):
        print "0) Building NID cache..."
        self.load_nids()

        # Vita is ARM
        idaapi.set_processor_type("arm",
                                  idaapi.SETPROC_ALL | idaapi.SETPROC_FATAL)

        print "1) Loading ELF segments"
        self.fin.seek(0)
        header = ELFHeader(self.fin.read(0x34))

        self.fin.seek(header.e_phoff)
        phdrs = [
            ELFphdr(self.fin.read(header.e_phentsize))
            for _ in xrange(header.e_phnum)
        ]

        for phdr in phdrs:
            if phdr.p_type == p_type.PT_LOAD:
                idaapi.add_segm(0, phdr.p_vaddr, phdr.p_vaddr + phdr.p_memsz,
                                ".text" if phdr.x else ".data",
                                "CODE" if phdr.x else "DATA")
                self.fin.file2base(phdr.p_offset, phdr.p_vaddr,
                                   phdr.p_vaddr + phdr.p_filesz, 1)

        self.seg0_off = phdrs[0].p_offset
        self.seg0_va = phdrs[0].p_vaddr

        self.fin.seek(self.seg0_off + header.e_entry)
        modinfo = Modinfo(self.fin.read(0x34))

        print "2) Doing noreturn functions first"
        self.parse_impexp(modinfo.export_top, modinfo.export_end, Modexport,
                          self.cb_noret)
        self.parse_impexp(modinfo.import_top, modinfo.import_end, Modimport,
                          self.cb_noret)

        print "3) Parsing export tables"
        self.parse_impexp(modinfo.export_top, modinfo.export_end, Modexport,
                          self.cb_exp)

        print "4) Parsing import tables"
        self.parse_impexp(modinfo.import_top, modinfo.import_end, Modimport,
                          self.cb_imp)

        print "5) Waiting for IDA to analyze the program"
        idc.Wait()

        print "6) Analyzing system instructions"
        from highlight_arm_system_insn import run_script
        run_script()

        print "6) Adding MOVT/MOVW pair xrefs"
        add_xrefs()
Пример #9
0
def init(tests):
    # workaround ida 6.95 function chunks which should really be functions
    for ea in [0x6718f260, 0x671a5250]:
        numrefs = idc.GetFchunkAttr(ea, idc.FUNCATTR_REFQTY)
        if numrefs <= 1:
            continue
        for idx in range(numrefs, 0, -1):
            idc.RemoveFchunk(idc.GetFchunkReferer(ea, idx - 1), ea)
        idc.MakeFunction(ea)
    idc.Wait()
    YaCo.start_tests()
Пример #10
0
    def pre_hook(self):
        self.unhook()
        hooks.idb.unhook()

        idc.SetCharPrm(idc.INF_AUTO, True)
        idc.Wait()
        idaapi.request_refresh(idaapi.IWID_STRUCTS | idaapi.IWID_ENUMS | idaapi.IWID_XREFS)
        idc.SetCharPrm(idc.INF_AUTO, False)
        idaapi.request_refresh(idaapi.IWID_STRUCTS | idaapi.IWID_ENUMS | idaapi.IWID_XREFS)

        self.hook()
        hooks.idb.hook()
Пример #11
0
 def makeFuncsFromPreamble(funcpreamble, startea=idc.FirstSeg(), endea = idaapi.BADADDR):
     """ This method makes functions everywhere that the sequence 'funpreamble' is found.
         NOTE: this method is generally unsafe, because it will attempt to make functions where
         there may be no function.  Use it with caution.
     """
     ea = startea
     i = 0
     while (ea != idaapi.BADADDR and ea < endea):
         ea = idc.FindBinary(ea, SEARCH_DOWN, funcpreamble)
         idc.MakeFunction(ea)
         idc.Wait()
         ea = ea + 1 # idc.FindBinary(ea) returns ea if ea matches, silly
Пример #12
0
def find_sscanf_vulns():
    idc.Wait()
    sscanf = idc.LocByName('_sscanf')
    if sscanf == idc.BADADDR:
        print("sscanf not found")
        return

    for caller in idautils.CodeRefsTo(sscanf, False):
        process_sscanf_callers(caller, sscanf)

    if ida_kernwin.cvar.batch:
        idc.Exit(0)
Пример #13
0
    def pre_hook(self):
        self.unhook()
        hooks.idb.unhook()

        idc.set_inf_attr(idc.INFFL_AUTO, True)
        idc.Wait()
        idaapi.request_refresh(idaapi.IWID_STRUCTS | idaapi.IWID_ENUMS
                               | idaapi.IWID_XREFS)
        idc.set_inf_attr(idc.INFFL_AUTO, False)
        idaapi.request_refresh(idaapi.IWID_STRUCTS | idaapi.IWID_ENUMS
                               | idaapi.IWID_XREFS)

        self.hook()
        hooks.idb.hook()
Пример #14
0
def _convert_address_to_function(func):
    """Convert an address that IDA has classified incorrectly into a proper function."""
    # If everything goes wrong, we'll try to restore this function.
    orig = idc.FirstFuncFchunk(func)
    # If the address is not code, let's undefine whatever it is.
    if not idc.isCode(idc.GetFlags(func)):
        if not is_mapped(func):
            # Well, that's awkward.
            return False
        item = idc.ItemHead(func)
        itemend = idc.ItemEnd(func)
        if item != idc.BADADDR:
            _log(1, 'Undefining item {:#x} - {:#x}', item, itemend)
            idc.MakeUnkn(item, idc.DOUNK_EXPAND)
            idc.MakeCode(func)
            # Give IDA a chance to analyze the new code or else we won't be able to create a
            # function.
            idc.Wait()
            idc.AnalyseArea(item, itemend)
    else:
        # Just try removing the chunk from its current function. IDA can add it to another function
        # automatically, so make sure it's removed from all functions by doing it in loop until it
        # fails.
        for i in range(1024):
            if not idc.RemoveFchunk(func, func):
                break
    # Now try making a function.
    if idc.MakeFunction(func) != 0:
        return True
    # This is a stubborn chunk. Try recording the list of chunks, deleting the original function,
    # creating the new function, then re-creating the original function.
    if orig != idc.BADADDR:
        chunks = list(idautils.Chunks(orig))
        if idc.DelFunction(orig) != 0:
            # Ok, now let's create the new function, and recreate the original.
            if idc.MakeFunction(func) != 0:
                if idc.MakeFunction(orig) != 0:
                    # Ok, so we created the functions! Now, if any of the original chunks are not
                    # contained in a function, we'll abort and undo.
                    if all(idaapi.get_func(start) for start, end in chunks):
                        return True
            # Try to undo the damage.
            for start, _ in chunks:
                idc.DelFunction(start)
    # Everything we've tried so far has failed. If there was originally a function, try to restore
    # it.
    if orig != idc.BADADDR:
        _log(0, 'Trying to restore original function {:#x}', orig)
        idc.MakeFunction(orig)
    return False
Пример #15
0
def main():
    global WINHE_RESULTS_DIR
    print "Start analysis"
    idc.Wait()  #wait while ida finish analysis
    DEPTH_LEVEL = os.getenv('DEPTH_LEVEL')
    auto_mode = 0
    # set WINHE_RESULTS_DIR variable in the cmd in case if you want to run IDA in the
    # silent mode.
    WINHE_RESULTS_DIR = os.getenv('WINHE_RESULTS_DIR')
    if WINHE_RESULTS_DIR == None:
        WINHE_RESULTS_DIR = os.getcwd()
    else:
        auto_mode = 1
    print "saving results in ", WINHE_RESULTS_DIR
    init_analysis()
    if auto_mode == 1:
        Exit(0)
Пример #16
0
def main():
    idc.Wait()  
    print ["Check begin-----------------------------------------------------------------"]
    file_type = idaapi.get_file_type_name()
    print "It's",[file_type],"file."
    danger_func_check()
    #iOS_file = ["Fat Mach-O file, 1. ARMv7","Fat Mach-O file, 2. ARM64","Mach-O file (EXECUTE). ARM64","Mach-O file (EXECUTE). ARMv7","Mach-O file (EXECUTE). ARM","Mach-O file (EXECUTE). ARMv7s","Mach-O file (EXECUTE). ARMv6"]
    #Android_so_file = []
    if ("Mach-O file" in file_type) and ("ARM" in file_type):
        iOS_check()
    if "PE" in file_type:
        CreateProcessAsUserW_check()
    #if file_type in Android_so_file:
        #Android_so_check()
    strcpy_buffer_check()
    print "-----------------------------------------------------------------"
    print ["Check over-----------------------------------------------------------------"]
    idc.Exit(0)  
Пример #17
0
    def update(self):
        memory_exporter = ya.MakeModel()

        modified_files = self.repo_manager.update_cache()
        ya.MakeXmlFilesDatabaseModel(modified_files).accept(
            memory_exporter.visitor)

        logger.debug("unhook")
        self.ida_hooks.unhook()

        logger.debug("export mem->ida")
        ya.export_to_ida(memory_exporter.model, self.hash_provider)

        idc.set_inf_attr(idc.INFFL_AUTO, True)
        idc.Wait()
        idc.set_inf_attr(idc.INFFL_AUTO, False)
        idc.Refresh()
        logger.debug("hook")
        self.ida_hooks.hook()
Пример #18
0
def main():
    print "Start metrics calculation"
    idc.Wait()  #wait while ida finish analysis
    if os.getenv('IDAPYTHON') != 'auto':
        name = AskFile(1, "*.*", "Where is a file with libcalls?")
        subcalls_mode = 0  #AskYN(1,("HIDECANCEL\nDo you want to instrument subcalls in the routines?\n"))
        if subcalls_mode == -1:
            print "Terminated"
            return 0
        init_analysis(name, subcalls_mode, MANUAL)
        print "done"
        return 0
    #else: #hidden mode
    #todo: get flag (instrument or don't instrument subcalls and where is a file with a list of libcalls)
    #init_analysis(name, subcalls_mode, SILENT)

    if os.getenv('IDAPYTHON') == 'auto':
        Exit(0)
    return 1
Пример #19
0
    def update(self):
        # pydevd.settrace()
        logger.debug("Yaco.update()")
        (modified_object_ids_str, deleted_object_ids_str, modified_files,
         _deleted_files) = self.repo_manager.update_cache()
        modified_object_ids = []
        deleted_object_ids = []
        for obj_id in modified_object_ids_str:
            modified_object_ids.append(ya.YaToolObjectId_From_String(obj_id))

        for obj_id in deleted_object_ids_str:
            deleted_object_ids.append(ya.YaToolObjectId_From_String(obj_id))

        logger.debug("delete objects")
        # fixme do something

        logger.debug("invalidate objects")
        # fixme do something

        logger.debug("loading XML")
        logger.debug("modified files : %r", modified_files)

        memory_exporter = ya.MakeModel()

        logger.debug("exporting XML to memory")
        ya.MakeXmlFilesDatabaseModel(modified_files).accept(
            memory_exporter.visitor)

        logger.debug("unhook")
        self.ida_hooks.unhook()

        logger.debug("export mem->ida")
        ya.export_to_ida(memory_exporter.model, self.hash_provider,
                         ya.UseFrames)

        idc.SetCharPrm(idc.INF_AUTO, True)
        idc.Wait()
        idc.SetCharPrm(idc.INF_AUTO, False)
        idc.Refresh()
        logger.debug("hook")
        self.ida_hooks.hook()
Пример #20
0
 def run(self, *args, **kwargs):
     try:
         print("YaCo: waiting for auto analysis to finish\n")
         idc.Wait()
         print("YaCo: saving base in current state\n")
         idc.SaveBase("")
         import_yaco_paths()
         import YaCo
         if not YaCo.start():
             idc.Warning("YaCo: already started")
     except Exception, e:
         print("YaCo: error during run")
         print(traceback.format_exc())
         logger = logging.getLogger("YaCo")
         if logger is not None:
             try:
                 logger.error("YaCo: error during run")
                 logger.error(traceback.format_exc())
             except:
                 pass
         raise e
Пример #21
0
def main():
    global DEPTH_LEVEL, WINHE_RESULTS_DIR
    print "Start analysis"
    idc.Wait()  #wait while ida finish analysis
    DEPTH_LEVEL = os.getenv('DEPTH_LEVEL')
    auto_mode = 0
    if DEPTH_LEVEL == None:
        DEPTH_LEVEL = 1  #default DEPTH_LEVEL
    else:
        DEPTH_LEVEL = int(DEPTH_LEVEL)
        auto_mode = 1
    # set WINHE_RESULTS_DIR variable in the cmd in case if you want to run IDA in the
    # silent mode.
    WINHE_RESULTS_DIR = os.getenv('WINHE_RESULTS_DIR')
    if WINHE_RESULTS_DIR == None:
        WINHE_RESULTS_DIR = os.getcwd()
    print "saving results in ", WINHE_RESULTS_DIR
    print "depth level = ", DEPTH_LEVEL
    init_analysis()
    if auto_mode == 1:
        Exit(0)
Пример #22
0
def MbrLoader():
    """ 
    This small routine loads the MBR into IDA
    It acts as a custom file loader (written with a script)
    """
    import idaapi;
    import idc;

    global SECTOR_SIZE, BOOT_START, BOOT_SIZE, BOOT_END, SECTOR2, MBRNAME

    # wait till end of analysis
    idc.Wait()

    # adjust segment
    idc.SetSegBounds(BOOT_START, BOOT_START, BOOT_START + BOOT_SIZE, idaapi.SEGMOD_KEEP)

    # load the rest of the MBR
    idc.loadfile(MBRNAME, SECTOR_SIZE, SECTOR2, SECTOR_SIZE)

    # Make code
    idc.AnalyzeArea(BOOT_START, BOOT_END)
Пример #23
0
    def make_stackframe(self, object_version, address):
        object_id = object_version.get_id()
        parent_object_id = object_version.get_parent_object_id()
        # associate stack frame id to function id
        self.stackframes_functions[object_id] = parent_object_id

        # association stackframe id to internal struc id
        eaFunc = object_version.get_object_address()
        logger.debug("stackframe[%s] : address of function is 0x%08X" %
                     (self.hash_provider.hash_to_string(object_id), eaFunc))

        attributes = object_version.get_attributes()
        stack_lvars = None
        stack_regvars = None
        stack_args = None
        try:
            stack_lvars = self.yatools.hex_string_to_address(
                attributes["stack_lvars"])
            stack_regvars = self.yatools.hex_string_to_address(
                attributes["stack_regvars"])
            stack_args = self.yatools.hex_string_to_address(
                attributes["stack_args"])
        except KeyError:
            logger.warning("Stackframe at %s has missing attribute" %
                           self.yatools.address_to_hex_string(eaFunc))

        stack_frame = idaapi.get_frame(eaFunc)
        if stack_frame is None:
            logger.error(
                "No function found for stackframe[%s] at 0x%08X" %
                (self.hash_provider.hash_to_string(object_id), eaFunc))
            self.analyze_function(eaFunc)
            stack_frame = idaapi.get_frame(eaFunc)

        if stack_frame is None:
            logger.error(
                "No function found for stackframe[%s] at 0x%08X after reanalysis"
                % (self.hash_provider.hash_to_string(object_id), eaFunc))
            idc.SetCharPrm(idc.INF_AUTO, 1)
            idc.Wait()
            idc.SetCharPrm(idc.INF_AUTO, 0)
            stack_frame = idaapi.get_frame(eaFunc)

        if stack_frame is None:
            logger.error(
                "No function found for stackframe[%s] at 0x%08X after full reanalysis"
                % (self.hash_provider.hash_to_string(object_id), eaFunc))
            idc.MakeFrame(eaFunc, stack_lvars, stack_regvars, stack_args)
            stack_frame = idaapi.get_frame(eaFunc)

        if stack_frame is None:
            logger.error(
                "No function found for stackframe[%s] at 0x%08X after idc.MakeFrame"
                % (self.hash_provider.hash_to_string(object_id), eaFunc))
        else:
            self.struc_ids[object_id] = stack_frame.id
            _yatools_ida_exporter.set_struct_id(object_id, stack_frame.id)
            stack_lvars = None
            try:
                stack_lvars = self.yatools.hex_string_to_address(
                    object_version.get_attributes()["stack_lvars"])
            except KeyError:
                logger.warning(
                    "Stackframe at %s has no stack_lvars attribute" %
                    self.yatools.address_to_hex_string(eaFunc))

            if stack_lvars is not None:
                logger.debug(
                    "Clearing everything for stackframe at 0x%08X, with stack_lvars=0x%04X",
                    eaFunc, stack_lvars)
                self.clear_struc_fields(
                    stack_frame.id,
                    object_version.get_size(),
                    object_version.get_xrefed_id_map().iterkeys(),
                    member_type=ya.OBJECT_TYPE_STACKFRAME_MEMBER,
                    name_offset=stack_lvars)
Пример #24
0
 def autoanalyze():
     print 'Waiting for IDA autoanalysis...'
     idc.Wait()
Пример #25
0
    output_file = open(info_filename,'w')        
    asm_file = open(asm_filename,'r')
    asmplus_file = open(asm_filename,'r')
    
    funcs = idautils.Functions()
    funcs_iterator = idautils.Functions()
    
    # scan all functions to extract number of functions and add them to the funcs_id
    for i in funcs_iterator:
        func_name = GetFunctionName(i)
        funcs_id.update({func_name:func_id})
        func_num += 1
        func_id += 1
        cg_adjmat.append([])
        
    for f in funcs:        
        func_name = GetFunctionName(f)              
        function_extract(output_file, f, cg_adjmat, funcs_id, callees, asm_filename) # extract functions data
        BB_extract(output_file, f, asmplus_filename) # extract basic blocks data, CFG and CFG adjacency matrices                                

    cg_extract(output_file, cg_adjmat, funcs_id, callees, func_num) # extract CG and CG adjacency matrix

        
# end of controller
#------------------------------------------------------------------------------------------------------------------------      

q = None
f = None
idc.Wait()
controller()
Пример #26
0
    def make_data(self, object_version, address):
        size = 0
        try:
            size = object_version.get_size()
        except KeyError:
            pass
        flags = None
        try:
            flags = object_version.get_object_flags()
        except KeyError:
            pass

        if size == 0:
            idc.MakeUnkn(address, idc.DOUNK_EXPAND)
        else:
            if flags is not None:
                if idc.isASCII(flags):
                    try:
                        str_type = object_version.get_string_type()
                        YaToolIDATools.check_and_set_str_type(str_type)
                    except KeyError:
                        pass
                    idc.MakeStr(address, address + size)
                    idc.SetFlags(address, flags)

                if idc.isStruct(flags):
                    found = False
                    for xref_offset_operand, xref_id_attr in object_version.get_xrefed_id_map(
                    ).iteritems():
                        (xref_offset, xref_operand) = xref_offset_operand
                        for xref_hash, xref_attrs in xref_id_attr:

                            if xref_hash in self.struc_ids:
                                struc_id = self.struc_ids[xref_hash]
                                if DEBUG_EXPORTER:
                                    logger.debug(
                                        "making unknown from 0x%08X to 0x%08X"
                                        % (address, address + size))
                                idaapi.do_unknown_range(
                                    address, size, idc.DOUNK_DELNAMES)

                                #   idc.MakeUnkn(address, DOUNK_SIMPLE | idc.DOUNK_DELNAMES)
                                #   for i in xrange(1, size):
                                #       MakeName(address + i, "")
                                #       idc.MakeUnkn(address + i, DOUNK_SIMPLE | idc.DOUNK_DELNAMES)
                                # idc.MakeStructEx uses idaapi.doStruct (but asks for name while
                                # we already have the struc id)
                                if DEBUG_EXPORTER:
                                    logger.debug(
                                        "Making struc at %s : %s (sizeof(%s)=0x%08X, size=0x%08X, flags=0x%08X"
                                        % (self.yatools.address_to_hex_string(
                                            address),
                                           self.yatools.address_to_hex_string(
                                               struc_id),
                                           idaapi.get_struc_name(struc_id),
                                           idc.GetStrucSize(struc_id), size,
                                           flags))
                                idc.SetCharPrm(idc.INF_AUTO, True)
                                idc.Wait()
                                if idaapi.doStruct(address, size,
                                                   struc_id) == 0:
                                    if DEBUG_EXPORTER:
                                        logger.warning("Making struc failed")
                                idc.SetCharPrm(idc.INF_AUTO, False)
                                #                                     idc.SetFlags(address, flags)
                                found = True
                    else:
                        logger.error(
                            "bad struc flags : idc.isStruct is true but no xref available for object %s"
                            % self.hash_provider.hash_to_string(
                                object_version.get_id()))
                    if not found:
                        logger.error(
                            "bad struc flags : idc.isStruct is true "
                            "but no struc available for object %s (%s)" %
                            (self.hash_provider.hash_to_string(
                                object_version.get_id()),
                             object_version.get_name()))
                else:
                    idc.MakeData(address, flags & (idc.DT_TYPE | idc.MS_0TYPE),
                                 size, 0)

            else:
                idc.MakeData(address, idc.FF_BYTE, size, 0)

        self.make_name(object_version, address, False)

        self.set_type(object_version, address)
Пример #27
0
def dump_exp_gadgets():
    import gadget
    exp_gadgets = gadget.find_exp_gadgets()
    with open("%s.payload.gadgets" % get_input_file_path(), "wb") as f:
        pickle.dump(exp_gadgets, f)
    return 

def load_exp_gadgets(dump_file):
    with open(dump_file, "rb") as f:
        exp_gadgets = pickle.load(f)
    return exp_gadgets

def disasm(ea):
    return idc.GetDisasm(ea)
"""

if __name__ == "__main__":
    import sys
    sys.setrecursionlimit(40000)
    idc.Wait()  # Wait for IDA to complete its auto analysis
    print '-------- DUMP start -----------'
    dump_data()
    print '-------- DUMP end -----------'
    '''
    (all_blocks, all_opcodes) = load_codes_blocks(target_file)
    show_blocks(all_blocks)
    print all_opcodes
    '''
    idc.Exit(0)  # Exit IDA when done;
Пример #28
0
 def autoanalyze():
     idc.Wait()
Пример #29
0
	def run(self, arg):
		global MKBundleManagerInstance
		idc.Wait()
		MKBundleManagerInstance.Show_BundledAssemblyManagerView()
Пример #30
0
    def go(self):
        print "0) Building cache..."
        self.load_nids()

        # Vita is ARM
        idaapi.set_processor_type("arm", idaapi.SETPROC_ALL | idaapi.SETPROC_FATAL)
        
        # Set compiler info
        cinfo = idaapi.compiler_info_t()
        cinfo.id = idaapi.COMP_GNU
        cinfo.cm = idaapi.CM_CC_CDECL | idaapi.CM_N32_F48
        cinfo.size_s = 2
        cinfo.size_i = cinfo.size_b = cinfo.size_e = cinfo.size_l = cinfo.defalign = 4
        cinfo.size_ll = cinfo.size_ldbl = 8
        idaapi.set_compiler(cinfo, 0)

        # Import types
        self.import_types()
        self.load_proto()

        print "1) Loading ELF segments"
        self.fin.seek(0)
        header = Ehdr(self.fin.read(Ehdr.SIZE))

        self.fin.seek(header.e_phoff)
        phdrs = [Phdr(self.fin.read(header.e_phentsize)) for _ in xrange(header.e_phnum)]
        phdr_text = phdrs[0]

        for phdr in phdrs:
            if phdr.p_type == Phdr.PT_LOAD:
                idaapi.add_segm(0, phdr.p_vaddr, phdr.p_vaddr + phdr.p_memsz,
                                ".text" if phdr.x else ".data",
                                "CODE" if phdr.x else "DATA")
                seg = idaapi.getseg(phdr.p_vaddr)
                if phdr.x:
                    seg.perm = idaapi.SEGPERM_EXEC | idaapi.SEGPERM_READ
                    phdr_text = phdr
                else:
                    seg.perm = idaapi.SEGPERM_READ | idaapi.SEGPERM_WRITE
                self.fin.file2base(phdr.p_offset, phdr.p_vaddr, phdr.p_vaddr + phdr.p_filesz, 1)

        if header.e_type == Ehdr.ET_SCE_EXEC:
            self.phdr_modinfo = phdr_text
            modinfo_off = phdr_text.p_offset + header.e_entry
        else:
            self.phdr_modinfo = phdrs[(header.e_entry & (0b11 << 30)) >> 30]
            modinfo_off = self.phdr_modinfo.p_offset + (header.e_entry & 0x3FFFFFFF)

        self.fin.seek(modinfo_off)
        modinfo = SceModuleInfo(self.fin.read(SceModuleInfo.SIZE))
        modinfo_ea = idaapi.get_fileregion_ea(modinfo_off)
        apply_struct(modinfo_ea, SceModuleInfo._find_or_create_struct())
        
        print ""
        print "   Module:  " + str(modinfo.name)
        print "   NID:     0x{:08X}".format(modinfo.nid)
        print ""

        print "2) Parsing export tables"
        self.parse_impexp(modinfo.export_top, modinfo.export_end, SceModuleExports, self.cb_exp)

        print "3) Parsing import tables"
        self.parse_impexp(modinfo.import_top, modinfo.import_end, SceModuleImports, self.cb_imp)

        print "4) Waiting for IDA to analyze the program"
        idc.Wait()

        print "5) Analyzing system instructions"
        from highlight_arm_system_insn import run_script
        run_script()

        print "6) Adding MOVT/MOVW pair xrefs"
        add_xrefs()