Example #1
0
 def analyze_function(self, address):
     chunks = YaToolIDATools.get_function_chunks(address)
     for (ch_start, ch_end) in chunks:
         if idc.AnalyzeArea(ch_start, ch_end) != 1:
             logger.error(
                 "[0x%08X] idc.AnalyzeArea failed [0x%08X->0x%08X" %
                 (address, ch_start, ch_end))
Example #2
0
    def make_function(self, object_version, address):
        #
        # call the architecture dependent plugin  ###########
        #
        self.arch_plugin.make_function_prehook(object_version, address)

        flags = object_version.get_object_flags()
        size = object_version.get_size()
        # create function if not already exist

        current_flags = idc.GetFlags(address)
        # if ea is func
        func = idaapi.get_func(address)
        if not idaapi.isFunc(current_flags) or (func is not None and
                                                (func.startEA != address)):
            logger.debug(
                "MakeFunction at 0x%08X : flags=0x%08X, current_flags=0x%08X" %
                (address, flags, current_flags))

            if func is not None:
                logger.debug(
                    "                                       "
                    "func.startEA[0x%08X]!=address func.endEA[0x%08X]!=(address+size[0x%08X])  "
                    % (func.startEA, func.endEA, size))
            if not idc.MakeFunction(address):
                if not idc.isLoaded(address):
                    logger.error(
                        "Failed at idc.MakeFunction at 0x%08X : data not loaded"
                        % address)
                else:
                    logger.error("Failed at idc.MakeFunction at 0x%08X" %
                                 address)
                    self.clear_function(object_version, address)
                    if not idc.MakeFunction(address):
                        logger.error("Failed at idc.MakeFunction at 0x%08X" %
                                     address)

                        #             idc.MakeUnknown(address, size, DOUNK_SIMPLE)
            if idc.AnalyzeArea(address, address + 1) != 1:
                logger.error("[0x%08X] idc.AnalyzeArea failed" % address)

                #             if(idc.AnalyzeArea(address, address+size) != 1):
                #                 logger.error("[0x%08X] idc.AnalyzeArea failed" % address)
                #             if(address == 0x0000000000411558):
                #                 raise Exception()
        if flags is not None:
            idc.SetFunctionFlags(address, flags)

        self.set_type(object_version, address)

        #
        # call the architecture dependent plugin  ###########
        #
        self.arch_plugin.make_function_posthook(object_version, address)
Example #3
0
def analyze_area(start_ea, end_ea):
    """
    Analyze a code area while debugging
    @param start_ea: Area start address
    @param end_ea:  Area end address
    @return: True if area successfully analyzed, otherwise False.
    """
    #TODO: Check with hex-rays why is it necessary to refresh memory.
    refresh_debugger_memory()

    if idc.AnalyzeArea(start_ea, end_ea) != 1:
        return False

    return True
Example #4
0
def try_make_function(function_start, function_end=idc.BADADDR, target_location=None, require_term=True,
                      end_mnem_bytes=None):
    """
    Description:
        Given a function location, attempt to create a function.
        If function creation fails, delete any partially created functions.
        If function creation succeeds, ensure all of the function's bytes are analyzed as code.

    Input:
        function_start - The startEA of the function to create
        function_end - The endEA of the function to create. IDA will calculate if not provided.
        target_location - If provided, fail function creation if it does not include this EA
        require_term - If provided, fail function creation if the last instruction is not a ret or jmp
        end_mnem_bytes - If provided, fail function creation if the last instruction is not the provided bytes
                         Instructions are entered as space separated bytes (i.e. '55' for 'push ebp')

    Output:
        Returns a tuple (function_start, function_end) for the created function if successful, None otherwise
    """
    if function_start <= function_end:
        if idc.MakeFunction(function_start, function_end):
            append_debug('Created a function 0x%X - 0x%X.' % (function_start, function_end))
            if require_term:
                last_mnem_ea = idc.ItemHead(idaapi.get_func(function_start).endEA - 1)
                last_mnem = idc.GetMnem(last_mnem_ea)
                if (end_mnem_bytes is None and 'ret' not in last_mnem and 'jmp' not in last_mnem) or \
                        (end_mnem_bytes and idaapi.get_many_bytes(last_mnem_ea, idc.ItemSize(last_mnem_ea)).encode('hex').upper() != end_mnem_bytes.upper()):
                    idc.DelFunction(function_start)
                    append_debug(
                        'Deleted function at 0x%X - the function didn\'t end with the correct mnem/bytes.' % function_start)
                    return
            if target_location is not None:
                if function_start <= target_location < idaapi.get_func(function_start).endEA:
                    idc.AnalyzeArea(function_start, idaapi.get_func(function_start).endEA)
                    return function_start, function_end
                else:
                    idc.DelFunction(function_start)
                    append_debug(
                        'Deleted function at 0x%X - the function didn\'t contain the target location.' % function_start)
                    return
        else:
            append_debug(
                'Tried to create a function 0x%X - 0x%X, but IDA wouldn\'t do it.' % (function_start, function_end))
    else:
        append_debug('The end address was not greater than the start address!')
Example #5
0
def main():
    base_addr = 0
    ea = 0
    idc.MakeFunction(ea)

    # heuristic
    while (true):
        mnemonic = idc.GetMnem(ea)

        if "LDR" in mnemonic:
            base_str = idc.GetOpnd(ea, 1)
            base_addr = int(base_str.split("=")[1], 16)

            break

        ea += 4

    print("[+] rebasing to address 0x%x" % (base_addr))
    idc.rebase_program(base_addr, idc.MSF_FIXONCE)
    idaapi.autoWait()

    segment_start = base_addr
    segment_end = idc.GetSegmentAttr(segment_start, idc.SEGATTR_END)

    ea = segment_start

    print("[+] searching and defining functions")

    while ea != idc.BADADDR:
        ea = idc.FindBinary(ea, idc.SEARCH_DOWN, "BF A9", 16)

        if ea != idc.BADADDR:
            ea = ea - 2

            if (ea % 4) == 0 and idc.GetFlags(ea) < 0x200:
                # print("[+] defining a function at 0x%x" % (ea))
                idc.MakeFunction(ea)

            ea = ea + 4

    idc.AnalyzeArea(segment_start, segment_end)
    idaapi.autoWait()
Example #6
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)
Example #7
0
def make_code_rec(ea, visited, magic_lodsb):

    #print "rec"
    while True:

        if was_visited(ea, visited):
            break

        if ea == magic_lodsb:
            break

        visit(ea, visited)

        old_op = idc.GetOpnd(ea, 0)
        if not isCode(GetFlags(ea)):
            n = 6
            undefBytes(ea, n)
            i = 0
            while i < n:
                r = idc.MakeCode(ea + i)
                if r == 0:
                    break
                i += r
            idc.AnalyzeArea(ea, ea + n)

        OpHex(ea, -1)

        if is_jxx(ea):
            jmp_ea = jxx_target(ea)
            if is_jmp(ea):
                ea = jmp_ea
                continue
            else:
                make_code_rec(jmp_ea, visited, magic_lodsb)
                #false branch will be taken below

        nea = NextNotTail(ea)
        ea = nea
Example #8
0
def load_file(fd, neflags, format):
    size = 0
    base_addr = 0
    ea = 0

    idaapi.set_processor_type("arm", idaapi.SETPROC_ALL)
    idaapi.get_inf_structure().lflags |= idaapi.LFLG_64BIT

    if (neflags & idaapi.NEF_RELOAD) != 0:
        return 1

    fd.seek(0, idaapi.SEEK_END)
    size = fd.tell()

    segm = idaapi.segment_t()
    segm.bitness = 2  # 64-bit
    segm.start_ea = 0
    segm.end_ea = size
    idaapi.add_segm_ex(segm, "iBoot", "CODE", idaapi.ADDSEG_OR_DIE)

    fd.seek(0)
    fd.file2base(0, 0, size, false)

    idaapi.add_entry(0, 0, "start", 1)
    idc.MakeFunction(ea)

    print("[+] Marked as code")

    # heuristic
    while (true):
        mnemonic = idc.GetMnem(ea)

        if "LDR" in mnemonic:
            base_str = idc.GetOpnd(ea, 1)
            base_addr = int(base_str.split("=")[1], 16)

            break

        ea += 4

    print("[+] Rebasing to address 0x%x" % (base_addr))
    idaapi.rebase_program(base_addr, idc.MSF_NOFIX)
    idaapi.autoWait()

    segment_start = base_addr
    segment_end = idc.GetSegmentAttr(segment_start, idc.SEGATTR_END)

    ea = segment_start

    print("[+] Searching and defining functions")

    while ea != idc.BADADDR:
        ea = idc.FindBinary(ea, idc.SEARCH_DOWN, "BF A9", 16)

        if ea != idc.BADADDR:
            ea = ea - 2

            if (ea % 4) == 0 and idc.GetFlags(ea) < 0x200:
                # print("[+] Defining a function at 0x%x" % (ea))
                idc.MakeFunction(ea)

            ea = ea + 4

    idc.AnalyzeArea(segment_start, segment_end)
    idaapi.autoWait()

    return 1


# EOF
Example #9
0
 def run(self):
     try:
         logger.debug('Starting up')
         dlg = StructTyperWidget()
         dlg.setStructs(loadStructs())
         oldTo = idaapi.set_script_timeout(0)
         res = dlg.exec_()
         idaapi.set_script_timeout(oldTo)
         if res == QtWidgets.QDialog.Accepted:
             regPrefix = dlg.getRegPrefix()
             sid = None
             struc = None
             if dlg.ui.rb_useStackFrame.isChecked():
                 ea = idc.here()
                 if using_ida7api:
                     sid = idc.get_frame_id(ea)
                 else:
                     sid = idc.GetFrame(ea)
                 struc = idaapi.get_frame(ea)
                 logger.debug('Dialog result: accepted stack frame')
                 if (sid is None) or (sid == idc.BADADDR):
                     #i should really figure out which is the correct error case
                     raise RuntimeError(
                         'Failed to get sid for stack frame at 0x%x' % ea)
                 if (struc is None) or (struc == 0) or (struc
                                                        == idc.BADADDR):
                     raise RuntimeError(
                         'Failed to get struc_t for stack frame at 0x%x' %
                         ea)
                 if using_ida7api:
                     pass
                 else:
                     #need the actual pointer value, not the swig wrapped struc_t
                     struc = long(struc.this)
             else:
                 structName = dlg.getActiveStruct()
                 if structName is None:
                     print("No struct selected. Bailing out")
                     return
                 logger.debug('Dialog result: accepted %s "%s"',
                              type(structName), structName)
                 if using_ida7api:
                     sid = idc.get_struc_id(structName)
                 else:
                     sid = idc.GetStrucIdByName(structName)
                 if (sid is None) or (sid == idc.BADADDR):
                     #i should really figure out which is the correct error case
                     raise RuntimeError('Failed to get sid for %s' %
                                        structName)
                 tid = idaapi.get_struc_id(structName)
                 if (tid is None) or (tid == 0) or (tid == idc.BADADDR):
                     #i should really figure out which is the correct error case
                     raise RuntimeError('Failed to get tid_t for %s' %
                                        structName)
                 if using_ida7api:
                     struc = idaapi.get_struc(tid)
                 else:
                     struc = g_dll.get_struc(tid)
                 if (struc is None) or (struc == 0) or (struc
                                                        == idc.BADADDR):
                     raise RuntimeError('Failed to get struc_t for %s' %
                                        structName)
             foundMembers = self.processStruct(regPrefix, struc, sid)
             if dlg.ui.rb_useStackFrame.isChecked() and (foundMembers != 0):
                 #reanalyze current function if we're analyzing a stack frame & found some func pointers
                 if using_ida7api:
                     funcstart = idc.get_func_attr(idc.here(),
                                                   idc.FUNCATTR_START)
                     funcend = idc.get_func_attr(idc.here(),
                                                 idc.FUNCATTR_END)
                 else:
                     funcstart = idc.GetFunctionAttr(
                         idc.here(), idc.FUNCATTR_START)
                     funcend = idc.GetFunctionAttr(idc.here(),
                                                   idc.FUNCATTR_END)
                 if (funcstart != idc.BADADDR) and (funcend != idc.BADADDR):
                     if using_ida7api:
                         idc.plan_and_wait(funcstart, funcend)
                     else:
                         idc.AnalyzeArea(funcstart, funcend)
         elif res == QtWidgets.QDialog.Rejected:
             logger.info('Dialog result: canceled by user')
         else:
             logger.debug('Unknown result')
             raise RuntimeError('Dialog unknown result')
     except Exception, err:
         logger.exception("Exception caught: %s", str(err))
Example #10
0
import idc
import idaapi
import sys

idc.Wait()
if len(idc.ARGV) == 2:
    tmp_dir = idc.ARGV[1]
    for tmp_file in sorted(os.listdir(tmp_dir)):
        if tmp_file.endswith('.dmp'):
            with open("{}/{}".format(tmp_dir, tmp_file)) as f:
                data = f.read()
                start_addr = int(tmp_file.split('.')[0], 16)
                stop_addr = (start_addr + len(data)) | 0xfff
                idc.SegCreate(start_addr, stop_addr, 0, 1, 0, idaapi.scPub)
                idc.SetSegmentType(start_addr, idc.SEG_CODE)
                idaapi.put_many_bytes(start_addr, data)
    # reanalyze after adding all the new sections
    idc.AnalyzeArea(0, idc.BADADDR)
# compresses the DB
idc.SaveBase('{}.idb'.format(idc.GetInputFile()), flags=idaapi.DBFL_COMP)
idc.Exit(0)