예제 #1
0
파일: DataParser.py 프로젝트: 453483289/DIE
    def loadPlugins(self):
        """
        Load\Reload all plugins found in the plugin location.
        """
        self.logger.info("Loading Plugins from %s", self.pluginLocation)

        self.pManager.collectPlugins()

        all_plugins = self.pManager.getAllPlugins()
        if len(all_plugins) == 0:
            idaapi.msg("Warning - No Plugins were loaded!\n")
            self.logger.error("No plugins were loaded")

        for pluginInfo in all_plugins:

            # TODO: Validate plugins!
            self.logger.info("Loading plugin %s", pluginInfo.name)

            if pluginInfo.name == "headers":
                # headers is an illegal plugin name (see get_parser_list)
                continue

            # Set a type name normalizing function
            pluginInfo.plugin_object.initPlugin(self.typeName_norm)
            self.pManager.activatePluginByName(pluginInfo.name)

            # Add type to type_parser dict for quick lookups
            suported_types = pluginInfo.plugin_object.getSupportedTypes()

            if suported_types is not None:
                self.addTypeParser(suported_types, pluginInfo.plugin_object)
예제 #2
0
def show_current_function_meaningful():
    try:
        function = sark.Function(idc.here())
        show_meaningful_in_function(function)

    except sark.exceptions.SarkNoFunction:
        idaapi.msg("[FunctionStrings] No function at 0x{:08X}.\n".format(idc.here()))
예제 #3
0
    def highlight_item_row(self, item):
        """
        highlight the entire row containing a table item
        @param item: table item
        """
        try:
            if not item.index().isValid():
                return

            parent = item.parent()
            if parent is None:
                parent = item

            if not parent.hasChildren():
                self.highlight_item(parent)
                return

            row = item.row()
            column_num = parent.columnCount()

            for column in xrange(0, column_num):
                if self.valueModel.hasIndex(row, column, parent.index()):
                    cur_index = self.valueModel.index(row, column, parent.index())

                    self.highlight_item(self.valueModel.itemFromIndex(cur_index))
                    persistent_index = QtCore.QPersistentModelIndex(cur_index)
                    self.highligthed_items.append(persistent_index)

        except Exception as ex:
            idaapi.msg("Error while highlighting item row: %s\n" % ex)
예제 #4
0
파일: qira.py 프로젝트: Maroc-OS/qira
 def qsjump_to(self, qs_ea):
     try:
         self.qira.jump_to(qs_ea)
     except AttributeError:
         idaapi.msg(
             "[%s] qsjump_to : Addr is not valid (%s)\n" %
             (self.qira.wanted_name, qs_ea,))
예제 #5
0
파일: qira.py 프로젝트: Maroc-OS/qira
 def qs_send_msg(self, qs_msg):
     try:
         self.qira.ws_send(qs_msg)
     except AttributeError:
         idaapi.msg(
             "[%s] qs_send_msg : Cannot send message (%s)\n" %
             (self.qira.wanted_name, qs_msg,))
예제 #6
0
파일: autoenum.py 프로젝트: ababook/Sark
    def run(self, arg):
        common_value = get_common_value()

        enum_name = idc.AskStr(self._last_enum, "Enum Name")
        if enum_name is None:
            return

        if not enum_name:
            enum_name = None

        self._last_enum = enum_name

        # Can't ask with negative numbers.
        if common_value >> ((8 * sark.core.get_native_size()) - 1):
            common_value = 0

        const_value = idc.AskLong(common_value, "Const Value")
        if const_value is None:
            return

        modify = True

        try:
            enum = sark.add_enum(enum_name)

        except sark.exceptions.EnumAlreadyExists:
            enum = sark.Enum(enum_name)
            yes_no_cancel = idc.AskYN(idaapi.ASKBTN_NO,
                                      "Enum already exists. Modify?\n")
            if yes_no_cancel == idaapi.ASKBTN_CANCEL:
                return

            elif yes_no_cancel == idaapi.ASKBTN_YES:
                modify = True

            else:  # yes_no_cancel == idaapi.ASKBTN_NO:
                modify = False


        member_name = const_name(enum, const_value)

        if modify:

            try:
                enum.members.add(member_name, const_value)
            except sark.exceptions.SarkErrorAddEnumMemeberFailed as ex:
                idaapi.msg("[AutoEnum] Adding enum member failed: {}.".format(ex.message))


        else:
            for member in enum.members:
                if member.value == const_value:
                    member_name = member.name
                    break
                else:
                    return


        # Apply the enum
        apply_enum_by_name(enum, member_name)
예제 #7
0
파일: qira.py 프로젝트: Maroc-OS/qira
 def term(self):
     idaapi.msg("[%s] Terminating tasks...\n" % (self.wanted_name,))
     try:
         self.stop()
     except AttributeError:
         pass
     idaapi.msg("[%s] Uninstalled!\n" % (self.wanted_name,))
예제 #8
0
    def find_context_list(self, context_list):
        """
        Find and highlight a list of function contexts
        @param context_list: list of function contexts (of type dbFunction_Context)
        """
        try:
            self.clear_highlights()
            root_index = self.functionModel.index(0, 0)
            if not root_index.isValid():
                return

            for func_context in context_list:
                context_id = id(func_context)
                matched_items = self.functionModel.match(root_index, DIE.UI.ContextId_Role, context_id, -1, QtCore.Qt.MatchFlag.MatchRecursive|QtCore.Qt.MatchFlag.MatchExactly)

                for index in matched_items:
                    if not index.isValid():
                        continue
                    # Do not highlight "ea root" items, only occurrences of it.
                    if not index.data().startswith("Occur"):
                        continue

                    item = self.functionModel.itemFromIndex(index)
                    self.functionTreeView.expand(index)
                    self.functionTreeView.scrollTo(index, QtGui.QAbstractItemView.ScrollHint.PositionAtTop)
                    self.highlight_item_row(item)

            return True

        except Exception as ex:
            idaapi.msg("Error while looking up function context in FunctionView: %s\n" % ex)
            return False
예제 #9
0
파일: qira.py 프로젝트: Maroc-OS/qira
 def ws_send(self, msg):
     if self.wsserver is not None:
         self.start()
     if msg is not None:
         if msg == 'connected':
             for conn in list(CLIENTS):
                 conn.sendMessage(msg)
                 time.sleep(1)
             CLIENTS.append(self)
         elif msg == 'closed':
             CLIENTS.remove(self)
             for conn in list(CLIENTS):
                 conn.sendMessage(msg)
                 time.sleep(1)
         else:
             # print "Tuple: %s" % (self.wsserver.connections.items(),)
             # This one still have errors in both items()/CLIENTS
             for conn in list(self.wsserver.connections.items()):
                 if conn != self:
                     # debugging
                     if DEBUG:
                         idaapi.msg("[%s] ws_send : %s\n" % (self.wanted_name, msg,))
                     conn.sendMessage(msg)
                 time.sleep(0.1)
     else:
         idaapi.msg("[%s] ws_send : Cannot send null\n" % (self.comment,))
예제 #10
0
    def _insert_thread_data(self, item, thread_id):
        """
        Insert thread_id data into a model item.
        The value found in thread_id argument will be delimited by the _make_thread_id_data function
        (e.g: thread_id 123 will become 't123t')
        the delimited value will then be appended to a string of concatenated (unique) child-item thread-ids
        (for example a item data value can be "a123aa5672aa11112a") for threads 123, 5672 and 111112
        @param item: the model item to add the data to
        @param thread_id: thread_id number
        @return: True if thread data was successfully added to item, otherwise False
        """
        try:
            current_thread_id = self._make_thread_id_data(thread_id)
            thread_data = item.data(role=DIE.UI.ThreadId_Role)


            if thread_data is None:
                item.setData(current_thread_id, role=DIE.UI.ThreadId_Role)

            elif not current_thread_id in thread_data:
                item.setData(thread_data + current_thread_id, role=DIE.UI.ThreadId_Role)

            return True

        except Exception as ex:
            idaapi.msg("Error while inserting thread data: %s\n" %ex)
            return False
예제 #11
0
파일: DIE.py 프로젝트: 453483289/DIE
    def __init__(self, is_dbg_log=False, is_dbg_pause=False, is_dbg_profile=False):

        ### Logging ###

        log_filename = os.path.join(os.getcwd(), "DIE.log")

        self._menu = sark.qt.MenuManager()

        #TODO: Fix logging to include rotating_file_handler \ console_logging
        if is_dbg_log:
            logging.basicConfig(filename=log_filename,
                        level=logging.DEBUG,
                        format='[%(asctime)s] [%(levelname)s] [%(name)s][%(filename)s:%(lineno)s] : %(message)s')
        else:
             logging.basicConfig(filename=log_filename,
                    level=logging.INFO,
                    format='[%(asctime)s] [%(levelname)s] [%(name)s][%(filename)s:%(lineno)s] : %(message)s')

        idaapi.msg("Logfile created at %s\n" % log_filename)
        self.logger = logging.getLogger(__name__)

        ### DIE Configuration ###
        self.config_file_name = os.path.join(os.getcwd(), "DIE.cfg")
        DIE.Lib.DieConfig.initialize()
        config = DIE.Lib.DieConfig.get_config()
        try:
            config.load(self.config_file_name)
        except IOError:
            pass

        except:
            import traceback
            idaapi.msg(traceback.format_exc())

        self.die_config = config


        self.addmenu_item_ctxs = []
        self.icon_list = {}

        self.debugAPI = DebugAPI.DebugHooker(is_dbg_pause, is_dbg_profile)
        DIE.Lib.DIEDb.initialize_db()
        self.die_db = DIE.Lib.DIEDb.get_db()

        self.is_marked = False

        DIE.UI.FunctionViewEx.initialize()
        DIE.UI.ValueViewEx.initialize()
        DIE.UI.BPView.initialize()
        DIE.UI.ParserView.initialize()
        DIE.UI.Die_Icons.initlialize()
        self.function_view = DIE.UI.FunctionViewEx.get_view()
        self.value_view = DIE.UI.ValueViewEx.get_view()
        self.bp_view = DIE.UI.BPView.get_view()
        self.parser_view = DIE.UI.ParserView.get_view()

        self.load_icons()

        return
예제 #12
0
파일: qira.py 프로젝트: heartbleeded/qira
  def init(self):
    self.old_addr = None
    self.addr = None

    threading.Thread(target=start_server).start()
    idaapi.msg("[QIRA Plugin] Ready to go!\n")

    return idaapi.PLUGIN_KEEP
예제 #13
0
 def activate(self, ctx):
     try:
         self._activate(ctx)
         return 1
     except:
         trace = traceback.format_exc()
         idaapi.msg("Action {!r} failed to activate. Traceback:\n{}".format(self.get_name(), trace))
         return 0
예제 #14
0
        def _activate(self, ctx):
            clear_func(ctx.cur_ea)
            mark_exit_nodes(ctx.cur_ea)

            idaapi.msg("\n" * 2)

            for block in iter_exit_nodes(ctx.cur_ea):
                idaapi.msg("Exit at 0x{:08X}\n".format(block.startEA))
예제 #15
0
파일: qira.py 프로젝트: Maroc-OS/qira
 def update_address(self, addr_type, addr):
     if (addr_type is not None) and (addr is not None):
         self.cmd = "set%s 0x%x" % (addr_type, addr)
         self.ws_send(self.cmd)
     else:
         idaapi.msg(
             "[%s] Cannot update address: 'None'\n" %
             (self.wanted_name,))
예제 #16
0
파일: idaref.py 프로젝트: nologic/idaref
    def term(self):
        idaapi.msg("Terminating %s\n" % self.wanted_name)
        try:
            self.stop()
        except:
            pass

        for ctx in self.ctxs:
            idaapi.del_menu_item(ctx)
예제 #17
0
파일: idaref.py 프로젝트: nologic/idaref
    def stop(self, *args):
        global insref_g
        idaapi.msg("Stopping IdaRef\n")

        if(insref_g != None):
            insref_g.destroy()
            insref_g = None
        else:
            print "IdaRef is not running"
예제 #18
0
파일: idaref.py 프로젝트: nologic/idaref
 def _add_menu(self, *args):
     ctx = idaapi.add_menu_item(*args)
         
     if ctx is None:
         idaapi.msg("Add failed!\n")
         return False
     else:
         self.ctxs.append(ctx)
         return True
예제 #19
0
    def mark_exists():
        ea = idaapi.get_screen_ea()
        clear_func(ea)
        mark_exit_nodes(ea)

        idaapi.msg("\n" * 2)

        for block in iter_exit_nodes(ea):
            idaapi.msg("Exit at 0x{:08X}\n".format(block.startEA))
예제 #20
0
파일: qira.py 프로젝트: heartbleeded/qira
 def handleMessage(self):
   #idaapi.msg("[QIRA Plugin] Received from QIRA web: %s\n" % (self.data,))
   dat = self.data.split(" ")
   if dat[0] == "setaddress" and dat[1] != "undefined":
     try:
       a = idaapi.toEA(0, int(str(dat[1][2:]),16))
       jump_to(a)
     except e:
       idaapi.msg("[QIRA Plugin] Error processing the address\n")
예제 #21
0
파일: qira.py 프로젝트: Maroc-OS/qira
 def ws_server(self, port):
     if port is None:
         port = self.port
     host = ''
     self.wsserver = SimpleWebSocketServer(host, port, QiraServer, selectInterval=0.1)
     if self.wsserver is not None:
         idaapi.msg("[%s] Starting WS Server\n" % (self.comment,))
         self.wsserver.serveforever()
     else:
         idaapi.msg("[%s] Cannot Start WS Server\n" % (self.comment,))
예제 #22
0
def s_send(msg):
  #idaapi.msg("[i2q Plugin] s_send start\n")
  try:
    s = socket.socket()
    host = "127.0.0.1"
    port = 3001
  
    s.connect((host, port))
  except Exception, e:
    idaapi.msg("[i2q Plugin] conn failed : %s\n" % e)
예제 #23
0
	def OneProfMakeFuncs(self):
		fname = idc.AskFile(0, '*.*', 'Select profile file, plz')
		prof = open(fname, 'rb')
		binprofile = prof.read().split('\n\n')

		binprof = self.kern.analyze_callgr_profile(binprofile)
		idaapi.msg("Tryind add funcs...\n")
		num = self.kern.make_funcs_from_prof(binprof)
		idc.Warning("%d funcs was added" % num)
		return True
예제 #24
0
파일: idaref.py 프로젝트: nologic/idaref
    def start(self, *args):
        global insref_g
        idaapi.msg("Starting IdaRef\n")
        
        if(insref_g != None and idaapi.find_tform(insref_g.title) == None):
            self.stop()

        if(insref_g == None):
            insref_g = InstructionReference(self)
        else:
            print "IdaRef Already started"
예제 #25
0
파일: Die_Icons.py 프로젝트: 453483289/DIE
    def __init__(self, icons_path="icons"):

        self.die_config = DieConfig.get_config()

        self.icons_path = self.die_config.icons_path

        if not os.path.exists(self.icons_path):
            idaapi.msg("Error: could not locate DIE icons directory.\n")
            return

        self._load_icons()
예제 #26
0
파일: idaref.py 프로젝트: nologic/idaref
    def init(self):
        global initialized
        ret = idaapi.PLUGIN_SKIP
        if initialized == False:
            initialized = True
            self.ctxs = []
            insref_g = None
            ret = self._add_menus()
        idaapi.msg("IdaRef initialized\n")

        return ret
예제 #27
0
def show_highlighted_function_strings():
    identifier = idaapi.get_highlighted_identifier()
    if not identifier:
        return

    try:
        function = sark.Function(name=identifier)
        show_function_strings(function)

    except sark.exceptions.SarkNoFunction:
        idaapi.msg("[FunctionStrings] {!r} is not a function.\n".format(identifier))
예제 #28
0
파일: qira.py 프로젝트: Maroc-OS/qira
 def send_names(self):
     qira_names = idaapi.get_nlist_size()
     for i in range(0, qira_names):
         self.cmd = "setname 0x%x %s" % (
             idaapi.get_nlist_ea(i), idaapi.get_nlist_name(i))
         # debugging
         if DEBUG:
             idaapi.msg(
                 "[%s] send_names: EA [0x%x], Name [%s]\n" %
                 (self.wanted_name, idaapi.get_nlist_ea(i),
                  idaapi.get_nlist_name(i),))
         self.ws_send(self.cmd)
예제 #29
0
파일: ui.py 프로젝트: zshwuhan/Sark
    def _get_handler(self, node_id):
        """Get the handler of a given node."""
        handler = self._get_attrs(node_id).get(self.HANDLER, self._default_handler)

        # Here we make sure the handler is an instance of `BasicNodeHandler` or inherited
        # types. While generally being bad Python practice, we still need it here as an
        # invalid handler can cause IDA to crash.
        if not isinstance(handler, BasicNodeHandler):
            idaapi.msg(("Invalid handler for node {}: {}. All handlers must inherit from"
                        "`BasicNodeHandler`.").format(node_id, handler))
            handler = self._default_handler
        return handler
예제 #30
0
    def init(self):

        try:
            self._install_plugin()
            idaapi.msg("RECLASSIFY load complete.\n")

        # failed to initialize or integrate the plugin, log and skip loading
        except Exception as e:
            form = idaapi.get_current_tform()
            print e

        return idaapi.PLUGIN_KEEP
예제 #31
0
파일: idasec.py 프로젝트: wgwjifeng/idasec
def main():
    idaapi.msg("Loading IDASEC\n")
    global IDASEC
    try:
        IDASEC
        IDASEC.OnClose(IDASEC)
        idaapi.msg("reloading IDASec\n")
        IDASEC = IDASecForm()
        return
    except Exception:
        IDASEC = IDASecForm()
    IDASEC.Show("Idasec")
예제 #32
0
def handle_message_queue():
  global msg_queue
  while len(msg_queue) > 0:
    dat = msg_queue[0].split(" ")
    msg_queue = msg_queue[1:]

    if dat[0] == "setaddress" and dat[1] != "undefined":
      try:
        a = idaapi.toEA(0, int(str(dat[1][2:]),16))
        jump_to(a)
      except e:
        idaapi.msg("[QIRA Plugin] Error processing the address\n")
예제 #33
0
파일: ui.py 프로젝트: IoanFilip2/Sark
 def _get_handler(self, node_id):
     """Get the handler of a given node."""
     handler = self._get_attrs(node_id).get(self.HANDLER, self._default_handler)
     
     # Here we make sure the handler is an instance of `BasicNodeHandler` or inherited
     # types. While generally being bad Python practice, we still need it here as an
     # invalid handler can cause IDA to crash.
     if not isinstance(handler, BasicNodeHandler):
         idaapi.msg(("Invalid handler for node {}: {}. All handlers must inherit from"
                    "`BasicNodeHandler`.").format(node_id, handler))
         handler = self._default_handler
     return handler
예제 #34
0
	def init(self):
		idaapi.msg("Sunrace init [ . ]\n")
		self.menus = list()
		self.kern = Kernel()
		self.ColorFuncsView = None
		self.is_reanalyse = False
		self.is_singleprofile = False
		self.is_twoprofile = False
		self.singlname = ''
		self.fname = ''
		self.sname = ''
		return idaapi.PLUGIN_KEEP
예제 #35
0
    def init(self):
        """
        初始化方法
        """
        idaapi.msg(">>> jack sparrow util plugin starts. {0}\n".format(
            datetime.now()))

        # 导入python目录下的功能模块
        idaapi.require("util")
        idaapi.require("util.plugin_util_impl")

        return idaapi.PLUGIN_OK  # return PLUGIN_KEEP
예제 #36
0
파일: vds5.py 프로젝트: patois/vds5plugin
    def init(self):
        self.vds5_hooks = None
        if not ida_hexrays.init_hexrays_plugin():
            idaapi.msg("hexrays-graph: hexrays is not available.")
            return idaapi.PLUGIN_SKIP

        ida_kernwin.register_action(
            ida_kernwin.action_desc_t(ACTION_NAME,
                                      "Hex-Rays show C graph (IDAPython)",
                                      display_graph_ah_t(), ACTION_SHORTCUT))
        self.vds5_hooks = vds5_hooks_t()
        self.vds5_hooks.hook()
        return idaapi.PLUGIN_KEEP
예제 #37
0
    def term(self):
        """
        This is called by IDA when it is unloading the plugin.
        """

        # unhook our plugin hooks
        self._hooks.unhook()

        # unregister our actions & free their resources
        self._del_action_google_search()

        # done
        idaapi.msg("%s terminated...\n" % self.wanted_name)
예제 #38
0
 def run(self, arg):
     try:
         idaapi.msg("StackStrings run() called with %d!\n" % arg)
         if is_py2:
             flare.stackstrings.main()
             idaapi.msg("StackStrings run() done")
         else:
             idaapi.msg("WARNING: stackstrings only works under python2 due to vivisect dependency\n")
     except Exception as err:
         idaapi.msg("Exception during run: %s\n" % str(err))
         raise
         
     idaapi.msg("StackStrings run() complete!\n")
예제 #39
0
    def initPlugin(self, type_norm_callback=None):
        """
        Plguin Initialization
        @param type_norm_callback: a type name normalization callback function
        """
        idaapi.msg("Initializing plugin %s\n" % self.__class__)

        # Set type name normalization callback function
        if type_norm_callback is not None:
            self.typeName_norm_cb = type_norm_callback

        # Register supported types
        self.registerSupportedTypes()
예제 #40
0
def s_send(msg):
    idaapi.msg("[q2i]s_send start\n")
    s = socket.socket()
    #host = socket.gethostname()
    host = "127.0.0.1"
    port = 3001
    s.connect((host, port))
    #idaapi.msg("[q2i Plugin]send msg : " + msg + "\n")
    s.send(msg)
    result = s.recv(1024)
    #idaapi.msg("[q2i Plugin]recv msg " + result + "\n" )
    parse_msg(result)
    s.close
예제 #41
0
def move_segm(frm, to, sz, fileformatname):
    idaapi.msg("move_segm(from=%s, to=%s, sz=%d, formatname=%s" %
               (hex(frm), hex(to), sz, fileformatname))

    gNode = idaapi.netnode()
    gNode.create(NETNODE_NAME)
    dBlob = gNode.getblob(0, 'D')
    dwords = [
        struct.unpack_from("<l", dBlob, x) for x in xrange(0, len(dBlob), 4)
    ]
    do_relocs(dwords, frm, to)

    return 1
예제 #42
0
    def init(self):
        """
        This is called by IDA when it is loading the plugin.
        """

        # initialize the menu actions our plugin will inject
        self._init_action_google_search()

        # initialize plugin hooks
        self._init_hooks()
        idaapi.msg("%s %s initialized...\n" % (self.wanted_name, VERSION))

        return idaapi.PLUGIN_KEEP
예제 #43
0
    def highlight_item(self, item):
        """
        Highlight a single item
        @param item: module item
        """
        try:
            item.setBackground(QtGui.QColor('yellow'))
            cur_font = item.font()
            cur_font.setBold(True)
            item.setFont(cur_font)

        except Exception as ex:
            idaapi.msg("Error while highlighting item: %s\n" % ex)
예제 #44
0
    def init(self):
        idaapi.msg('[%s] init. press CTRL+ALT+S in a function.' %
                   (self.plg_name))

        act_desc = idaapi.action_desc_t(self.act_name, self.plg_name,
                                        STLCommentHandler(), None,
                                        self.act_tooltip)

        idaapi.register_action(act_desc)
        idaapi.attach_action_to_menu(self.menu_category, self.act_name,
                                     idaapi.SETMENU_APP)

        return self.flags
예제 #45
0
    def term(self):
        if not hasattr(self, '_hooks'):
            return

        # unhook our plugin hooks
        self._hooks.unhook()

        # unregister our actions & free their resources
        self._del_action_bulk()
        self._del_action_copy()

        # done
        idaapi.msg("%s terminated...\n" % self.wanted_name)
예제 #46
0
    def OnSelectLine(self, n):
        self.selcount += 1
        func_addr = int(self.items[n][0], 16)
        func_name = self.items[n][1]

        t_addrs = self.function_to_addrs[func_addr]
        idaapi.msg("%d tainted instructions in %s\n" % \
                       (len(t_addrs), func_name))

        for tainted_addr in t_addrs:
            idaapi.set_item_color(tainted_addr, TAINTED)

        idaapi.jumpto(func_addr)
예제 #47
0
    def run(self, arg):
        idaapi.msg("[i2q Plugin] Syncing ...\n")
        self.addr = idaapi.get_screen_ea()

        if (self.old_addr != self.addr):
            if (idaapi.isCode(idaapi.getFlags(self.addr))):
                #idaapi.msg("[i2q Plugin] update instrunction address\n")
                update_address("iaddr", self.addr)
            else:
                # Data Address
                #idaapi.msg("[i2q Plugin] update data address\n")
                update_address("daddr", self.addr)
        self.old_addr = self.addr
예제 #48
0
    def prepare_debug_ui(self):
        wd = WaitDialog()
        idaapi.msg("[%s] waiting...\n" % (PLUGNAME))
        wd.thread.start()
        wd.exec_()

        target_pid = wd.get_target_pid()
        if target_pid != -1:
            ida_dbg.attach_process(target_pid, -1)
            idc.GetDebuggerEvent(idc.WFNE_SUSP, -1)
            ida_dbg.continue_process()
        else:
            idaapi.msg("[%s] exit waiting\n" % (PLUGNAME))
예제 #49
0
def main():

    idaapi.msg("Loading AFL_Node_Extract\n")

    global g_num_edge
    global g_dict_func_edge
    global g_off_set_random
    global g_size_ins_block
    global g_off_random

    dict_func_edge = {}

    if idc.__EA64__:  # 64bit
        g_off_set_random = 0x16
        g_size_ins_block = 0x38
        g_off_random = 3
    else:  # 32bit
        g_off_set_random = 3
        g_size_ins_block = 0x10
        g_off_random = 1

    #func = 0x80E3440
    #print('%d %d') % (func, idc.GetFunctionAttr(func, idc.FUNCATTR_END))
    #HandleFunc(func)

    #for func in idautils.Functions():
    #    g_num_edge = 0
    #    HandleFunc(func)
    #    dict_func_edge[func] = g_num_edge

    g_dict_func_edge = dict_func_edge
    for func in idautils.Functions():
        if IsSanFunc(func):
            continue
        print('%d %s') % (func, idc.GetFunctionName(func))
        HandleFunc(func)

    try:
        #for func in idautils.Functions():
        #    Find__afl_maybe_log(func, idc.GetFunctionAttr(func, idc.FUNCATTR_END)) #print hex(func), idc.GetFunctionName(func)

        #func = 0x804F2A0
        #print('%d %d') % (func, idc.GetFunctionAttr(func, idc.FUNCATTR_END))
        #HandleFunc(func)
        pass
    except Exception:
        pass

    g_f.write('analyse time: ' + str(time.time() - g_time_start) + 's\n')
    g_f.close()
    print('analyse time: ' + str(time.time() - g_time_start) + 's\n')
예제 #50
0
    def run(self):
        '''Start the plugin.'''

        if not idaapi.init_hexrays_plugin():
            print "HRDEV Error: Failed to initialise Hex-Rays plugin."
            return

        function_name = idaapi.get_func_name(idaapi.get_screen_ea())
        demangled_name = self.tools.demangle_name(function_name)

        src = idaapi.decompile(idaapi.get_screen_ea())

        file_name = '{}.cpp'.format(self.tools.to_file_name(demangled_name))
        cache_path = os.path.sep.join(
            [tempfile.gettempdir(), 'hrdev_cache', self._bin_name])

        # Create required directories if they dont exist
        tmp_dir_path = os.path.sep.join([tempfile.gettempdir(), 'hrdev_cache'])
        if not os.path.isdir(tmp_dir_path):
            os.mkdir(tmp_dir_path)

        if not os.path.isdir(cache_path):
            os.mkdir(cache_path)

        complete_path = os.path.sep.join([cache_path, file_name])
        idaapi.msg("HRDEV cache path: {}\n".format(complete_path))

        # Check if file is already in cache
        if not os.path.isfile(complete_path) or \
           self.config_main.getboolean('etc', 'disable_cache'):
            self.tools.save_file(complete_path, str(src))

        self.tools.set_file_path(complete_path)

        lvars = {}
        for v in src.lvars:
            _type = idaapi.print_tinfo('', 0, 0, idaapi.PRTYPE_1LINE, v.tif,
                                       '', '')
            lvars[str(v.name)] = "{} {} {}".\
                format(_type, str(v.name), str(v.cmt))

        max_title = self.config_main.getint('etc', 'max_title')
        self.gui = hrdev_plugin.include.gui.Canvas(self.config_main,
                                                   self.config_theme,
                                                   self.tools, lvars,
                                                   demangled_name[:max_title])
        self.gui.Show('HRDEV')

        self.parser = hrdev_plugin.include.syntax.Parser(self, lvars)
        self.parser.run(complete_path)
        return
예제 #51
0
파일: DebugAPI.py 프로젝트: waders909/DIE
    def dbg_bpt(self, tid, ea):
        """
        'Hit Debug Breakpoint' Callback -
         this callback gets called once a breakpoint has been reached -
         this means we can either be in a CALL or a RET instruction.
        """
        try:
            # If final breakpoint has been reached. skip all further breakpoints.
            if self.end_bp is not None and ea == self.end_bp:
                self.logger.info("Final breakpoint reached at %s. context logging is stopped.", hex(ea))
                self.bp_handler.unsetBPs()
                request_continue_process()
                run_requests()
                return 0

            # If required, update IAT
            if self.update_imports:
                self.update_iat()

            # Set current call-stack
            if tid not in self.callStack:
                idaapi.msg("Creating new callstack for thread %d\n" % tid)
                self.callStack[tid] = CallStack()

            self.current_callstack = self.callStack[tid]

            # Did we just return from a function call?
            if self.bp_handler.isRetBP(ea):
                try:
                    self.current_callstack.pop()
                except DieCallStackPopError:
                    self.logger.exception("Error while popping function from callstack")

                self.bp_handler.removeRetBP(ea)
                if not is_call(ea):
                    request_continue_process()
                    run_requests()

            # Is this a CALL instruction?
            if is_call(ea):
                self.prev_bp_ea = ea  # Set prev ea
                self.bp_handler.addRetBP(ea)
                if not self.is_dbg_pause:
                    request_step_into()  # Great, step into the called function
                    run_requests()  # Execute dbg_step_into callback.

            return 0

        except Exception as ex:
            self.logger.exception("Failed while handling breakpoint at %s:", ea, ex)
            return 1
예제 #52
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
예제 #53
0
 def startServer(self):
     if self.server != None:
         idaapi.msg(">>> There is a running server\n")
         return
     i = 0
     while True:
         try:
             server = TCPServer(("", RI_BASE_PORT + i), MainTCPHandler)
             self.server = threading.Thread(target=server.serve_forever)
             self.server.start()
             break
         except socket.error:
             i += 1
     idaapi.msg(">>> Start server at port " + str(RI_BASE_PORT + i) + '\n')
예제 #54
0
파일: ESigs.py 프로젝트: newmsk/ESig
 def run(self, arg):
     idaapi.msg("ESigPlugin run")
     e_main_ea = get_E_main()
     if e_main_ea != 0:
         e_sig = E_Sigs(e_main_ea)
         e_sig.set_E_main_name()
         e_sig.load_flirt_sigs()
         e_sig.handle_dll_calls()
         idaapi.jumpto(e_main_ea)
         print("e sig finish")
     else:
         idaapi.msg(
             "Can not find E language main function, the file may not be compiled by E compiler."
         )
예제 #55
0
 def run(self, arg):
   idaapi.msg("[QIRA Plugin] Syncing with Qira\n")
   self.addr = idaapi.get_screen_ea()
   if (self.old_addr != self.addr):
     if (idaapi.isCode(idaapi.getFlags(self.addr))):
       # don't update the address if it's already the qira address
       if (self.addr != qira_address):
         # Instruction Address
         set_qira_address(self.addr)
         update_address("iaddr", self.addr)
     else:
       # Data Address
       update_address("daddr", self.addr)
   self.old_addr = self.addr
예제 #56
0
def show_local_xrefs(arg=None):
    delim = '-' * 86 + '\n'
    header = '\nXrefs to %s from %s:\n'

    global localxrefs
    fmt = ''

    r = LocalXrefs()
    localxrefs = r

    offsets = r.xrefs.keys()
    offsets.sort()

    if r.highlighted:
        idaapi.msg(header % (r.highlighted, r.function))
        idaapi.msg(delim)

        for ea in offsets:
            info = r.xrefs[ea]

            if not fmt:
                fmt = "%%s   %%s   %%-%ds   %%s\n" % (len(info['offset']) + 15)

            idaapi.msg(fmt % (info['direction'], info['type'], info['offset'],
                              info['text']))

        idaapi.msg(delim)
예제 #57
0
    def run(self, arg):
        global localxrefs
        fmt = ''

        r = LocalXrefs()
        localxrefs = r

        offsets = r.xrefs.keys()
        offsets.sort()

        if r.highlighted:
            idaapi.msg(self.HEADER % (r.highlighted, r.function))
            idaapi.msg(self.DELIM)

            for ea in offsets:
                info = r.xrefs[ea]

                if not fmt:
                    fmt = "%%s   %%s   0x%%08X %%-%ds   %%s\n" % (
                        len(info['offset']) + 15)

                idaapi.msg(fmt % (info['direction'], info['type'], info['ea'],
                                  info['offset'], info['text']))

            idaapi.msg(self.DELIM)
예제 #58
0
    def run(self, arg):
        try:
            for ea in idautils.Heads():
                #print(idc.print_operand(ea, 0))
                mnem = idc.print_insn_mnem(ea)

                # color call instructions
                if mnem == 'call':
                    idaapi.set_item_color(ea, self.COLOR_CALL)
                    continue

                # color lea instructions
                if mnem == 'lea':
                    idaapi.set_item_color(ea, self.COLOR_POINTER)
                    continue

                # color suspected crypto instructions
                # xor that does not zero out the register
                if mnem == 'xor' and (idc.print_operand(ea, 0) !=
                                      idc.print_operand(ea, 1)):
                    idaapi.set_item_color(ea, self.COLOR_CRYPTO)
                    continue

                # common RC4 instructions
                if mnem == 'cmp' and idc.get_operand_type(
                        ea, 0) == ida_ua.o_reg and idc.print_operand(
                            ea, 1) == '0x100':
                    idaapi.set_item_color(ea, self.COLOR_CRYPTO)
                    continue

                # misc math operations
                mathInstrList = [
                    'sar', 'sal', 'shr', 'shl', 'ror', 'rol', 'idiv', 'div',
                    'imul', 'mul', 'not'
                ]
                if mnem in mathInstrList:
                    idaapi.set_item_color(ea, self.COLOR_CRYPTO)
                    continue

                # color string operations
                # skip instructions that start with 'c' to exclude conditional moves, e.g. cmovs
                if (mnem.startswith('c') == False) and (mnem.endswith('x') == False) and \
                    (('scas' in mnem) or ('movs' in mnem) or ('stos' in mnem)):
                    idaapi.set_item_color(ea, self.COLOR_STRING_OPERATION)
                    continue

        except Exception as err:
            idaapi.msg("Exception during run: %s\n" % str(err))
            raise
예제 #59
0
    def init(self):
        # just go when we have hexrays
        if not idaapi.init_hexrays_plugin():
            return idaapi.PLUGIN_SKIP

        # initialize the menu actions our plugin will inject
        self._init_action_bulk()
        self._init_action_copy()

        # initialize plugin hooks
        self._init_hooks()

        # done
        idaapi.msg("%s %s initialized...\n" % (self.wanted_name, VERSION))
        return idaapi.PLUGIN_KEEP
예제 #60
0
파일: DIE.py 프로젝트: waders909/DIE
    def init(self):
        try:
            # For Debugging:
            #self.die_manager = DieManager(is_dbg_log=True, is_dbg_pause=False, is_dbg_profile=True)
            self.die_manager = DieManager()
            self.die_manager.add_menu_items()
            self.die_manager.show_logo()
            return idaapi.PLUGIN_KEEP

        except Exception as ex:
            idaapi.msg("Failed to initialize DIE. {}\n".format(ex))
            self.die_manager.del_menu_items()
            del self.die_manager
            idaapi.msg("Errors and fun!\n")
            return idaapi.PLUGIN_SKIP