Example #1
0
 def clear_output_window():
     if Util.is_ida70():
         from PyQt5 import QtGui, QtCore, QtWidgets
         form = idaapi.find_tform("Output window")
         w = idaapi.PluginForm.FormToPyQtWidget(form)
         w.setFocus()
     else:
         from PySide import QtGui, QtCore
         form = idaapi.find_tform("Output window")
         w = idaapi.PluginForm.FormToPySideWidget(form)
         w.setFocus()
     idaapi.process_ui_action("msglist:Clear")
Example #2
0
def get_disas_bg_color_ida6():
    """
    Get the background color of an IDA disassembly view. (IDA 6.x)
    """

    # find a form (eg, IDA view) to steal a pixel from
    for i in xrange(5):
        form = idaapi.find_tform("IDA View-%c" % chr(ord('A') + i))
        if form:
            break
    else:
        raise RuntimeError("Failed to find donor IDA View")

    # locate the Qt Widget for an IDA View form and take 2px tall screenshot
    if using_pyqt5:
        widget = idaapi.PluginForm.FormToPyQtWidget(form)
        pixmap = widget.grab(QtCore.QRect(0, 0, widget.width(), 2))
    else:
        widget = idaapi.PluginForm.FormToPySideWidget(form)
        region = QtCore.QRect(0, 0, widget.width(), 2)
        pixmap = QtGui.QPixmap.grabWidget(widget, region)

    # extract 1 pixel like a pleb (hopefully a background pixel :|)
    img = QtGui.QImage(pixmap.toImage())
    color = QtGui.QColor(img.pixel(img.width() / 2, 1))

    # return the color of the pixel we extracted
    return color
Example #3
0
def get_widget(title):
    """Get the Qt widget of the IDA window with the given title."""
    tform = idaapi.find_tform(title)
    if not tform:
        return

    return idaapi.PluginForm.FormToPySideWidget(tform)
Example #4
0
def get_ida_bg_color_ida6():
    """
    Get the background color of an IDA disassembly view. (IDA 6.x)
    """
    names  = ["Enums", "Structures"]
    names += ["Hex View-%u" % i for i in range(5)]
    names += ["IDA View-%c" % chr(ord('A') + i) for i in range(5)]

    # find a form (eg, IDA view) to analyze colors from
    for window_name in names:
        form = idaapi.find_tform(window_name)
        if form:
            break
    else:
        raise RuntimeError("Failed to find donor View")

    # touch the target form so we know it is populated
    touch_window(form)

    # locate the Qt Widget for a form and take 1px image slice of it
    if using_pyqt5:
        widget = idaapi.PluginForm.FormToPyQtWidget(form)
        pixmap = widget.grab(QtCore.QRect(0, 10, widget.width(), 1))
    else:
        widget = idaapi.PluginForm.FormToPySideWidget(form)
        region = QtCore.QRect(0, 10, widget.width(), 1)
        pixmap = QtGui.QPixmap.grabWidget(widget, region)

    # convert the raw pixmap into an image (easier to interface with)
    image = QtGui.QImage(pixmap.toImage())

    # return the predicted background color
    return QtGui.QColor(predict_bg_color(image))
Example #5
0
def get_disas_bg_color():
    """
    Get the background color of the disas text area via pixel... YOLO

    PS: please expose the get_graph_color(...) palette accessor, Ilfak ;_;
    """

    # find a form (eg, IDA view) to steal a pixel from
    for i in xrange(5):
        form = idaapi.find_tform("IDA View-%c" % chr(ord('A') + i))
        if form:
            break
    else:
        raise RuntimeError("Failed to find donor IDA View")

    # lookup the Qt Widget for the given form and take 2px tall image
    if using_pyqt5():
        widget = idaapi.PluginForm.FormToPyQtWidget(form)
        pixmap = widget.grab(QtCore.QRect(0, 0, widget.width(), 2))
    else:
        widget = idaapi.PluginForm.FormToPySideWidget(form)
        pixmap = QtGui.QPixmap.grabWidget(
            widget, QtCore.QRect(0, 0, widget.width(), 2))

    # extract a pixel from the top center like a pleb (hopefully a background pixel :|)
    img = QtGui.QImage(pixmap.toImage())
    color = QtGui.QColor(img.pixel(img.width() / 2, 1))

    # return the color of the pixel we extracted
    return color
Example #6
0
 def activate(self, ctx):
     tform = idaapi.find_tform('Classes')
     if not tform:
         class_viewer = ClassViewer(classes.ProxyModel(), classes.TreeModel())
         class_viewer.Show()
     else:
         idaapi.switchto_tform(tform, True)
Example #7
0
File: qt.py Project: Noam5/sark2
def get_widget(title):
    """Get the Qt widget of the IDA window with the given title."""
    tform = idaapi.find_tform(title)
    if not tform:
        raise exceptions.FormNotFound("No form titled {!r} found.".format(title))

    return form_to_widget(tform)
Example #8
0
    def destroy(self):
        self.destroying = True
        self.is_loaded = False
        self.hooks.unhook()
        window = idaapi.find_tform(self.title)

        if (window):
            idaapi.close_tform(window, 0)
Example #9
0
            def update():
                if (self.destroying == True or idaapi.find_tform(self.title) == None):
                    return -1
                else:
                    if(self.do_auto):
                        self.update()

                    return 200
Example #10
0
    def destroy(self):
        self.destroying = True
        self.is_loaded = False
        self.hooks.unhook()
        window = idaapi.find_tform(self.title)

        if(window):
            idaapi.close_tform(window, 0)
Example #11
0
 def get_init_menu(self):
     try:
         self.widget = form_to_widget(idaapi.get_current_tform())
         if self.widget is None:
             raise Exception()
     except:
         self.widget = form_to_widget(idaapi.find_tform('Output window'))
     self.window = self.widget.window()
     self.menu = self.window.findChild(QtWidgets.QMenuBar)
Example #12
0
            def update():
                if (self.destroying == True
                        or idaapi.find_tform(self.title) == None):
                    return -1
                else:
                    if (self.do_auto):
                        self.update()

                    return 200
Example #13
0
    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"
Example #14
0
 def activate(self, ctx):
     """
     :param ctx: idaapi.action_activation_ctx_t
     :return:    None
     """
     tform = idaapi.find_tform('Classes')
     if not tform:
         class_viewer = Forms.ClassViewer()
         class_viewer.Show()
     else:
         idaapi.switchto_tform(tform, True)
Example #15
0
File: qt.py Project: Noam5/sark2
def get_window():
    """Get IDA's top level window."""
    tform = idaapi.get_current_tform()

    # Required sometimes when closing IDBs and not IDA.
    if not tform:
        tform = idaapi.find_tform("Output window")

    widget = form_to_widget(tform)
    window = widget.window()
    return window
Example #16
0
    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"
Example #17
0
def get_selected_funcs():
    tform = idaapi.find_tform("Functions window")
    if not tform:
        idc.Warning("Unable to find 'Functions window'")
        return

    widget = idaapi.PluginForm.FormToPySideWidget(tform)
    table = widget.findChild(QtWidgets.QTableView)
    selected_funcs = [str(s.data()) for s in table.selectionModel().selectedRows()]

    return match_funcs(selected_funcs)
Example #18
0
def touch_window(target):
    """
    Touch a window/widget/form to ensure it gets drawn by IDA.

    XXX/HACK:

      We need to ensure that widget we will analyze actually gets drawn
      so that there are colors for us to steal.

      To do this, we switch to it, and switch back. I tried a few different
      ways to trigger this from Qt, but could only trigger the full
      painting by going through the IDA routines.

    """

    # get the currently active widget/form title (the form itself seems transient...)
    if using_ida7api:
        twidget = idaapi.get_current_widget()
        title = idaapi.get_widget_title(twidget)
    else:
        form = idaapi.get_current_tform()
        title = idaapi.get_tform_title(form)

    # touch/draw the widget by playing musical chairs
    if using_ida7api:

        # touch the target window by switching to it
        idaapi.activate_widget(target, True)
        flush_ida_sync_requests()

        # locate our previous selection
        previous_twidget = idaapi.find_widget(title)

        # return us to our previous selection
        idaapi.activate_widget(previous_twidget, True)
        flush_ida_sync_requests()

    else:

        # touch the target window by switching to it
        idaapi.switchto_tform(target, True)
        flush_ida_sync_requests()

        # locate our previous selection
        previous_form = idaapi.find_tform(title)

        # lookup our original form and switch back to it
        idaapi.switchto_tform(previous_form, True)
        flush_ida_sync_requests()
Example #19
0
 def __init__(self, funcname, blocks, edges, blockInfo, options):
     #Lets make sure we dont open the same graph twice. (it can crash IDA ... )     
     self.options = options   
     
     AlreadyOpenGraph = idaapi.find_tform("basic block graph to " + funcname)
     if(AlreadyOpenGraph != None):
         idaapi.close_tform(AlreadyOpenGraph, 0)
     
     idaapi.GraphViewer.__init__(self, "basic block graph to " + funcname)
     self.funcname = funcname
     self.blocks = blocks
     self.blockInfo = blockInfo
     self.edges = edges
     self.block_to_id = {}
     self.id_to_block = {}
Example #20
0
    def __init__(self, funcname, affected, edges, ui_obj):
        #Lets make sure we dont open the same graph twice. (it can crash IDA ... )
        AlreadyOpenGraph = idaapi.find_tform("call graph of 0x%08x" % funcname)

        if (AlreadyOpenGraph != None):
            idaapi.close_tform(AlreadyOpenGraph, 0)

        idaapi.GraphViewer.__init__(self, "call graph of 0x%08x" % funcname)

        self.funcname = funcname
        self.affected = affected
        self.edges = edges
        self.f_to_id = {}
        self.id_to_f = {}
        self.ui_obj = ui_obj
Example #21
0
    def __init__(self, funcname, affected, edges, ui_obj):
        #Lets make sure we dont open the same graph twice. (it can crash IDA ... )
        AlreadyOpenGraph = idaapi.find_tform("call graph of 0x%08x" % funcname)
        
        if(AlreadyOpenGraph != None):
            idaapi.close_tform(AlreadyOpenGraph, 0)
            

        idaapi.GraphViewer.__init__(self, "call graph of 0x%08x" % funcname)

        self.funcname = funcname
        self.affected = affected
        self.edges = edges
        self.f_to_id = {}
        self.id_to_f = {}
        self.ui_obj = ui_obj
Example #22
0
    def __init__(self, funcname, blocks, edges, blockInfo, options):
        #Lets make sure we dont open the same graph twice. (it can crash IDA ... )
        self.options = options

        AlreadyOpenGraph = idaapi.find_tform("basic block graph to " +
                                             funcname)
        if (AlreadyOpenGraph != None):
            idaapi.close_tform(AlreadyOpenGraph, 0)

        idaapi.GraphViewer.__init__(self, "basic block graph to " + funcname)
        self.funcname = funcname
        self.blocks = blocks
        self.blockInfo = blockInfo
        self.edges = edges
        self.block_to_id = {}
        self.id_to_block = {}
Example #23
0
    def eventFilter(self, source, event):

        #
        # hook the destroy event of the coverage overview widget so that we can
        # cleanup after ourselves in the interest of stability
        #

        if int(event.type()
               ) == 16:  # NOTE/COMPAT: QtCore.QEvent.Destroy not in IDA7?
            self._target.terminate()

        #
        # this is an unknown event, but it seems to fire when the widget is
        # being saved/restored by a QMainWidget. we use this to try and ensure
        # the Coverage Overview stays docked when flipping between Reversing
        # and Debugging states in IDA.
        #
        # See issue #16 on github for more information.
        #

        if int(event.type()) == 2002 and disassembler.NAME == "IDA":
            import idaapi

            #
            # if the general registers IDA View exists, we make the assumption
            # that the user has probably started debugging.
            #

            # NOTE / COMPAT:
            if disassembler.USING_IDA7API:
                debug_mode = bool(idaapi.find_widget("General registers"))
            else:
                debug_mode = bool(idaapi.find_tform("General registers"))

            #
            # if this is the first time the user has started debugging, dock
            # the coverage overview in the debug QMainWidget workspace. its
            # dock status / position should persist future debugger launches.
            #

            global debugger_docked
            if debug_mode and not debugger_docked:
                idaapi.set_dock_pos(self._target._title, "Structures",
                                    idaapi.DP_TAB)
                debugger_docked = True

        return False
Example #24
0
def get_selected_funcs():
    """
    Return the list of function names selected in the Functions window.
    """

    # NOTE / COMPAT:
    if using_ida7api:
        import sip
        twidget = idaapi.find_widget("Functions window")
        widget = sip.wrapinstance(long(twidget),
                                  QtWidgets.QWidget)  # NOTE: LOL
    else:
        tform = idaapi.find_tform("Functions window")
        if using_pyqt5:
            widget = idaapi.PluginForm.FormToPyQtWidget(tform)
        else:
            widget = idaapi.PluginForm.FormToPySideWidget(tform)

    # TODO: test this
    if not widget:
        idaapi.warning("Unable to find 'Functions window'")
        return

    #
    # locate the table widget within the Functions window that actually holds
    # all the visible function metadata
    #

    table = widget.findChild(QtWidgets.QTableView)

    #
    # scrape the selected function names from the Functions window table
    #

    selected_funcs = [
        str(s.data()) for s in table.selectionModel().selectedRows()
    ]

    #
    # re-map the scraped names as they appear in the function table, to their true
    # names as they are saved in the IDB. See the match_funcs(...) function
    # comment for more details
    #

    return match_funcs(selected_funcs)
Example #25
0
    def _make_unique_title(self, title):
        """Make the title unique.

        Adds a counter to the title to prevent duplicates.

        Prior to IDA 6.8, two graphs with the same title could crash IDA.
        This has been fixed (https://www.hex-rays.com/products/ida/6.8/index.shtml).
        The code will not change for support of older versions and as it is
        more usable this way.
        """
        unique_title = title

        for counter in itertools.count():
            unique_title = "{}-{}".format(title, counter)
            if not idaapi.find_tform(unique_title):
                break

        return unique_title
Example #26
0
    def _make_unique_title(self, title):
        """Make the title unique.

        Adds a counter to the title to prevent duplicates.

        Prior to IDA 6.8, two graphs with the same title could crash IDA.
        This has been fixed (https://www.hex-rays.com/products/ida/6.8/index.shtml).
        The code will not change for support of older versions and as it is
        more usable this way.
        """
        unique_title = title

        for counter in itertools.count():
            unique_title = "{}-{}".format(title, counter)
            if not idaapi.find_tform(unique_title):
                break

        return unique_title
Example #27
0
    def OnRefresh(self, n):

        if not self.is_select:
            form_title = "ETM coverage"
            form = idaapi.find_tform(form_title)

            if form != None:
                print "ETM coverage window already open. Switching to it."
                idaapi.switchto_tform(form, True)
                return n

            self.coverage_window = EtmCoverageChoose2(form_title, modal=False)
            self.coverage_window.fill(self.coverage)
            self.coverage_window.show()
            self.callgraph_window = EtmCallGraphViewer(self.callgraph)
            self.callgraph_window.show()

        self.is_select = False
        return n
Example #28
0
def get_selected_funcs():
    """
    Return the list of function names selected in the Functions window.
    """

    # locate the functions window for scraping
    tform = idaapi.find_tform("Functions window")
    if not tform:
        idc.Warning("Unable to find 'Functions window'")
        return

    #
    # extract the PySide / PyQt widget from the located IDA TForm so we can
    # tap into its Qt elements more easily and scrape relevant data from them
    #

    if using_pyqt5():
        widget = idaapi.PluginForm.FormToPyQtWidget(tform)
    else:
        widget = idaapi.PluginForm.FormToPySideWidget(tform)

    #
    # locate the table widget within the Functions window that actually holds
    # all the visible function metadata
    #

    table = widget.findChild(QtWidgets.QTableView)

    #
    # scrape the selected function names from the Functions window table
    #

    selected_funcs = [
        str(s.data()) for s in table.selectionModel().selectedRows()
    ]

    #
    # re-map the scraped names as they appear in the function table, to their true
    # names as they are saved in the IDB. See the match_funcs(...) function
    # comment for more details
    #

    return match_funcs(selected_funcs)
Example #29
0
def get_selected_funcs():
    """
    Return the list of function names selected in the Functions window.
    """

    # locate the functions window for scraping
    tform = idaapi.find_tform("Functions window")
    if not tform:
        idc.Warning("Unable to find 'Functions window'")
        return

    #
    # extract the PySide / PyQt widget from the located IDA TForm so we can
    # tap into its Qt elements more easily and scrape relevant data from them
    #

    if using_pyqt5():
        widget = idaapi.PluginForm.FormToPyQtWidget(tform)
    else:
        widget = idaapi.PluginForm.FormToPySideWidget(tform)

    #
    # locate the table widget within the Functions window that actually holds
    # all the visible function metadata
    #

    table = widget.findChild(QtWidgets.QTableView)

    #
    # scrape the selected function names from the Functions window table
    #

    selected_funcs = [str(s.data()) for s in table.selectionModel().selectedRows()]

    #
    # re-map the scraped names as they appear in the function table, to their true
    # names as they are saved in the IDB. See the match_funcs(...) function
    # comment for more details
    #

    return match_funcs(selected_funcs)
Example #30
0
def get_disas_bg_color():
    """
    Get the background color of an IDA disassembly view.

    -----------------------------------------------------------------------

    The necessity of this function is pretty silly. I would like lighthouse
    to be color-aware of the user's IDA theme such that it selects reasonable
    colors that maintain readability.

    Since there is no supported way to probe the palette & colors in use by
    IDA, we must get creative. This function attempts to locate an IDA
    disassembly view, and take a screenshot of said widget. It will then
    attempt to extract the color of a single background pixel (hopefully).

    PS: please expose the get_graph_color(...) palette accessor, Ilfak ;_;
    """

    # find a form (eg, IDA view) to steal a pixel from
    for i in xrange(5):
        form = idaapi.find_tform("IDA View-%c" % chr(ord('A') + i))
        if form:
            break
    else:
        raise RuntimeError("Failed to find donor IDA View")

    # locate the Qt Widget for an IDA View form and take 2px tall screenshot
    if using_pyqt5():
        widget = idaapi.PluginForm.FormToPyQtWidget(form)
        pixmap = widget.grab(QtCore.QRect(0, 0, widget.width(), 2))
    else:
        widget = idaapi.PluginForm.FormToPySideWidget(form)
        region = QtCore.QRect(0, 0, widget.width(), 2)
        pixmap = QtGui.QPixmap.grabWidget(widget, region)

    # extract 1 pixel like a pleb (hopefully a background pixel :|)
    img = QtGui.QImage(pixmap.toImage())
    color = QtGui.QColor(img.pixel(img.width() / 2, 1))

    # return the color of the pixel we extracted
    return color
Example #31
0
def ida_get_cfg_raw(existing_cfg=None):
    if "idaapi" not in sys.modules:
        print "ERROR: idaapi not loaded"
        return None
    
    import idaapi
    tw = idaapi.find_tform("IDAgrap")
    if tw is not None:
        import idagrap
        # Get CFG from existing loaded IDAgrap
        w = idaapi.PluginForm.FormToPyQtWidget(tw)
        pgw=w.findChild(idagrap.ui.widgets.PatternGenerationWidget.PatternGenerationWidget)
        cfg = pgw.cc.PatternGenerator.graph
        return cfg, True
    else:
        # If necessary, load grap and creates new CFG object
        if existing_cfg is None:
            fp, pathname, description = imp.find_module("grap")
            _mod = imp.load_module("grap", fp, pathname, description)
            cfg = _mod.CFG()
            return cfg, False
        return existing_cfg, False
Example #32
0
 def activate(self, ctx):
     tform = idaapi.find_tform("Structure Builder")
     if tform:
         idaapi.switchto_tform(tform, True)
     else:
         StructureBuilder(cache.temporary_structure).Show()
 def run(arg):
     tform = idaapi.find_tform("Structure Builder")
     if tform:
         idaapi.switchto_tform(tform, True)
     else:
         Forms.StructureBuilder(Helper.temporary_structure).Show()
Example #34
0
def find_widget(title):
    if idaapi.IDA_SDK_VERSION <= 699:
        form = idaapi.find_tform(title)
    else:
        form = ida_kernwin.find_widget(title)
    return form
Example #35
0
    def create(self):
        if(idaapi.find_tform(self.title) == None):
            if(not idaapi.simplecustviewer_t.Create(self, self.title)):
                print "Unable to open"
                return False
            
            if idaapi.IDA_SDK_VERSION >= 700:
                self.menu_update = 1
                self.menu_lookup = 2
                self.menu_autorefresh = 3
                self.change_arch = 4
                
                class Hooks(idaapi.UI_Hooks):
                    class PopupActionHandler(idaapi.action_handler_t):
                        def __init__(self, owner, menu_id):
                            self.owner = owner
                            self.menu_id = menu_id
                        
                        def activate(self, ctx):
                            self.owner.OnPopupMenu(self.menu_id)
                            
                        def update(self, ctx):
                            return idaapi.AST_ENABLE_ALWAYS
                            
                    def __init__(self, form):
                        idaapi.UI_Hooks.__init__(self)
                        self.form = form
                    def finish_populating_widget_popup(self, widget, popup):
                        if self.form.title == idaapi.get_widget_title(widget):
                            idaapi.attach_dynamic_action_to_popup(widget, popup, idaapi.action_desc_t(None, "Update View", self.PopupActionHandler(self.form, self.form.menu_update),   None, None, -1))
                            idaapi.attach_dynamic_action_to_popup(widget, popup, idaapi.action_desc_t(None, "Lookup Instruction", self.PopupActionHandler(self.form, self.form.menu_lookup),   None, None, -1))
                            idaapi.attach_dynamic_action_to_popup(widget, popup, idaapi.action_desc_t(None, "Toggle Auto-refresh", self.PopupActionHandler(self.form, self.form.menu_autorefresh),   None, None, -1))
                            idaapi.attach_action_to_popup(widget, popup, "-", None)
                            idaapi.attach_dynamic_action_to_popup(widget, popup, idaapi.action_desc_t(None, "Change Architecture", self.PopupActionHandler(self.form, self.form.change_arch),  None, None, -1))
                            idaapi.attach_action_to_popup(widget, popup, "-", None)        
                self.hooks = Hooks(self)
                self.hooks.hook()
            else:
                self.menu_update = self.AddPopupMenu("Update View")
                self.menu_lookup = self.AddPopupMenu("Lookup Instruction")
                self.menu_autorefresh = self.AddPopupMenu("Toggle Auto-refresh")
                self.change_arch = self.AddPopupMenu("Change Architecture")

            self.Show()

            def update():
                if (self.destroying == True or idaapi.find_tform(self.title) == None):
                    return -1
                else:
                    if(self.do_auto):
                        self.update()

                    return 200

            if('register_timer' in dir(idaapi)):
                idaapi.register_timer(200, update)

                self.is_loaded = True
            else:
                print "Sorry I can't support auto-refresh in your version of IDA."
                print "Use 'ref.update()' to get documentation for your instruction."
        else:
            print "Already loaded. Please close old instance first."
Example #36
0
def run_bap_with(argument_string, no_extras=False):
    """
    Run bap with the given argument_string.

    Uses the currently open file, dumps latest symbols from IDA and runs
    BAP with the argument_string

    Also updates the 'BAP View'

    Note: If no_extras is set to True, then none of the extra work mentioned
          above is done, and instead, bap is just run purely using
                bap <executable> <argument_string>
    """
    from bap.plugins.bap_view import BAP_View
    from bap.utils import config
    import ida
    import idc
    import tempfile

    check_and_configure_bap()
    bap_executable_path = config.get('bap_executable_path')
    if bap_executable_path is None:
        return  # The user REALLY doesn't want us to run it

    args = {
        'bap_executable_path': bap_executable_path,
        'bap_output_file': tempfile.mkstemp(suffix='.out',
                                            prefix='ida-bap-')[1],
        'input_file_path': idc.GetInputFilePath(),
        'symbol_file_location': tempfile.mkstemp(suffix='.sym',
                                                 prefix='ida-bap-')[1],
        'header_path': tempfile.mkstemp(suffix='.h', prefix='ida-bap-')[1],
        'remaining_args': argument_string
    }

    if no_extras:

        command = (
            "\
            \"{bap_executable_path}\" \"{input_file_path}\" \
            {remaining_args} \
            > \"{bap_output_file}\" 2>&1 \
            ".format(**args)
        )

    else:

        bap_api_enabled = (config.get('enabled',
                                      default='0',
                                      section='bap_api').lower() in
                           ('1', 'true', 'yes'))

        ida.dump_symbol_info(args['symbol_file_location'])

        if bap_api_enabled:
            ida.dump_c_header(args['header_path'])
            idc.Exec(
                "\
                \"{bap_executable_path}\" \
                --api-add=c:\"{header_path}\" \
                ".format(**args)
            )

        command = (
            "\
            \"{bap_executable_path}\" \"{input_file_path}\" \
            --read-symbols-from=\"{symbol_file_location}\" \
            --symbolizer=file \
            --rooter=file \
            {remaining_args} \
            -d > \"{bap_output_file}\" 2>&1 \
            ".format(**args)
        )

    idc.Exec(command)

    with open(args['bap_output_file'], 'r') as f:
        BAP_View.update(
            "BAP execution string\n" +
            "--------------------\n" +
            "\n" +
            '\n    --'.join(command.strip().split('--')) +
            "\n" +
            "\n" +
            "Output\n" +
            "------\n" +
            "\n" +
            f.read()
        )

    # Force close BAP View
    # This forces the user to re-open the new view if needed
    # This "hack" is needed since IDA decides to give a different BAP_View
    #   class here, than the cls parameter it sends to BAP_View
    # TODO: Fix this
    import idaapi
    tf = idaapi.find_tform("BAP View")
    if tf:
        idaapi.close_tform(tf, 0)

    # Do a cleanup of all the temporary files generated/added
    if not no_extras:
        if bap_api_enabled:
            idc.Exec(
                "\
                \"{bap_executable_path}\" \
                --api-remove=c:`basename \"{header_path}\"` \
                ".format(**args)
            )
    idc.Exec(
        "\
        rm -f \
            \"{symbol_file_location}\" \
            \"{header_path}\" \
            \"{bap_output_file}\" \
        ".format(**args)
    )
Example #37
0
            for addr in free_addr:
                patch_call_free(addr)

        #patch format vul
        if bfind_puts == True:
            printf_addr = search_printf_instr(func)
            if printf_addr != []:
                for addr in printf_addr:
                    patch_call_printf(addr)

    return


if __name__ == '__main__':
    #清空输出窗口
    form = idaapi.find_tform("Output window")
    idaapi.switchto_tform(form, True)
    idaapi.process_ui_action("msglist:Clear")

    #save to file
    path = os.path.abspath(__file__)
    path = os.path.realpath(__file__)
    path = os.path.dirname(path)

    #
    target_path = idc.GetInputFilePath()
    target_file = idc.GetInputFile()

    if idaapi.init_hexrays_plugin():
        #print("Hex-rays version %s has been detected" % idaapi.get_hexrays_version())
        pass
Example #38
0
def run_bap_with(argument_string):
    """
    Run bap with the given argument_string.

    Uses the currently open file, dumps latest symbols from IDA and runs
    BAP with the argument_string

    Also updates the 'BAP View'
    """
    from bap.plugins.bap_view import BAP_View
    from bap.utils import config
    import ida
    import idc
    import tempfile

    check_and_configure_bap()
    bap_executable_path = config.get('bap_executable_path')
    if bap_executable_path is None:
        return  # The user REALLY doesn't want us to run it

    args = {
        'bap_executable_path':
        bap_executable_path,
        'bap_output_file':
        tempfile.mkstemp(suffix='.out', prefix='ida-bap-')[1],
        'input_file_path':
        idc.GetInputFilePath(),
        'symbol_file_location':
        tempfile.mkstemp(suffix='.sym', prefix='ida-bap-')[1],
        'header_path':
        tempfile.mkstemp(suffix='.h', prefix='ida-bap-')[1],
        'remaining_args':
        argument_string
    }

    bap_api_enabled = (config.get('enabled', default='0',
                                  section='bap_api').lower()
                       in ('1', 'true', 'yes'))

    ida.dump_symbol_info(args['symbol_file_location'])

    if bap_api_enabled:
        ida.dump_c_header(args['header_path'])
        idc.Exec("\
            \"{bap_executable_path}\" \
            --api-add=c:\"{header_path}\" \
            ".format(**args))

    command = ("\
        \"{bap_executable_path}\" \"{input_file_path}\" \
        --read-symbols-from=\"{symbol_file_location}\" --symbolizer=file \
        {remaining_args} \
        -d > \"{bap_output_file}\" 2>&1 \
        ".format(**args))

    idc.Exec(command)

    with open(args['bap_output_file'], 'r') as f:
        BAP_View.update("BAP execution string\n" + "--------------------\n" +
                        "\n" + '\n    --'.join(('bap' +
                                                argument_string).split('--')) +
                        "\n" + "\n" + "Output\n" + "------\n" + "\n" +
                        f.read())

    # Force close BAP View
    # This forces the user to re-open the new view if needed
    # This "hack" is needed since IDA decides to give a different BAP_View
    #   class here, than the cls parameter it sends to BAP_View
    # TODO: Fix this
    import idaapi
    tf = idaapi.find_tform("BAP View")
    if tf:
        idaapi.close_tform(tf, 0)

    # Do a cleanup of all the temporary files generated/added
    if bap_api_enabled:
        idc.Exec("\
            \"{bap_executable_path}\" \
            --api-remove=c:`basename \"{header_path}\"` \
            ".format(**args))
    idc.Exec("\
        rm -f \
            \"{symbol_file_location}\" \
            \"{header_path}\" \
            \"{bap_output_file}\" \
        ".format(**args))
Example #39
0
    def create(self):
        if (idaapi.find_tform(self.title) == None):
            if (not idaapi.simplecustviewer_t.Create(self, self.title)):
                print "Unable to open"
                return False

            if idaapi.IDA_SDK_VERSION >= 700:
                self.menu_update = 1
                self.menu_lookup = 2
                self.menu_autorefresh = 3
                self.change_arch = 4

                class Hooks(idaapi.UI_Hooks):
                    class PopupActionHandler(idaapi.action_handler_t):
                        def __init__(self, owner, menu_id):
                            self.owner = owner
                            self.menu_id = menu_id

                        def activate(self, ctx):
                            self.owner.OnPopupMenu(self.menu_id)

                        def update(self, ctx):
                            return idaapi.AST_ENABLE_ALWAYS

                    def __init__(self, form):
                        idaapi.UI_Hooks.__init__(self)
                        self.form = form

                    def finish_populating_widget_popup(self, widget, popup):
                        if self.form.title == idaapi.get_widget_title(widget):
                            idaapi.attach_dynamic_action_to_popup(
                                widget, popup,
                                idaapi.action_desc_t(
                                    None, "Update View",
                                    self.PopupActionHandler(
                                        self.form, self.form.menu_update),
                                    None, None, -1))
                            idaapi.attach_dynamic_action_to_popup(
                                widget, popup,
                                idaapi.action_desc_t(
                                    None, "Lookup Instruction",
                                    self.PopupActionHandler(
                                        self.form, self.form.menu_lookup),
                                    None, None, -1))
                            idaapi.attach_dynamic_action_to_popup(
                                widget, popup,
                                idaapi.action_desc_t(
                                    None, "Toggle Auto-refresh",
                                    self.PopupActionHandler(
                                        self.form, self.form.menu_autorefresh),
                                    None, None, -1))
                            idaapi.attach_action_to_popup(
                                widget, popup, "-", None)
                            idaapi.attach_dynamic_action_to_popup(
                                widget, popup,
                                idaapi.action_desc_t(
                                    None, "Change Architecture",
                                    self.PopupActionHandler(
                                        self.form, self.form.change_arch),
                                    None, None, -1))
                            idaapi.attach_action_to_popup(
                                widget, popup, "-", None)

                self.hooks = Hooks(self)
                self.hooks.hook()
            else:
                self.menu_update = self.AddPopupMenu("Update View")
                self.menu_lookup = self.AddPopupMenu("Lookup Instruction")
                self.menu_autorefresh = self.AddPopupMenu(
                    "Toggle Auto-refresh")
                self.change_arch = self.AddPopupMenu("Change Architecture")

            self.Show()

            def update():
                if (self.destroying == True
                        or idaapi.find_tform(self.title) == None):
                    return -1
                else:
                    if (self.do_auto):
                        self.update()

                    return 200

            if ('register_timer' in dir(idaapi)):
                idaapi.register_timer(200, update)

                self.is_loaded = True
            else:
                print "Sorry I can't support auto-refresh in your version of IDA."
                print "Use 'ref.update()' to get documentation for your instruction."
        else:
            print "Already loaded. Please close old instance first."
Example #40
0
File: rev.py Project: wyu0hop/RESim
    # This action is always available.
    def update(self, ctx):
        return idaapi.AST_ENABLE_ALWAYS


if __name__ == "__main__":
    #Wait()
    bookmark_view = bookmarkView.bookmarkView()
    stack_trace = stackTrace.StackTrace()
    #print('back from init bookmarkView')
    keymap_done = False
    #primePump()
    #nameSysCalls(True)
    #print('back from nameSysCalls')
    form = idaapi.find_tform("Stack view")
    #print('do switch')
    idaapi.switchto_tform(form, True)
    #print('now create bookmark_view')
    print('RESim Ida Client Version 1.2')
    isim = idaSIM.IdaSIM(stack_trace, bookmark_view, kernel_base, reg_list,
                         registerMath)
    bookmark_view.Create(isim)
    bookmark_view.register()
    bookmark_list = bookmark_view.updateBookmarkView()
    if bookmark_list is not None:
        for bm in bookmark_list:
            if 'nox' in bm:
                eip_str = getTagValue(bm, 'nox')
                eip = int(eip_str, 16)
                idc.MakeCode(eip)