def main(self):
     print "\n[+]Launching..."
     try:
         for i in idautils.Functions():
             self.get_strings_per_function(i)
         entropy = truediv(self.string_counter, idaapi.get_func_qty()) * 100
         print "\n[+]Well done! Added {} strings in {} functions ({:.2f}%)".format(
             self.string_counter, idaapi.get_func_qty(), entropy)
     except KeyboardInterrupt:
         print "\n[+]Ended by user"
Esempio n. 2
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())
 def main(self):
     print("\n[+]Launching...")
     try:
         for i in idautils.Functions():
             self.get_strings_per_function(i)
         print("\n[+]Well done! Added {} strings in {} functions".format(
             self.string_counter, idaapi.get_func_qty()))
     except KeyboardInterrupt:
         print("\n[+]Ended by user")
Esempio n. 4
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())
Esempio n. 5
0
def idb_to_mega(filename):
    """Convert IDB to mega file."""
    mode = "w"
    # File already exists
    if os.path.exists(filename):
        ask = idaapi.askyn_c(False, "Append result to existing file?")
        if ask == -1:
            return
        elif ask == 0:
            if 1 != idaapi.askyn_c(False, "Overwrite existing file?"):
                return
        elif ask == 1:
            mode = "a+"
    # Process functions
    with open(filename, mode) as f:
        for i in range(idaapi.get_func_qty()):
            line = process_func(i)
            if line:
                line += "\n"
                f.write(line)
Esempio n. 6
0
def get_all_funcs():
    for idx in range(idaapi.get_func_qty()):
        f = idaapi.getn_func(idx)
        yield f
Esempio n. 7
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
Esempio n. 8
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
Esempio n. 9
0
def make_func_sigs(config):
    logger = logging.getLogger("idb2pat:make_func_sigs")
    sigs = []
    if config.mode == USER_SELECT_FUNCTION:
        f = idaapi.choose_func("Choose Function:", idc.BADADDR)
        if f is None:
            logger.error("No function selected")
            return []
        idc.jumpto(f.start_ea)
        if not idaapi.has_any_name(idc.get_full_flags(f.start_ea)):
            logger.error("Function doesn't have a name")
            return []

        try:
            sigs.append(make_func_sig(config, f))
        except Exception as e:
            logger.exception(e)
            logger.error("Failed to create signature for function at %s (%s)",
                         hex(f.start_ea),
                         idc.get_func_name(f.start_ea) or "")

    elif config.mode == NON_AUTO_FUNCTIONS:
        for f in get_functions():
            # HTC - remove check FUNC_LIB flag to include library functions
            if idaapi.has_name(idc.get_full_flags(f.start_ea)):
                # and f.flags & idc.FUNC_LIB == 0:
                try:
                    sigs.append(make_func_sig(config, f))
                except FuncTooShortException:
                    pass
                except Exception as e:
                    logger.exception(e)
                    logger.error(
                        "Failed to create signature for function at %s (%s)",
                        hex(f.start_ea),
                        idc.get_name(f.start_ea) or "")

    elif config.mode == LIBRARY_FUNCTIONS:
        for f in get_functions():
            if idaapi.has_name(idc.get_full_flags(
                    f.start_ea)) and f.flags & idc.FUNC_LIB != 0:
                try:
                    sigs.append(make_func_sig(config, f))
                except FuncTooShortException:
                    pass
                except Exception as e:
                    logger.exception(e)
                    logger.error(
                        "Failed to create signature for function at %s (%s)",
                        hex(f.start_ea),
                        idc.get_name(f.start_ea) or "")

    elif config.mode == PUBLIC_FUNCTIONS:
        for f in get_functions():
            if idaapi.is_public_name(f.start_ea):
                try:
                    sigs.append(make_func_sig(config, f))
                except FuncTooShortException:
                    pass
                except Exception as e:
                    logger.exception(e)
                    logger.error(
                        "Failed to create signature for function at %s (%s)",
                        hex(f.start_ea),
                        idc.get_name(f.start_ea) or "")

    elif config.mode == ENTRY_POINT_FUNCTIONS:
        for i in zrange(idaapi.get_func_qty()):
            f = idaapi.get_func(idaapi.get_entry(idaapi.get_entry_ordinal(i)))
            if f is not None:
                try:
                    sigs.append(make_func_sig(config, f))
                except FuncTooShortException:
                    pass
                except Exception as e:
                    logger.exception(e)
                    logger.error(
                        "Failed to create signature for function at %s (%s)",
                        hex(f.start_ea),
                        idc.get_name(f.start_ea) or "")

    elif config.mode == ALL_FUNCTIONS:
        n = idaapi.get_func_qty()
        for i, f in enumerate(get_functions()):
            try:
                logger.info("[ %d / %d ] %s %s", i + 1, n,
                            idc.get_name(f.start_ea), hex(f.start_ea))
                sigs.append(make_func_sig(config, f))
            except FuncTooShortException:
                pass
            except Exception as e:
                logger.exception(e)
                logger.error(
                    "Failed to create signature for function at %s (%s)",
                    hex(f.start_ea),
                    idc.get_name(f.start_ea) or "")

    return sigs
Esempio n. 10
0
def get_functions():
    for i in zrange(idaapi.get_func_qty()):
        yield idaapi.getn_func(i)