예제 #1
0
 def query_selected_func(self, ctx):
     title = self._get_ctx_title(ctx)
     if title == "Functions window":
         if IDAUtils.is_hexrays_v7():
             ida_funcs = [idaapi.getn_func(f_idx) for f_idx in
                          ctx.chooser_selection]
         else:
             ida_funcs = [idaapi.getn_func(f_idx - 1) for f_idx in
                          ctx.chooser_selection]
         if self._get_connector() is not None:
             self.connector.search_func(
                 queries=IDAUtils.get_as_multiple_surrogate(ida_funcs),
                 topk=self.get_conf_topk(),
                 threshold=self.get_conf_threshold(),
                 avoid_same_binary=self.get_conf_avoidSameBinary())
     else:
         connector, ida_funcs, threshold, topk, avoidSameBinary = self.select_funcs()
         if ida_funcs is None:
             return
         if connector is None:
             self.open_cnn_manager()
             connector = self.connector
         if connector is not None and ida_funcs is not None and len(
                 ida_funcs) > 0:
             connector.search_func(
                 queries=IDAUtils.get_as_multiple_surrogate(ida_funcs),
                 topk=topk,
                 threshold=threshold,
                 avoid_same_binary=avoidSameBinary)
예제 #2
0
 def get_chooser_item_attrs(self, chooser, n, attrs):
     func = idaapi.getn_func(n)
     if bai_mark.is_bai_func(func.start_ea):
         colors = [0x8B98B3, 0x6F82AB, 0x5B74AB, 0x3B5BA1, 0x304A82]
         score = bai_mark.record[func.start_ea]['score']
         index = max(int((score * 100 - 80) / 5), 0)
         attrs.color = colors[index]
예제 #3
0
 def activate(self, ctx):
     for idx in ctx.chooser_selection:
         func_ea = idaapi.getn_func(idx - 1).startEA
         cfunc = helper.decompile_function(func_ea)
         obj = api.VariableObject(cfunc.get_lvars()[0], 0)
         if cfunc:
             NewDeepSearchVisitor(cfunc, 0, obj, cache.temporary_structure).process()
예제 #4
0
    def run(self, arg):
        """
            loop through all functions, collect "self._data", then show view

            @param: arg : --
        """
        try:
            self._data = dict()
            count = idaapi.get_func_qty()
            for i in xrange(count):
                fn = idaapi.getn_func(i)
                fn_an = self.analyze_func(fn)

                # if fn_an['math']:
                # 	print 'fn: %#08x has math' % fn.startEA

                if idaapi.has_dummy_name(idaapi.getFlags(fn.startEA)):
                    self._handle_calls(fn, fn_an)

                self._handle_tags(fn, fn_an)

            if self.view:
                self.view.Close(idaapi.PluginForm.FORM_NO_CONTEXT)

            self.view = AutoREView(self._data)
            self.view.Show()
        except:
            idaapi.msg('AutoRE: error: %s\n' % traceback.format_exc())
예제 #5
0
파일: ida_binaryai.py 프로젝트: nforest/sdk
 def get_chooser_item_attrs(self, chooser, n, attrs):
     func = idaapi.getn_func(n)
     if bai_mark.is_bai_func(func.start_ea):
         colors = [0xE8E4FF, 0xC0BAFF, 0x817FFF, 0x5E58FF]
         score = bai_mark.record[func.start_ea]['score']
         index = max(int((score*100-80)/5), 0)
         attrs.color = colors[index]
예제 #6
0
def process_func(i):
    """Convert function i into a mega file line."""
    func = idaapi.getn_func(i)
    if not func:
        return

    if idaapi.has_name(idaapi.getFlags(func.startEA)) and \
       not (func.flags & idaapi.FUNC_LIB):
        return create_func_signature(func.startEA, func.endEA - func.startEA)
 def activate(self, ctx):
     for pfn_id in ctx.chooser_selection:
         ida_func = idaapi.getn_func(pfn_id - 1)
         if self._action == ACTION_ADD_ANNOTATION:
             ali.ida_add_lineinfo_comment_to_func(
                 ali_plugin.dia, ida_func)
         elif self._action == ACTION_DEL_ANNOTATION:
             ali.ida_del_lineinfo_comment_from_func(ida_func)
     return 1
예제 #8
0
 def index_selected_func(self, ctx):
     title = self._get_ctx_title(ctx)
     if title == "Functions window":
         if IDAUtils.is_hexrays_v7():
             ida_funcs = [idaapi.getn_func(f_idx) for f_idx in
                          ctx.chooser_selection]
         else:
             ida_funcs = [idaapi.getn_func(f_idx - 1) for f_idx in
                          ctx.chooser_selection]
         if self._get_connector() is not None:
             self.connector.index(
                 IDAUtils.get_as_single_surrogate(ida_funcs))
     else:
         connector, ida_funcs, _, _, _ = self.select_funcs()
         if ida_funcs is None:
             return
         if connector is None:
             self.open_cnn_manager()
             connector = self.connector
         if connector is not None and ida_funcs is not None and len(ida_funcs) > 0:
             self.connector.index(
                 IDAUtils.get_as_single_surrogate(ida_funcs))
예제 #9
0
    def _preprocess_api_wrappers(self, fnqty):
        rv = defaultdict(dict)

        for i in xrange(fnqty):
            fn = idaapi.getn_func(i)
            items = list(FuncItems(self.start_ea_of(fn)))
            if len(items) not in (1, 2):
                continue

            dis0 = decode_insn(items[0])
            if dis0 is None:
                continue
            addr = self._check_is_jmp_wrapper(dis0)

            if not addr and len(items) > 1:
                dis1 = decode_insn(items[1])
                if dis1 is not None:
                    addr = self._check_is_push_retn_wrapper(dis0, dis1)

            if not addr:
                continue

            name = idaapi.get_ea_name(addr)
            name = name.replace(idaapi.FUNC_IMPORT_PREFIX, '')
            if not name:
                continue

            imp_stripped_name = name.lstrip('_')

            for tag, names in TAGS.items():
                for tag_api in names:
                    if tag in STRICT_TAG_NAME_CHECKING:
                        match = tag_api in (name, imp_stripped_name)
                    else:
                        match = tag_api in name
                    if not match:
                        continue

                    refs = list(CodeRefsTo(self.start_ea_of(fn), 1))

                    for ref in refs:
                        ref_fn = idaapi.get_func(ref)
                        if not ref_fn:
                            # idaapi.msg('AutoRE: there is no func for ref: %08x for api: %s' % (ref, name))
                            continue
                        if tag not in rv[self.start_ea_of(ref_fn)]:
                            rv[self.start_ea_of(ref_fn)][tag] = list()
                        if name not in rv[self.start_ea_of(ref_fn)][tag]:
                            rv[self.start_ea_of(ref_fn)][tag].append(name)
        return dict(rv)
예제 #10
0
    def interactive_load_exec_tree(self,ctx):
        disassembler.show_wait_box("Start building execute trace metadata...")
        # Thx to Arnaud :)
        idx_l = list(ctx.chooser_selection)
        if len(idx_l) > 1:
            print "UI: multiple selection not allowed!"
            return 1

        f = idaapi.getn_func(idx_l[0])
        self.director.exec_tree_addr = f.startEA
        if self._ui_exe_tree_overview and self._ui_exe_tree_overview.isVisible():
            self._ui_exe_tree_overview.show()
            return
        self._ui_exe_tree_overview =ExecuteTreeOverview(self)
        self._ui_exe_tree_overview.show()
예제 #11
0
 def indexSelectedFunctions(self, ctx):
     if ctx.form_title == "Functions window":
         funcs = []
         for fidx in ctx.chooser_selection:
             func = idaapi.getn_func(fidx - 1)
             funcs.append(func)
         self.createIndexProgressForm(funcs)
     else:
         form = IndexSelectionForm(self)
         ok = form.Execute()
         funcs = form.funcs
         s_cnn = form.cnn
         form.Free()
         if ok == 1:
             self.createIndexProgressForm(funcs, s_cnn)
예제 #12
0
 def querySelectedFunctions(self, ctx):
     if ctx.form_title == "Functions window":
         funcs = []
         for fidx in ctx.chooser_selection:
             func = idaapi.getn_func(fidx - 1)
             funcs.append(func)
         self.createProgressForm(funcs)
     else:
         form = SelectionForm(self)
         ok = form.Execute()
         funcs = form.funcs
         s_cnn = form.cnn
         form.Free()
         if ok == 1:
             self.createProgressForm(funcs, s_cnn)
예제 #13
0
    def run(self, arg):
        if RDEBUG and RDEBUG_EGG:
            if not os.path.isfile(RDEBUG_EGG):
                idaapi.msg(
                    'AutoRE: Remote debug is enabled, but I cannot find the debug egg: %s'
                    % RDEBUG_EGG)
            else:
                import sys

                if RDEBUG_EGG not in sys.path:
                    sys.path.append(RDEBUG_EGG)

                import pydevd
                pydevd.settrace(RDEBUG_HOST,
                                port=RDEBUG_PORT,
                                stdoutToServer=True,
                                stderrToServer=True
                                )  # , stdoutToServer=True, stderrToServer=True

        try:
            self._data = dict()
            count = idaapi.get_func_qty()

            # pre-process of api wrapper functions
            known_refs_tags = self._preprocess_api_wrappers(count)

            for i in xrange(count):
                fn = idaapi.getn_func(i)
                fn_an = self.analyze_func(fn)

                # if fn_an['math']:
                # 	print 'fn: %#08x has math' % fn.startEA

                if idaapi.has_dummy_name(idaapi.getFlags(fn.startEA)):
                    self._handle_calls(fn, fn_an)

                known_refs = known_refs_tags.get(fn.startEA)
                self._handle_tags(fn, fn_an, known_refs)

            if self.view:
                self.view.Close(idaapi.PluginForm.FORM_NO_CONTEXT)
            self.view = AutoREView(self._data)
            self.view.Show()
        except:
            idaapi.msg('AutoRE: error: %s\n' % traceback.format_exc())
예제 #14
0
    def _priority_paint_functions(self, target_address):
        """
        Paint functions in the immediate vicinity of the given address.

        This will paint both the instructions & graph nodes of defined functions.
        """
        database_coverage = self._director.coverage

        # the number of functions before and after the cursor to paint
        FUNCTION_BUFFER = 1

        # determine range of functions to repaint
        func_num = idaapi.get_func_num(target_address)
        func_num_start = func_num - FUNCTION_BUFFER
        func_num_end   = func_num + FUNCTION_BUFFER + 1

        # we will save the instruction addresses painted by our function paints
        function_instructions = set()

        # repaint the specified range of functions
        for num in xrange(func_num_start, func_num_end):
            function = idaapi.getn_func(num)
            if not function:
                continue

            # repaint the function
            self.paint_function(function)

            # NOTE/COMPAT:
            if using_ida7api:
                start_ea = function.start_ea
            else:
                start_ea = function.startEA

            # get the function coverage data for the target address
            function_coverage = database_coverage.functions.get(start_ea, None)
            if not function_coverage:
                continue

            # extract the painted instructions in this function
            function_instructions |= function_coverage.instructions

        # return the instruction addresses painted
        return function_instructions
예제 #15
0
 def querySelectedFunctions(self, ctx):
     if ctx.form_title == "Functions window":
         funcs = []
         for fidx in ctx.chooser_selection:
             func = idaapi.getn_func(fidx - 1)
             funcs.append(func)
         self.createProgressForm(funcs, self.getConfThreshold(),
                                 self.getConfTopK())
     else:
         form = SelectionForm(self)
         ok = form.Execute()
         funcs = form.funcs
         s_cnn = form.cnn
         form.Free()
         if ok == 1:
             self.createProgressForm(funcs,
                                     form.threshold,
                                     form.topk,
                                     cnn=s_cnn)
예제 #16
0
    def activate(self, ctx):
        for idx in ctx.chooser_selection:
            func_ea = idaapi.getn_func(idx - 1).startEA
            try:
                cfunc = idaapi.decompile(func_ea)
                if cfunc is None:
                    continue

                FunctionTouchVisitor(cfunc).process()

                lvars = cfunc.get_lvars()
                if not (lvars and lvars[0].is_arg_var and Helper.is_legal_type(lvars[0].type())):
                    continue

                scanner = DeepSearchVisitor(cfunc, 0, 0)
                scanner.process()
                for field in scanner.candidates:
                    self.temporary_structure.add_row(field)

            except idaapi.DecompilationFailure:
                print "[Warning] Failed to decompile function at 0x{0:08X}".format(func_ea)
예제 #17
0
	def handleFuncViewMenuAction(self, actionType, index):
		if self.clientSocket is None:
			fl_log("FridaLink: Frida not connected\n");
			return

		actionHandlers = {
			# HOOKS
			kPopupAction_HookFuncOnce 		: self.handleHookFuncOnce,
			kPopupAction_HookFuncPerm 		: self.handleHookFuncPerm,
			kPopupAction_HookFuncCust 		: self.handleHookFuncCust,
			kPopupAction_HookFuncEdit 		: self.handleHookFuncEdit,
			kPopupAction_HookFuncCPU		: self.handleHookFuncShowCPU,
			kPopupAction_HookFuncStack		: self.handleHookFuncShowStack,
			kPopupAction_HookFuncBacktrace  : self.handleHookFuncShowBacktrace,
			kPopupAction_HookFuncLinkMem  	: self.handleHookFuncLinkMemory,
			kPopupAction_UnhookFunc   		: self.handleUnhookFunc,
			# REPLACE
			kPopupAction_ReplaceFunc        : self.handleReplaceFunc,
			kPopupAction_ReplaceFuncEdit    : self.handleReplaceFuncEdit,
			kPopupAction_ReplaceFuncDel     : self.handleReplaceFuncDel,
		}

		actionHandlers[actionType](getn_func(index).startEA)
예제 #18
0
 def byAddress(cls, ea):
     n = idaapi.get_fchunk_num(ea)
     f = idaapi.getn_func(n)
     return cls.getIndex(n)
예제 #19
0
파일: idt_ext.py 프로젝트: pent0/EKA2L1
import idaapi
import idc
import types
import os

idt = GetIdbPath()

idt = idt.replace('.idb', '.idt')
idt = idt.replace('.i64', '.idt')

dll = GetInputFile()

f = open(idt, 'wb')
f.write("0 Name = %s\n" % (dll))
for i in xrange(idaapi.get_entry_qty()):
    fn = idaapi.getn_func(i)
    a = fn.startEA
    if a != BADADDR:
        eo = GetEntryOrdinal(i)
        nm = GetFunctionName(GetEntryPoint(eo))
        if nm != '':
            f.write("%d Name=%s\n" % (eo, nm))
f.close()
예제 #20
0
 def get_chooser_item_attrs(self, chooser, n, attrs):
     func = idaapi.getn_func(n)
     if bai_mark.is_bai_func(func.start_ea):
         attrs.color = int(bai_config['color'], 16)
예제 #21
0
def get_functions():
    for i in zrange(idaapi.get_func_qty()):
        yield idaapi.getn_func(i)
예제 #22
0
def get_all_funcs():
    for idx in range(idaapi.get_func_qty()):
        f = idaapi.getn_func(idx)
        yield f
예제 #23
0
        def activate(self, ctx):
            if self.menu_title == MenuAskEntryId:
                self.outer_self.mixto.entry_id = idaapi.ask_str(
                    "", 1000, "Mixto Entry Id")

            else:
                if self.outer_self.mixto.entry_id is None:
                    self.outer_self.mixto.entry_id = idaapi.ask_str(
                        "", 1000, "Mixto Entry Id")

            if self.menu_title == MenuAllFunc:
                all_func = ""
                # Get count of all functions in the binary
                count = idaapi.get_func_qty()

                for i in range(count):
                    fn = idaapi.getn_func(i)

                    # Function should not have dummy name such as sub_*
                    # and should not start with underscore (possible library functions)
                    if not idaapi.has_dummy_name(get_flags_at(
                            start_ea_of(fn))) and not idaapi.get_func_name(
                                start_ea_of(fn)).startswith("_"):
                        all_func += "{} @ 0x{:x}\n".format(
                            idaapi.get_func_name(start_ea_of(fn)),
                            start_ea_of(fn))
                self.outer_self.mixto.AddCommit(all_func,
                                                self.outer_self.mixto.entry_id,
                                                "(IDA) All Functions")

            elif self.menu_title == MenuImports:
                global AllImports
                AllImports = ""
                # Get count of all import modules in the binary
                count = idaapi.get_import_module_qty()

                for i in range(count):
                    module_name = idaapi.get_import_module_name(i)

                    AllImports += "{}:\n".format(module_name)
                    idaapi.enum_import_names(i, imports_cb)
                self.outer_self.mixto.AddCommit(AllImports,
                                                self.outer_self.mixto.entry_id,
                                                "(IDA) All Imports")

            elif self.menu_title == MenuDecFunc:
                addr_current = idc.get_screen_ea()
                addr_func = idaapi.get_func(addr_current)

                if not addr_func:
                    idaapi.msg("Place cursor inside a function!")
                    return False
                else:
                    err = None
                    out = str(idaapi.decompile(addr_func))
                    # print(out)
                    self.outer_self.mixto.AddCommit(
                        str(out),
                        self.outer_self.mixto.entry_id,
                        "(IDA) Function Decompilation {}".format(
                            idc.GetFunctionName(addr_func.startEA)),
                    )

            elif self.menu_title == MenuExports:
                all_exports = ""
                for entry in idautils.Entries():
                    _, ord, ea, name = entry
                    if not name:
                        all_exports += "0x{:x}: ord#{}\n".format(ea, ord)
                    else:
                        all_exports += "0x{:x}: {} ord#{}\n".format(
                            ea, name, ord)
                self.outer_self.mixto.AddCommit(all_exports,
                                                self.outer_self.mixto.entry_id,
                                                "(IDA) All Exports")

            elif self.menu_title == MenuAllComments:
                addr_current = idc.get_screen_ea()
                addr_func = idaapi.get_func(addr_current)

                uniq_comments = {}
                comments = []
                for ea in range(addr_func.startEA, addr_func.endEA):
                    comment = idaapi.get_cmt(ea, 0)
                    if comment is not None:
                        # hacky way to make sure only uniq comments are added
                        if uniq_comments.get(comment) == 1:
                            pass
                        else:
                            print(uniq_comments)
                            comments.append("{offset} {value}".format(
                                offset=hex(ea), value=comment))
                            print("here")
                            uniq_comments[comment] = 1
                if len(comments) > 0:
                    out = "\n".join(comments)
                    self.outer_self.mixto.AddCommit(
                        str(out),
                        self.outer_self.mixto.entry_id,
                        "(IDA) Function Comments {}".format(
                            idc.GetFunctionName(addr_func.startEA)),
                    )

                else:
                    raise TypeError("No comments found")

            return True
예제 #24
0
        def activate(self, ctx):
            if self.menu_title == MenuAskEntryId:
                self.outer_self.mixto.entry_id = idaapi.ask_str(
                    "", 1000, "Mixto Entry Id")

            else:
                if self.outer_self.mixto.entry_id is None:
                    self.outer_self.mixto.entry_id = idaapi.ask_str(
                        "", 1000, "Mixto Entry Id")

            if self.menu_title == MenuAllFunc:
                all_func = ""
                # Get count of all functions in the binary
                count = idaapi.get_func_qty()

                for i in range(count):
                    fn = idaapi.getn_func(i)

                    # Function should not have dummy name such as sub_*
                    # and should not start with underscore (possible library functions)
                    if not idaapi.has_dummy_name(get_flags_at(
                            start_ea_of(fn))) and not idaapi.get_func_name(
                                start_ea_of(fn)).startswith("_"):
                        all_func += "{} @ 0x{:x}\n".format(
                            idaapi.get_func_name(start_ea_of(fn)),
                            start_ea_of(fn))
                self.outer_self.mixto.AddCommit(all_func,
                                                self.outer_self.mixto.entry_id,
                                                "(IDA) All Functions")

            elif self.menu_title == MenuImports:
                global AllImports
                AllImports = ""
                # Get count of all import modules in the binary
                count = idaapi.get_import_module_qty()

                for i in range(count):
                    module_name = idaapi.get_import_module_name(i)

                    AllImports += "{}:\n".format(module_name)
                    idaapi.enum_import_names(i, imports_cb)
                self.outer_self.mixto.AddCommit(AllImports,
                                                self.outer_self.mixto.entry_id,
                                                "(IDA) All Imports")

            elif self.menu_title == MenuDecFunc:
                addr_current = idc.get_screen_ea()
                addr_func = idaapi.get_func(addr_current)

                if not addr_func:
                    idaapi.msg("Place cursor inside a function!")
                    return False
                else:
                    err = None
                    out = ida_hexrays.decompile_func(addr_func, err)
                    # print(out)
                    self.outer_self.mixto.AddCommit(
                        str(out),
                        self.outer_self.mixto.entry_id,
                        "(IDA) Function Decompilation",
                    )

            elif self.menu_title == MenuExports:
                all_exports = ""
                for entry in idautils.Entries():
                    _, ord, ea, name = entry
                    if not name:
                        all_exports += "0x{:x}: ord#{}\n".format(ea, ord)
                    else:
                        all_exports += "0x{:x}: {} ord#{}\n".format(
                            ea, name, ord)
                self.outer_self.mixto.AddCommit(all_exports,
                                                self.outer_self.mixto.entry_id,
                                                "(IDA) All Exports")

            elif self.menu_title == MenuAllComments:
                raise NotImplementedError("Comments not yet implemented TODO")

            return True
예제 #25
0
 def get_chooser_item_attrs(self, chooser, n, attrs):
     func = idaapi.getn_func(n)
     if bai_mark.is_bai_func(func.start_ea):
         attrs.color = bai_mark.color
예제 #26
0
 def byAddress(cls, ea):
     n = idaapi.get_fchunk_num(ea)
     f = idaapi.getn_func(n)
     return cls.getIndex(n)