Пример #1
0
    def OnDeleteLine(self, n):
        ans = idaapi.askyn_c(
            1,
            "HIDECANCEL\nAre you sure you want to delete function [%s] @ [%s]?"
            % (self.items[n][3], self.items[n][4]))
        if ans == 1:
            asms = Assembler.LoadSavedAssemblers()
            item = int(self.items[n][2], 16)
            if asms != None and len(asms.keys()) > 0:
                for asm in asms.itervalues():
                    if asm.functions.has_key(item):
                        print "Removed [%08x]!" % item
                        del asm.functions[item]
                        asm.SaveState()

            opty_ea = int(self.items[n][4], 16)
            print "set_name[%08x]" % opty_ea
            idc.MakeComm(opty_ea, "")
            idaapi.set_name(opty_ea, "")
            idc.DelFunction(opty_ea)

            comment = idc.Comment(item)
            comment = re.sub(r"(?i)OPTY@\[[\d+abcdef]+\];\s*", "", comment)
            idc.MakeComm(item, comment)

        self.populate_items()
        return n
Пример #2
0
    def define(ea):
        if CompleteObjectLocator.isDefined(ea):
            return
        if not CompleteObjectLocator.isValid(ea):
            raise RttiError(
                "%08X: doesn't look like a correct CompleteObjectLocator" %
                (ea))

        # Ensure referenced structs are defined.
        # An exception will be thrown if something goes wrong.
        tdPtr = idaapi.get_full_long(ea + 12)
        td = TypeDescriptor(tdPtr)
        chdPtr = idaapi.get_full_long(ea + 16)
        chd = ClassHierarchyDescriptor(chdPtr)

        strid = idaapi.get_struc_id('_s__RTTICompleteObjectLocator')
        size = idaapi.get_struc_size(strid)
        idaapi.do_unknown_range(ea, size, idaapi.DOUNK_DELNAMES)
        idaapi.doStruct(ea, size, strid)

        if chd.isMultipleInheritance:
            if chd.isVirtualInheritance:
                print '%08X: Cannot handle virtual inheritance yet.' % (ea)
            else:
                # '??_R4' + td.baseMangledName + '6B' + baseClassTd.baseMangledName + '@'
                # '??_7'  + ...
                print '%08X: Cannot handle multiple inheritance yet.' % (ea)
        else:
            idaapi.set_name(ea, '??_R4' + td.baseMangledName + '6B@', 0)
Пример #3
0
def jtool2_information():
    print("[-] Other method information construction")
    fd = open(kernelcache_path)
    data = fd.readlines()
    fd.close()

    for line in data:
        t = line[:-1].strip()
        addr = int(t.split("|")[0], 0)
        sym = t.split("|")[1]

        segName = idc.get_segm_name(addr)
        if segName != "__TEXT_EXEC:__text" or "." in sym:
            if "__DATA" in segName:
                idaapi.set_name(addr, sym, idaapi.SN_FORCE)
            continue

        if not idau.is_function_start(addr):
            print("[jtool2] Current '{}'' - [{}] is not defined as function".
                  format(sym, hex(addr)))
            if not idau.force_function(addr):
                print("[jtool2] Can't convert '{}' - [{}] to function".format(
                    sym, hex(addr)))
                continue

        curSym = idc.get_func_name(addr)
        if "sub_" in curSym:
            idaapi.set_name(addr, sym, idaapi.SN_FORCE)

    print("[-] Done")
def make_symbols(symbols_file, is_arch64, skip_absolute_symbols,
                 skip_module_symbols):
    arch_warn = True
    for symbol_line in symbols_file:
        symbol_line = symbol_line.strip()
        print(symbol_line)
        address_number, type_string, name, line_is_arch64 = parse_symbol_line(
            symbol_line)
        if arch_warn and is_arch64 != line_is_arch64:
            ignore_arch_warn = ida_kernwin.ask_buttons(
                "Yes", "No", "Cancel", -1,
                "Detected line arch is different from arch selected, maybe symbols file is corrupted, do you want ignore this kind of warning? Cancel to exit"
            )
            if ignore_arch_warn == -1:
                raise UICancel
            elif ignore_arch_warn == 1:
                arch_warn = False
        if skip_absolute_symbols and type_string == 'A':
            continue
        if skip_module_symbols and name[-1] == ']':
            continue
        idaapi.set_debug_name(address_number, name)
        idaapi.set_name(address_number, name,
                        SN_NOWARN | SN_NOCHECK | SN_PUBLIC)
    ida_kernwin.open_names_window(0)
Пример #5
0
    def define(ea):
        if BaseClassDescriptor.isDefined(ea):
            return

        td = TypeDescriptor(BaseClassDescriptor.__typeDescriptorPtr(ea))

        attrs = BaseClassDescriptor.__attributes(ea)
        if attrs != 0 and attrs != 0x40:
            print '%08X: Suspicious attributes value: %08X' % (ea, attrs)
            # raise RttiError('%08X: Suspicious attributes value: %08X' % (ea, attrs))
        isV2 = (attrs & 0x40) != 0
        if isV2:
            strid = idaapi.get_struc_id('_s__RTTIBaseClassDescriptor2')
        else:
            strid = idaapi.get_struc_id('_s__RTTIBaseClassDescriptor')
        size = idaapi.get_struc_size(strid)
        idaapi.do_unknown_range(ea, size, idaapi.DOUNK_DELNAMES)
        idaapi.doStruct(ea, size, strid)

        pmd = BaseClassDescriptor.__where(ea)
        name = '??_R1'
        name += mangleNumber(pmd.mdisp)
        name += mangleNumber(pmd.pdisp)
        name += mangleNumber(pmd.vdisp)
        name += mangleNumber(attrs)
        name += td.baseMangledName + '8'
        idaapi.set_name(ea, name, 0)

        if isV2:
            ClassHierarchyDescriptor.define(BaseClassDescriptor.__v2ChdPtr(ea))
Пример #6
0
def clear_prefix():
    """
    Clear user defined prefixes from the selected functions in the Functions window.
    """

    #
    # loop through all the functions selected in the 'Functions window' and
    # clear any user defined prefixes applied to them.
    #

    for func_name in get_selected_funcs():

        #
        # locate the last (rfind) prefix separator in the function name as
        # we will want to keep everything that comes after it
        #

        i = func_name.rfind(PREFIX_SEPARATOR)

        # if there is no prefix (separator), there is nothing to trim
        if i == -1:
            continue

        # trim the prefix off the original function name and discard it
        new_name = func_name[i + 1:]
        func_addr = idaapi.get_name_ea(idaapi.BADADDR, func_name)
        idaapi.set_name(func_addr, new_name, idaapi.SN_NOWARN)

    # refresh the IDA views
    refresh_views()
Пример #7
0
 def yarasearch(self, memory, offsets, rules):
     print ">>> start yara search"
     values = list()
     matches = rules.match(data=memory)
     for match in matches:
         #print "%s => %d matches" % (name, len(match.strings))
         for string in match.strings:
             # print "\t 0x%08x : %s" % (self.toVirtualAddress(string[0],offsets),repr(string[2]))
             name = match.rule
             try:
                 if name.endswith("_API"):
                     name = name + "_" + idc.GetString(
                         self.toVirtualAddress(string[0], offsets))
             except:
                 pass
             value = [
                 self.toVirtualAddress(string[0], offsets),
                 name + "_" + hex(self.toVirtualAddress(
                     string[0], offsets)).lstrip("0x").rstrip("L").upper(),
                 string[1],
                 repr(string[2]),
             ]
             idaapi.set_name(
                 value[0],
                 name + "_" + hex(self.toVirtualAddress(
                     string[0], offsets)).lstrip("0x").rstrip("L").upper(),
                 0)
             values.append(value)
     print "<<< end yara search"
     return values
Пример #8
0
def load_file(li, neflags, format):
    if format != "NeoGeo 68k loader":
        return 0

    idaapi.set_processor_type("68000", SETPROC_ALL | SETPROC_FATAL)

    idaapi.add_segm(0, 0x000000, 0x0FFFFF, "ROM", "CODE")
    idaapi.add_segm(0, 0x100000, 0x10F2FF, "WRAM", "DATA")
    idaapi.add_segm(0, 0x10F300, 0x10FFFF, "BIOSRAM", "DATA")
    idaapi.add_segm(0, 0x200000, 0x2FFFFF, "PORT", "DATA")
    idaapi.add_segm(0, 0x300000, 0x3FFFFF, "IO", "DATA")
    idaapi.add_segm(0, 0x400000, 0x401FFF, "PALETTES", "DATA")
    idaapi.add_segm(0, 0x800000, 0xBFFFFF, "MEMCARD", "DATA")
    idaapi.add_segm(0, 0xC00000, 0xC1FFFF, "SYSROM", "DATA")
    idaapi.add_segm(0, 0xD00000, 0xD0FFFF, "BRAM", "DATA")

    li.seek(0, 2)
    size = li.tell()
    li.seek(0)
    file_data = li.read(size)
    idaapi.mem2base(file_data, 0, 0x100000)

    name_long(0x000000, "InitSP")
    name_long(0x000004, "InitPC")

    idaapi.do_unknown(0x3C0000, 1)
    idaapi.doByte(0x3C0000, 1)
    idaapi.set_name(0x3C0000, "REG_VRAMADDR")
    #idaapi.set_cmt(0x3C0000, "Pouet.", 1)

    return 1
Пример #9
0
    def define(ea):
        if BaseClassDescriptor.isDefined(ea):
            return

        td = TypeDescriptor(BaseClassDescriptor.__typeDescriptorPtr(ea))

        attrs = BaseClassDescriptor.__attributes(ea)
        if attrs != 0 and attrs != 0x40:
            print "%08X: Suspicious attributes value: %08X" % (ea, attrs)
            # raise RttiError('%08X: Suspicious attributes value: %08X' % (ea, attrs))
        isV2 = (attrs & 0x40) != 0
        if isV2:
            strid = idaapi.get_struc_id("_s__RTTIBaseClassDescriptor2")
        else:
            strid = idaapi.get_struc_id("_s__RTTIBaseClassDescriptor")
        size = idaapi.get_struc_size(strid)
        idaapi.do_unknown_range(ea, size, idaapi.DOUNK_DELNAMES)
        idaapi.doStruct(ea, size, strid)

        pmd = BaseClassDescriptor.__where(ea)
        name = "??_R1"
        name += mangleNumber(pmd.mdisp)
        name += mangleNumber(pmd.pdisp)
        name += mangleNumber(pmd.vdisp)
        name += mangleNumber(attrs)
        name += td.baseMangledName + "8"
        idaapi.set_name(ea, name, 0)

        if isV2:
            ClassHierarchyDescriptor.define(BaseClassDescriptor.__v2ChdPtr(ea))
Пример #10
0
def add_arg_descr(function, segment_ea, arg_description_format):
    """ Name address in added segment annotated with argument descriptions.

    Arguments:
    function -- function object
    segment_ea -- start looking for empty byte to annotate from this ea

    Return:
    next possible free address to add information to
    """
    # No arguments
    if len(function.arguments) == 0:
        return segment_ea
    for argument in function.arguments:
        try:
            free_ea = get_segment_end_ea(segment_ea)
        except FailedToExpandSegmentException as e:
            raise e

        fields = {
            "function_name": function.name,
            "function_dll": function.dll,
            "argument_name": argument.name,
        }
        name = arg_description_format.format(**fields)
        if not name_exists(name):
            g_logger.debug(' Adding name {} at {}'.format(name, hex(free_ea)))
            idaapi.set_name(free_ea, name)
            description = argument.description[:MAX_ARG_DESCR_LEN]
            idc.set_cmt(free_ea, format_comment(description), 0)
        else:
            g_logger.debug(' Name %s already exists' % name)
    return (free_ea + 1)
Пример #11
0
def main() -> None:
    all_vtables = ai_common.get_vtables()
    names = ai_common.get_action_vtable_names()
    not_decompiled = {func.addr for func in utils.get_functions() if func.status == utils.FunctionStatus.NotDecompiled}

    new_names: Dict[int, str] = dict()

    order = ai_common.topologically_sort_vtables(all_vtables, "Action")
    for vtable_addr in order:
        if vtable_addr in BaseClasses:
            continue

        class_name = names.get(vtable_addr)
        for i, fn_ea in enumerate(iterate_vtable(vtable_addr)):
            if idaapi.get_name(fn_ea) == "__cxa_pure_virtual":
                continue

            real_fn_ea = fn_ea & ~_ida_base
            if real_fn_ea not in new_names:
                if i < len(_vtable_fn_names):
                    new_names[real_fn_ea] = format_fn_name(_vtable_fn_names[i], class_name)
                else:
                    # Unknown member function.
                    new_names[real_fn_ea] = f"uking::action::{class_name}::m{i}"

                if real_fn_ea in not_decompiled:
                    idaapi.set_name(fn_ea, new_names[real_fn_ea])

    utils.add_decompiled_functions(dict(), new_names)
Пример #12
0
def add_arg_descr(function, segment_ea, arg_description_format):
    """ Name address in added segment annotated with argument descriptions.

    Arguments:
    function -- function object
    segment_ea -- start looking for empty byte to annotate from this ea

    Return:
    next possible free address to add information to
    """
    # No arguments
    if len(function.arguments) == 0:
        return segment_ea
    for argument in function.arguments:
        try:
            free_ea = get_segment_end_ea(segment_ea)
        except FailedToExpandSegmentException as e:
            raise e

        fields = {
            "function_name": function.name,
            "function_dll":  function.dll,
            "argument_name": argument.name,
        }
        name = arg_description_format.format(**fields).encode('utf-8')
        if not name_exists(name):
            g_logger.debug(' Adding name {} at {}'.format(name, hex(free_ea)))
            idaapi.set_name(free_ea, name)
            description = argument.description[:MAX_ARG_DESCR_LEN]
            idc.MakeComm(free_ea, format_comment(description))
        else:
            g_logger.debug(' Name %s already exists' % name)
    return (free_ea + 1)
Пример #13
0
 def yarasearch(self, memory, offsets, rules):
     print(">>> start yara search")
     values = list()
     matches = rules.match(data=memory)
     for match in matches:
         for string in match.strings:
             name = match.rule
             if name.endswith("_API"):
                 try:
                     name = name + "_" + idc.GetString(
                         self.toVirtualAddress(string[0], offsets))
                 except:
                     pass
             value = [
                 self.toVirtualAddress(string[0], offsets),
                 match.namespace,
                 name + "_" + hex(self.toVirtualAddress(
                     string[0], offsets)).lstrip("0x").rstrip("L").upper(),
                 string[1],
                 repr(string[2]),
             ]
             idaapi.set_name(
                 value[0],
                 name + "_" + hex(self.toVirtualAddress(
                     string[0], offsets)).lstrip("0x").rstrip("L").upper(),
                 0)
             values.append(value)
     print("<<< end yara search")
     return values
Пример #14
0
def search_function():
    curr_addr = MinEA()
    end = MaxEA()
    current_func_name = ""
    while curr_addr < end:
        if curr_addr == idc.BADADDR:
            break
        elif idc.GetMnem(curr_addr) == 'call':
            if idc.GetOpnd(curr_addr, 0) in FUNCTIONS_REGISTERS.keys():
                func_name_addr = get_string_for_function(
                    curr_addr, FUNCTIONS_REGISTERS[idc.GetOpnd(curr_addr,
                                                               0)].lower())
                if func_name_addr:
                    try:
                        function_start = idc.GetFunctionAttr(
                            curr_addr, idc.FUNCATTR_START)
                        new_filename = get_fixed_source_filename(
                            func_name_addr)
                        current_func_name = idc.GetFunctionName(function_start)
                        if is_function_name(current_func_name):
                            idaapi.set_name(function_start, new_filename,
                                            idaapi.SN_FORCE)
                        else:
                            print "Function:", current_func_name, "was not changed"
                    except:
                        print "failed at address " + hex(curr_addr), \
                            "function:", current_func_name, "call:", idc.GetOpnd(curr_addr, 0)
        curr_addr = idc.NextHead(curr_addr)
Пример #15
0
def bulk_prefix():
    """
    Prefix the Functions window selection with a user defined string.
    """

    # prompt the user for a prefix to apply to the selected functions
    tag = idaapi.ask_str(PREFIX_DEFAULT, 0, "Function Tag")

    # the user closed the window... ignore
    if tag == None:
        return

    # the user put a blank string and hit 'okay'... notify & ignore
    elif tag == '':
        idaapi.warning("[ERROR] Tag cannot be empty [ERROR]")
        return

    #
    # loop through all the functions selected in the 'Functions window' and
    # apply the user defined prefix tag to each one.
    #

    for func_name in get_selected_funcs():

        # ignore functions that already have the specified prefix applied
        if func_name.startswith(tag):
            continue

        # apply the user defined prefix to the function (rename it)
        new_name  = '%s%s%s' % (str(tag), PREFIX_SEPARATOR, func_name)
        func_addr = idaapi.get_name_ea(idaapi.BADADDR, func_name)
        idaapi.set_name(func_addr, new_name, idaapi.SN_NOWARN)

    # refresh the IDA views
    refresh_views()
Пример #16
0
    def define(ea):
        if CompleteObjectLocator.isDefined(ea):
            return
        if not CompleteObjectLocator.isValid(ea):
            raise RttiError("%08X: doesn't look like a correct CompleteObjectLocator" % (ea))

        # Ensure referenced structs are defined.
        # An exception will be thrown if something goes wrong.
        tdPtr = idaapi.get_full_long(ea + 12)
        td = TypeDescriptor(tdPtr)
        chdPtr = idaapi.get_full_long(ea + 16)
        chd = ClassHierarchyDescriptor(chdPtr)

        strid = idaapi.get_struc_id("_s__RTTICompleteObjectLocator")
        size = idaapi.get_struc_size(strid)
        idaapi.do_unknown_range(ea, size, idaapi.DOUNK_DELNAMES)
        idaapi.doStruct(ea, size, strid)

        if chd.isMultipleInheritance:
            if chd.isVirtualInheritance:
                print "%08X: Cannot handle virtual inheritance yet." % (ea)
            else:
                # '??_R4' + td.baseMangledName + '6B' + baseClassTd.baseMangledName + '@'
                # '??_7'  + ...
                print "%08X: Cannot handle multiple inheritance yet." % (ea)
        else:
            idaapi.set_name(ea, "??_R4" + td.baseMangledName + "6B@", 0)
Пример #17
0
def kiwidog(address, end, search):
    
    magic = idaapi.find_binary(address, end, search, 0x0, SEARCH_DOWN)
    function = idaapi.get_func(idaapi.get_first_dref_to(magic))
    idaapi.set_name(function.start_ea, '__stack_chk_fail', SN_NOCHECK | SN_NOWARN)
    function.flags |= FUNC_NORET
    idaapi.update_func(function)
Пример #18
0
    def search(self):

        exports = set([info[3] for info in idautils.Entries()])
        comexports = set([
            'DllUnregisterServer', 'DllEntryPoint', 'DllGetClassObject',
            'DllCanUnloadNow', 'DllRegisterServer'
        ])
        dllpath = ida_nalt.get_input_file_path().decode('utf-8')
        if not comexports.issubset(exports):
            print('{} is not COM! exports mismatching'.format(dllpath))
            return
        try:
            tlb = pythoncom.LoadTypeLib(dllpath)
        except:
            print('{} is not COM! LoadTypeLib fail'.format(dllpath))
            return
        classes = {}
        values = []
        for i in range(tlb.GetTypeInfoCount()):
            if tlb.GetTypeInfoType(i) == pythoncom.TKIND_COCLASS:
                ctypeinfo = tlb.GetTypeInfo(i)
                clsid = str(ctypeinfo.GetTypeAttr().iid)
                for j in range(ctypeinfo.GetTypeAttr().cImplTypes):
                    typeinfo = ctypeinfo.GetRefTypeInfo(
                        ctypeinfo.GetRefTypeOfImplType(j))
                    attr = typeinfo.GetTypeAttr()
                    name = tlb.GetDocumentation(i)[0]
                    iid = str(attr.iid)
                    vas = self.get_com_vas(
                        dllpath.encode(locale.getdefaultlocale()[1]), clsid,
                        iid, str(attr.cFuncs))
                    if isinstance(vas, str):
                        print(vas)
                    else:
                        for findex in range(attr.cFuncs):
                            fundesc = typeinfo.GetFuncDesc(findex)
                            funnames = typeinfo.GetNames(fundesc.memid)
                            funname_ext = "{}_{}_{}".format(
                                name, funnames[0],
                                invokekinds[fundesc.invkind])
                            typ, flags, default = fundesc.rettype
                            desc = ''
                            if fundesc.invkind == pythoncom.INVOKE_FUNC:
                                desc += vartypes.get(typ, 'UNKNOWN') + ' ('
                                argi = 1
                                for argdesc in fundesc.args:
                                    typ, flags, default = argdesc
                                    desc += '{} {}'.format(
                                        vartypes.get(typ, 'UNKNOWN'),
                                        funnames[argi])
                                    if default is not None:
                                        desc += '={}'.format(default)
                                    desc += ' ,'
                                    argi += 1
                                desc += ')'
                            idaapi.set_name(vas[findex], funname_ext)
                            values.append(
                                [vas[findex], funname_ext, name, desc])
        ComHelperResultChooser("Comhelper", values).show()
Пример #19
0
 def setData(self, index, content, role) -> bool:
     if not index.isValid():
         return False
     func_info = self.function_info_list[index.row()]
     if index.column() == self.COL_NAME:
         set_name(func_info.start, str(content), SN_NOWARN)
         g_DataManager.refreshData()
     return True
Пример #20
0
def prefix_function(function_address, prefix):
    """
    Prefix a function name with the given string.
    """
    original_name = get_function_name(function_address)
    new_name = str(prefix) + PREFIX_SEPARATOR + str(original_name)

    # rename the function with the newly prefixed name
    idaapi.set_name(function_address, new_name, idaapi.SN_NOWARN)
Пример #21
0
 def commit(self):
     if self.name_modified:
         self.name_modified = False
         if self.address:
             idaapi.set_name(self.address, self.name)
     if self.tinfo_modified:
         self.tinfo_modified = False
         if self.address:
             idaapi.apply_tinfo2(self.address, self.tinfo.get_pointed_object(), idaapi.TINFO_DEFINITE)
Пример #22
0
 def commit(self):
     addresses = self.addresses
     if self.name_modified:
         self.name_modified = False
         if len(addresses) == 1:
             idaapi.set_name(addresses[0], self.name)
     if self.tinfo_modified:
         self.tinfo_modified = False
         if len(addresses) == 1:
             idaapi.apply_tinfo2(addresses[0], self.tinfo.get_pointed_object(), idaapi.TINFO_DEFINITE)
Пример #23
0
def markup_string(env, ea):
    t = GoString(ea, env=env)

    val = str(t)
    MakeComm(ea, str("String: %s" % (val)))

    tt = "string_" + val.replace("*", "ptr_")
    markup_fields(tt, t.get_fields())

    idaapi.set_name(ea, tt)
Пример #24
0
def create_dword_and_name(offset, name):
    """
    Apply dword type to offset and name it

    :param offset: Offset of word
    :param name: Name to apply
    """

    idaapi.create_dword(offset, 4)
    idaapi.set_name(offset, name, idaapi.SN_NOWARN|idaapi.SN_NOLIST|idaapi.SN_NOCHECK)
Пример #25
0
def define_ke_task_desc(ea, task_desc_name):

    print "{}: 0x{:X}".format(task_desc_name, ea)

    sid = idaapi.get_struc_id("ke_task_desc")
    struct_size = idaapi.get_struc_size(sid)

    # undefined addr and define struct
    idaapi.del_items(ea, struct_size, idaapi.DELIT_DELNAMES)
    idaapi.create_struct(ea, struct_size, sid)
    idaapi.set_name(ea, task_desc_name, idaapi.SN_FORCE)
Пример #26
0
def define_func(addr, name):

    if addr & 1:
        addr -= 1
        idaapi.split_sreg_range(addr, idaapi.str2reg("T"), 1, idaapi.SR_user)
    else:
        idaapi.split_sreg_range(addr, idaapi.str2reg("T"), 0, idaapi.SR_user)

    if idaapi.create_insn(addr):
        idc.add_func(addr)
        idaapi.set_name(addr, name, idaapi.SN_FORCE)
Пример #27
0
def markup_fields(base_name, fields):
    for field in fields:
        idaapi.set_name(field.ea, base_name + "_" + field.name)
        if len(field.instance) == 1:
            MakeByte(field.ea)
        if len(field.instance) == 2:
            MakeWord(field.ea)
        if len(field.instance) == 4:
            MakeDword(field.ea)
        if len(field.instance) == 8:
            MakeQword(field.ea)
Пример #28
0
    def req_lbl(self, hash):
        msg, offset, base = hash['msg'], hash['offset'], hash['base']
        offset, msg = self.addr_switch(offset, msg)
        if not offset:
            return

        ea = self.rebase(base, offset)
        if not ea:
            return

        idaapi.set_name(ea, str(msg), False)
        print ("[*] label added at 0x%x" % ea)
Пример #29
0
def do_dll_imports(dll, iatCurr, hashes):
    idaapi.msg("%lx: processing import hashes for dll %s\n" % (iatCurr, dll))
    hash2name = HashExportNames(dll)
    for h in hashes:
        if h in hash2name:
            idaapi.create_dword(iatCurr, 4)
            idaapi.set_name(
                iatCurr, hash2name[h],
                idaapi.SN_NOWARN | idaapi.SN_NOLIST | idaapi.SN_NOCHECK)
        else:
            idaapi.msg(
                "%lx: hash value %lx for dll %s could not be found\n" %
                iatCurr, h, dll)
        iatCurr += 4
Пример #30
0
    def define(ea):
        if TypeDescriptor.isDefined(ea):
            return
        if not TypeDescriptor.isValid(ea):
            raise RttiError("%08X: This doesn't look like a TypeDescriptor." % ea)

        # FIXME: 64-bit compatibility
        mangledName = getAsciiz(ea + 8)

        # Define data in DB
        structLength = 8 + len(mangledName) + 1
        idaapi.do_unknown_range(ea, structLength, idaapi.DOUNK_DELNAMES)
        idaapi.doStruct(ea, structLength, idaapi.get_struc_id("_TypeDescriptor"))
        idaapi.set_name(ea, TypeDescriptor.makeName(ea), 0)
Пример #31
0
def iometa_information():
    print("[-] UserClient Method construction")
    fd = open(iometa_path)
    data = fd.readlines()
    fd.close()

    # Current
    className = ""

    for line in data:
        t = line[:-1].strip()
        if "vtab" in t and "meta" in t:
            className = t.split(" ")[5]
            #print(className)
            continue

        #offset = int(t.split(" ")[0])
        addr = int(t.split(" ")[1][5:], 0)
        sym = idc.get_func_name(addr)
        name = t.split(" ")[4].split("(")[0]

        if not idau.is_function_start(addr):
            print("[iometa] Current '{}'' - [{}] is not defined as function".
                  format(name, hex(addr)))
            if not idau.force_function(addr):
                print("[iometa] Can't convert '{}' - [{}] to function".format(
                    name, hex(addr)))

        if "sub_" in sym:
            idaapi.set_name(addr, name, idaapi.SN_FORCE)

        if "externalMethod" in name:
            sid = ida_struct.get_struc_id(className)

            if sid == 0xffffffffffffffff and className != "IOUserClient":
                print("[iometa] can't resolve class {}, create one".format(
                    className))
                construct_class(className)

            tu = (
                '\x0c0=\tIOReturn\x07\xffA\n=\rIOUserClient=\tuint32_t\n=\x1aIOExternalMethodArguments\n=\x19IOExternalMethodDispatch\n=\tOSObject\n\x01',
                '\x05this\tselector\narguments\tdispatch\x07target\nreference')
            if not idc.apply_type(addr, tu):
                print(
                    "[iometa] externalMethod type propagation failure '{}' - [{}]"
                    .format(name, hex(addr)))

    print("[-] Done")
Пример #32
0
def recursive_prefix(addr):
    """
    Recursively prefix a function tree with a user defined string.
    """
    func_addr = idaapi.get_name_ea(idaapi.BADADDR, idaapi.get_func_name(addr))
    if func_addr == idaapi.BADADDR:
        idaapi.msg("Prefix: 0x%08X does not belong to a defined function\n" %
                   addr)
        return

    # NOTE / COMPAT:
    # prompt the user for a prefix to apply to the selected functions
    if using_ida7api:
        tag = idaapi.ask_str(PREFIX_DEFAULT, 0, "Function Tag")
    else:
        tag = idaapi.askstr(0, PREFIX_DEFAULT, "Function Tag")

    # the user closed the window... ignore
    if tag == None:
        return

    # the user put a blank string and hit 'okay'... notify & ignore
    elif tag == '':
        idaapi.warning("[ERROR] Tag cannot be empty [ERROR]")
        return

    # recursively collect all the functions called by this function
    nodes_xref_down = graph_down(func_addr, path=set([]))

    # graph_down returns the int address needs to be converted
    tmp = []
    tmp1 = ''
    for func_addr in nodes_xref_down:
        tmp1 = idaapi.get_func_name(func_addr)
        if tmp1:
            tmp.append(tmp1)
    nodes_xref_down = tmp

    # prefix the tree of functions
    for rename in nodes_xref_down:
        func_addr = idaapi.get_name_ea(idaapi.BADADDR, rename)
        if tag not in rename:
            idaapi.set_name(func_addr,
                            '%s%s%s' % (str(tag), PREFIX_SEPARATOR, rename),
                            idaapi.SN_NOWARN)

    # refresh the IDA views
    refresh_views()
Пример #33
0
def name(ea, string=None):
    '''Returns the name at the specified address. (local than global)'''
    if string is not None:
        SN_NOCHECK = 0x00
        SN_NOLIST = 0x80
        SN_LOCAL = 0x200
        SN_PUBLIC = 0x02

        n = name(ea)

        flags = SN_NOCHECK
        try:
            function.top(ea)
            flags |= SN_LOCAL
        except ValueError:
            flags |= 0

        res = idaapi.set_name(ea, string, flags)
        tag(ea, 'name', string)
        return n

    try:
        return tag(ea, 'name')
    except KeyError:
        pass
    return None
Пример #34
0
    def define(ea):
        if TypeDescriptor.isDefined(ea):
            return
        if not TypeDescriptor.isValid(ea):
            raise RttiError("%08X: This doesn't look like a TypeDescriptor." %
                            ea)

        # FIXME: 64-bit compatibility
        mangledName = getAsciiz(ea + 8)

        # Define data in DB
        structLength = 8 + len(mangledName) + 1
        idaapi.do_unknown_range(ea, structLength, idaapi.DOUNK_DELNAMES)
        idaapi.doStruct(ea, structLength,
                        idaapi.get_struc_id("_TypeDescriptor"))
        idaapi.set_name(ea, TypeDescriptor.makeName(ea), 0)
Пример #35
0
    def req_lbl(self, hash):
        msg, offset, base = hash['msg'], hash['offset'], hash['base']
        offset, msg = self.addr_switch(offset, msg)
        if not offset:
            return

        ea = self.rebase(base, offset)
        if not ea:
            return

        flags = False
        if str(msg).startswith('@@'):
            flags = idaapi.SN_LOCAL

        idaapi.set_name(ea, str(msg), flags)
        rs_log("label added at 0x%x" % ea)
Пример #36
0
def set_name(address, name, anyway=False):
    """Set the name of an address.

    Sets the name of an address in IDA.
    If the name already exists, check the `anyway` parameter:

        True - Add `_COUNTER` to the name (default IDA behaviour)
        False - Raise an `exceptions.SarkErrorNameAlreadyExists` exception.


    Args
        address: The address to rename.
        name: The desired name.
        anyway: Set anyway or not. Defualt ``False``.
    """
    success = idaapi.set_name(address, name,
                              idaapi.SN_NOWARN | idaapi.SN_NOCHECK)
    if success:
        return

    if anyway:
        success = idaapi.force_name(address, name)
        if success:
            return

        raise exceptions.SarkSetNameFailed(
            "Failed renaming 0x{:08X} to {!r}.".format(address, name))

    raise exceptions.SarkErrorNameAlreadyExists(
        "Can't rename 0x{:08X}. Name {!r} already exists.".format(
            address, name))
Пример #37
0
    def req_lbl(self, hash):
        msg, offset, base = hash["msg"], hash["offset"], hash["base"]
        offset, msg = self.addr_switch(offset, msg)
        if not offset:
            return

        ea = self.rebase(base, offset)
        if not ea:
            return

        flags = False
        if str(msg).startswith("@@"):
            flags = idaapi.SN_LOCAL

        idaapi.set_name(ea, str(msg), flags)
        print ("[*] label added at 0x%x" % ea)
Пример #38
0
def set_name(address, name, anyway=False):
    """Set the name of an address.

    Sets the name of an address in IDA.
    If the name already exists, check the `anyway` parameter:

        True - Add `_COUNTER` to the name (default IDA behaviour)
        False - Raise an `exceptions.SarkErrorNameAlreadyExists` exception.

    :param address: The address to rename.
    :param name: The desired name.
    :param anyway: Set anyway or not. Defualt `False`.
    :return: None
    """
    success = idaapi.set_name(address, name, idaapi.SN_NOWARN | idaapi.SN_NOCHECK)
    if success:
        return

    if anyway:
        success = idaapi.do_name_anyway(address, name)
        if success:
            return

        raise exceptions.SarkSetNameFailed("Failed renaming 0x{:08X} to {!r}.".format(address, name))

    raise exceptions.SarkErrorNameAlreadyExists(
        "Can't rename 0x{:08X}. Name {!r} already exists.".format(address, name))
Пример #39
0
def name(ea, string=None):
    '''Returns the name at the specified address. (local than global)'''
    if string is not None:
        SN_NOCHECK = 0x00
        SN_NOLIST = 0x80
        SN_LOCAL = 0x200
        SN_PUBLIC = 0x02

        n = name(ea)
        
        flags = SN_NOCHECK
        try:
            function.top(ea)
            flags |= SN_LOCAL
        except ValueError:
            flags |= 0

        res = idaapi.set_name(ea, string, flags)
        tag(ea, 'name', string)
        return n

    try:
        return tag(ea, 'name')
    except KeyError:
        pass
    return None
Пример #40
0
    def define(ea, count):
        # TODO: sanity checks

        idaapi.do_unknown_range(ea, count * 4, idaapi.DOUNK_DELNAMES)
        idaapi.doDwrd(ea, 4)
        idaapi.do_data_ex(ea, idaapi.getFlags(ea), count * 4, idaapi.BADADDR)
        # TODO: rewrite into idaapi calls
        idc.SetArrayFormat(ea, idc.AP_INDEX | idc.AP_IDXDEC, 1, 0)

        # Entry 0 describes the class itself => I can find out the class name.
        bcd = BaseClassDescriptor(idaapi.get_full_long(ea))
        idaapi.set_name(ea, "??_R2" + bcd.typeDescriptor.baseMangledName + "8", 0)

        i = 1
        while i < count:
            bcd = BaseClassDescriptor(idaapi.get_full_long(ea + i * 4))
            i += 1
Пример #41
0
    def define(ea):
        if ClassHierarchyDescriptor.isDefined(ea):
            return
        if not ClassHierarchyDescriptor.isValid(ea):
            raise RttiError("%08X: Doesn't look like a correct ClassHierarchyDescriptor" % ea)

        strid = idaapi.get_struc_id("_s__RTTIClassHierarchyDescriptor")
        size = idaapi.get_struc_size(strid)
        idaapi.do_unknown_range(ea, size, idaapi.DOUNK_DELNAMES)
        idaapi.doStruct(ea, size, strid)

        bca = BaseClassArray(
            ClassHierarchyDescriptor.__baseClassArrayPtr(ea), ClassHierarchyDescriptor.__baseClassCount(ea)
        )

        # Entry 0 describes the class itself => I can find out the class name.
        idaapi.set_name(ea, "??_R3" + bca[0].typeDescriptor.baseMangledName + "8", 0)
Пример #42
0
def name(fn, name=None):
    fn = by(fn)
    if name is None:
        res = idaapi.get_func_name(fn.startEA)
        if not res: res = idaapi.get_name(-1, fn.startEA)
        if not res: res = idaapi.get_true_name(fn.startEA, fn.startEA)
        return res
    return idaapi.set_name(fn.startEA, name, idaapi.SN_PUBLIC)
Пример #43
0
def markup_type(env, ea):
    t = GoType(ea, env=env)

    type_name = str(t.get("*name"))
    MakeComm(ea, str("Type: %s" % (type_name)))

    tt = "type_" + type_name.replace("*", "ptr_")
    markup_fields(tt, t.get_fields())
    idaapi.set_name(ea, tt)

    try:
        markup_uncommon_type(env, t.get_x().value())
    except:
        g_logger.info("failed to markup uncommon type")

    try:
        markup_type(env, t.get_pointerType().value())
    except:
        g_logger.info("failed to markup ptr type")
Пример #44
0
def markup_uncommon_type(env, ea):
    t = GoUncommonType(ea, env=env)

    type_name = str(t.get("*name"))
    MakeComm(ea, str("UncommonType: %s" % (type_name)))

    tt = "uncommontype_" + type_name.replace("*", "ptr_")
    markup_fields(tt, t.get_fields())
    idaapi.set_name(ea, tt)

    try:
        markup_string(env, t.get_name().value())
    except:
        g_logger.info("failed to markup uncommon type name string")

    try:
        markup_string(env, t.get_pkgPath().value())
    except:
        g_logger.info("failed to markup uncommon type pkgPath string")
Пример #45
0
 def __init__(self, address, name=""):
     self.address = address
     self.__frame = None
     self.__attributes = None
     
     self.__func_t = idaapi.get_func(self.address)
     if not self.__func_t:
         print "NOTE: Function does not exist at %08X, creating." % self.address
         if not idaapi.add_func(self.address, idc.BADADDR):
             print "ERR : Couldn't create function at %08X" % self.address
             raise Exception()
         if name:
             if not idaapi.set_name(address, name, idc.SN_AUTO):
                 print "ERR : Couldn't set function name at %08X to %s" % (self.address,name)
Пример #46
0
 def OnDeleteLine(self, n):
     ans = idaapi.askyn_c(1, "HIDECANCEL\nAre you sure you want to delete function [%s] @ [%s]?" % (self.items[n][3], self.items[n][4]) )
     if ans == 1:
         asms = Assembler.LoadSavedAssemblers()
         item = int(self.items[n][2], 16)
         if asms != None and len(asms.keys()) > 0:
             for asm in asms.itervalues():
                 if asm.functions.has_key(item):
                     print "Removed [%08x]!" % item
                     del asm.functions[item]
                     asm.SaveState()
         
         opty_ea = int(self.items[n][4], 16)
         print "set_name[%08x]" % opty_ea
         idc.MakeComm(opty_ea, "")
         idaapi.set_name(opty_ea, "")
         idc.DelFunction(opty_ea)
         
         comment = idc.Comment(item)
         comment = re.sub(r"(?i)OPTY@\[[\d+abcdef]+\];\s*", "", comment)
         idc.MakeComm(item, comment)
         
     self.populate_items()
     return n
Пример #47
0
 def searchAll(self):
     if self.start_ea is not None:
         l = list(idautils.Functions(idc.SegStart(self.start_ea), idc.SegEnd(self.end_ea)))
     else:
         l = list(idautils.Functions())
     
     for f in l:
         name = idc.GetFunctionName(f)
         
         if not name.startswith("sub_"):
             continue
         
         flags = idc.GetFunctionFlags(f)
         if flags & idc.FUNC_LIB or flags == -1:
             continue
         
         x = self.readFunction(f, False)
         
         if x:
             match = self.searchExact(x)
             if match:
                 print "%08x Function %s exact matches with %s" % (f, idc.GetFunctionName(f), match)
                 try:
                     idaapi.set_name(int(f), str(match))
                 except:
                     print "  %08x Cannot rename function" % f
                     print sys.exc_info()[1]
             else:
                 match = self.search(x)
                 if match:
                     print "%08x Function %s partially matches with %s" % (f, idc.GetFunctionName(f), match)
                     try:
                         idc.MakeComm(f, str(match))
                     except:
                         print "  %08x Cannot rename function" % f
                         print sys.exc_info()[1]
Пример #48
0
 def import_names(self, ranges):
     renames = self.extract_names(ranges)
     for new_name in renames:
         idaapi.set_name(new_name["addr"],
                         new_name["name"],
                         idaapi.SN_AUTO)
Пример #49
0
    def Assemble(self, function, nasm=True):
        '''
            Main Assemble Function
        '''

        if self.functions.has_key(function.start_ea):
            ans = idaapi.askyn_c(1, "HIDECANCEL\nFunction @ [%08x] was already optimized, are you sure you want to overwrite old one?")
            if ans == 0:
                return

        idc.Batch(1)

        self.jmp_table = ""
        self.jmp_table_refs = []
        self.jmp_deps = {}
        self.ref_instr = {}
        self.bb_head_ea = {}

        function_ea = self.free_ea
        function_end = None

        if debug:
            print ">Assemble(%08x) - Starting" % function.start_ea

        if nasm:
            if self.opty_dir == None:
                self.opty_dir = idc.GetIdbPath()
                self.opty_dir = self.opty_dir[:self.opty_dir.rfind(os.sep)] + os.sep + "optimice_%s" % idc.GetInputFile()
                if not os.path.isdir(self.opty_dir):
                    os.mkdir(self.opty_dir)

            self.nasm = True
            self.nasmfw = open(self.opty_dir + os.sep + 'f_%08x.asm' % function.start_ea, "w+")
            self.NasmWriteToFile("[BITS 32]\n")
            self.NasmWriteToFile("\torg %09xh\n" % function_ea)
        else:
            self.nasm = False

        for bb_ea in function.DFSFalseTraverseBlocks():
            if self.nasm:
                self.NasmWriteToFile("\nL%08x:\n" % bb_ea)
                self.bb_head_ea[bb_ea] = True
            else:
                self.bb_head_ea[bb_ea] = self.free_ea

            for instr in function.GetBBInstructions(bb_ea):
                if instr == None:
                    continue

                mnem = self.BuildAsmString(instr, function)

                if debug:
                    print ">Assemble - Assembling @ %08x [%s]" % (instr.GetOriginEA(), mnem)

                if not self.nasm:
                    self.AsmAndWrite(mnem, instr, function=function)

            if not instr.IsCFI():
                ref_from = list(function.GetRefsFrom(instr.GetOriginEA()))[0][0]

                if self.bb_head_ea.has_key(ref_from):
                    if self.nasm:
                        self.NasmWriteToFile("\tjmp L%08x ; \n" % ref_from)
                    else:
                        self.AsmAndWrite("jmp %09xh" % self.bb_head_ea[ref_from])

            elif instr.GetMnem() == "call":
                for ref,path in function.GetRefsFrom(instr.GetOriginEA()):
                    if path == False:
                        if self.bb_head_ea.has_key(ref):
                            if self.nasm:
                                self.NasmWriteToFile("\tjmp L%08x ; ###FAKE 2 JMP###\n" % ref)
                            else:
                                self.AsmAndWrite("jmp %09xh" % self.bb_head_ea[ref])

            elif instr.IsJcc():
                ref_from = list(function.GetRefsFrom(instr.GetOriginEA()))
                for ref,path in ref_from:
                    if path == False:
                        break

                if path == True:
                    raise MiscError

                elif self.bb_head_ea.has_key(ref):
                    print "Check this out @ [%08x] ref:[%08x]" % (instr.GetOriginEA(), ref)
                    if self.nasm:
                        self.NasmWriteToFile("\tjmp L%08x ; ###FAKE 2 JMP###\n" % ref)
                    else:
                        self.AsmAndWrite("jmp %09xh" % self.bb_head_ea[ref])

        ret = None
        if self.nasm:
            self.NasmWriteToFile(self.jmp_table)

            self.nasmfw.close()
            self.nasmfw = None

            ret = self.NasmAssemble(function.start_ea, self.free_ea)
            if ret != None:
                self.free_ea = ret
        else:
            ret = self.AsmAndWriteBranches(function)
            self.free_ea = ret

        self.ref_instr = {}
        idc.Batch(0)

        if ret != None:
            idc.MakeFunction(function_ea)

            comment = idc.Comment(function_ea)
            if comment != None:
                comment = 'Origin@[%08x]; %s' % (function.start_ea, comment)
            else:
                comment = 'Origin@[%08x];' % function.start_ea

            idc.MakeComm(function_ea, comment)

            comment = idc.Comment(function.start_ea)
            if comment != None:
                comment = 'OPTY@[%08x]; %s' % (function_ea, comment)
            else:
                comment = 'OPTY@[%08x];' % function_ea

            idc.MakeComm(function.start_ea, comment)

            idaapi.set_name(function_ea, "om_%s" % idc.Name(function.start_ea))

        function_end = self.free_ea
        self.functions[function.start_ea] = (function_ea, function_end)

        idaapi.refresh_idaview_anyway()
Пример #50
0
 def _embed_func_name(self, name):
     idaapi.set_name(self._first_addr, name, idaapi.SN_NOWARN)
Пример #51
0
 def set_func_name(cls, start_addr, func_name):
     idaapi.set_name(start_addr, func_name, idaapi.SN_NOWARN)
Пример #52
0
def queryFile(comFile, tMan, iMan, coClassCLSID=None, coClassName=None):

    success = False
    imgBase = idaapi.get_imagebase()

    class tmpCoClass(object):
        def __init__(self, name, iid):
            self.iid = iid
            self.name = self.entryName = coClassName

    if not os.access(comFile, os.R_OK|os.X_OK):
        print "Bad file permissions on %s, can't RX" % (comFile)
        return False

    try:
        tlb = pyTypeLibs.typeLib(comFile)
        tMan.addLib(tlb)
        classes = tlb.getClasses()
    except OSError:
        if not coClassCLSID:
            print "%s has no typelib, but we need a CLSID to create an instance" % comFile
            print "Try passing the -C argument with a clsid to instantiate"
            return False
        else:
            tmpClass = tmpCoClass("obj", coClassCLSID)
            print "Using CLSID %s to instantiate" % (coClassCLSID)
            classes = [tmpClass]
    
    #
    if coClassCLSID:
        tmpClass = tmpCoClass("obj", coClassCLSID)
        print "Using CLSID %s to instantiate" % (coClassCLSID)
        classes = [tmpClass]

    #
    for coclass in classes:
        
        #try and instantiate each coclass we find
        try:
            iuk = iquery.iQuery()
            if iuk.coCreateUnknown(comFile, coclass.iid):
                success = True
                print "Class %s (%s)" % (coclass.entryName, coclass.iid)
                del iuk
            else:
                print "Failed to CoCreate class %s %s" % (coclass.entryName, coClass.iid)
                continue

            #
            for iFace in iMan.getInterfaceList():

                #any exception caught by the outside try{}
                iuk = iquery.iQuery()
                if not iuk.coCreateUnknown(comFile, coclass.iid):
                    break
                
                #
                try:
                    if iuk.isInterfaceSupported(iFace.iid):
                        iMan.resolveBase(iFace)
                        print "  Interface %s %s" % (iFace.entryName, iFace.iid)
                        print "    Inheritance hierarchy: %s" % (iFace.hierStr())
                        vtOffset = imgBase + iuk.getIFaceVTOffset(iFace.iid)
                        iName = coclass.entryName + "::" + iFace.entryName
                        if not idaapi.set_name(int(vtOffset), str(iName)):
                            print "ERROR:Failed to set interface name, (%#x, %s)" % (vtOffset, iName)
                        print "    %s - VT addr %#x" % (iFace.entryName, vtOffset)
                        offset = 0
                        for func in iFace.getVtable():
                            fName = iName + "::" + func.name
                            fAddr = idc.Dword(vtOffset + offset)
                            if not idaapi.set_name(int(fAddr), str(fName)):
                                print "ERROR:Failed to set function name, (%#x, %s)" % (fAddr, fName)
                                break
                            #print "      (%#x) %s" % (vtOffset + offset, str(func))
                            offset += 4
                    else:
                        #print "%s (%s) not supported" % (iFace.iid, iFace.entryName)
                        pass
                except RuntimeError, exc:
                    #print "EXC %s" % (exc)
                    #print "%s (%s) not supported (EXC)" % (iFace.iid, iFace.entryName)
                    pass

                del iuk

        except RuntimeError, exc:
            if not isinstance(coclass, pyTypeLibs.tCoClass) or coclass.canCreate():
                print "INFO:Failed to CoCreate class %s %s, %s" % (coclass.entryName, coclass.iid, str(exc))
                print("If LoadLibrary() failed, it may be because the DLL tried load a resource\n"
                        "DLL that is based on the current module name. msxml3.dll tries to do this\n"
                        "when it tries to load msxml3r.dll\n")