Python idc.ScreenEA() Examples

The following are 18 code examples of idc.ScreenEA(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module idc , or try the search function .
Example #1
Source File: win_driver_plugin.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def find_all_ioctls():
    """
    From the currently selected address attempts to traverse all blocks inside the current function to find all immediate values which
    are used for a comparison/sub immediately before a jz. Returns a list of address, second operand pairs.
    """
    
    ioctls = []
    # Find the currently selected function and get a list of all of it's basic blocks
    addr = idc.ScreenEA()
    f = idaapi.get_func(addr)
    fc = idaapi.FlowChart(f, flags=idaapi.FC_PREDS)
    for block in fc:
        # grab the last two instructions in the block 
        last_inst = idc.PrevHead(block.endEA)
        penultimate_inst = idc.PrevHead(last_inst)
        # If the penultimate instruction is cmp or sub against an immediate value immediately preceding a 'jz' 
        # then it's a decent guess that it's an IOCTL code (if this is a dispatch function)
        if idc.GetMnem(penultimate_inst) in ['cmp', 'sub'] and idc.GetOpType(penultimate_inst, 1) == 5:
            if idc.GetMnem(last_inst) == 'jz':
                value = get_operand_value(penultimate_inst)
                ioctls.append((penultimate_inst, value))
                ioctl_tracker.add_ioctl(penultimate_inst, value)
    return ioctls 
Example #2
Source File: win_driver_plugin.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_position_and_translate():
    """
    Gets the current selected address and decodes the second parameter to the instruction if it exists/is an immediate
    then adds the C define for the code as a comment and prints a summary table of all decoded IOCTL codes.
    """

    pos = idc.ScreenEA()
    if idc.GetOpType(pos, 1) != 5:   # Check the second operand to the instruction is an immediate
        return
    
    value = get_operand_value(pos)
    ioctl_tracker.add_ioctl(pos, value)
    define = ioctl_decoder.get_define(value)
    make_comment(pos, define)
    # Print summary table each time a new IOCTL code is decoded
    ioctls = []
    for inst in ioctl_tracker.ioctl_locs:
        value = get_operand_value(inst)
        ioctls.append((inst, value))
    ioctl_tracker.print_table(ioctls) 
Example #3
Source File: Stingray.py    From Stingray with GNU General Public License v3.0 6 votes vote down vote up
def get_current_function_strings( self ):

        addr_in_func = idc.ScreenEA()
        curr_func = idc.GetFunctionName(addr_in_func)

        funcs = [ addr_in_func ]
        if ConfigStingray.SEARCH_RECURSION_MAXLVL > 0:
            funcs = find_function_callees(  addr_in_func, 
                                            ConfigStingray.SEARCH_RECURSION_MAXLVL  )

        total_strs = []
        for func in funcs:
            strs = find_function_strings(func)
            total_strs += [ s.get_row() for s in strs ]

        return total_strs


# ------------------------------------------------------------------------------ 
Example #4
Source File: win_driver_plugin.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def finish_populating_tform_popup(self, form, popup):
        tft = idaapi.get_tform_type(form)
        if tft != idaapi.BWN_DISASM:
            return

        pos = idc.ScreenEA()
        register_dynamic_action(form, popup, 'Decode All IOCTLs in Function', DecodeAllHandler())
        register_dynamic_action(form, popup, 'Decode IOCTLs using Angr', DecodeAngrHandler())
		# If the second argument to the current selected instruction is an immediately
        # then give the option to decode it.
        if idc.GetOpType(pos, 1) == 5:
            register_dynamic_action(form, popup, 'Decode IOCTL', DecodeHandler())
            if pos in ioctl_tracker.ioctl_locs:
                register_dynamic_action(form, popup, 'Invalid IOCTL', InvalidHandler())
        if len(ioctl_tracker.ioctl_locs) > 0:
            register_dynamic_action(form, popup, 'Show All IOCTLs', ShowAllHandler()) 
Example #5
Source File: widgets.py    From rematch with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, text_max_length=30, **kwargs):
    super(QFunctionSelect, self).__init__(**kwargs)

    self.text_max = text_max_length
    self.func = None

    self.label = QtWidgets.QPushButton()
    self.label.clicked.connect(self.label_clicked)
    self.label.setFlat(True)
    self.btn = QtWidgets.QPushButton("...")
    self.btn.setMaximumWidth(20)
    self.btn.clicked.connect(self.btn_clicked)

    current_func = ida_funcs.get_func(idc.ScreenEA())
    if current_func:
      self.set_func(current_func)

    layout = QtWidgets.QHBoxLayout()
    layout.setContentsMargins(0, 0, 0, 0)
    layout.addWidget(self.label)
    layout.addWidget(self.btn)
    layout.setStretch(0, 1)
    self.setLayout(layout) 
Example #6
Source File: yara_fn.py    From python-idb with Apache License 2.0 5 votes vote down vote up
def main():
    va = idc.ScreenEA()
    fva = get_function(va)
    rule = create_yara_rule_for_function(fva)
    print(rule)

    if test_yara_rule(rule):
        print("success: validated the generated rule")
    else:
        print("error: failed to validate generated rule") 
Example #7
Source File: find.py    From Sibyl with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):

        addr = idc.ScreenEA()
        func = idaapi.get_func(addr)

        tests_choice = "\n".join(map(lambda x: "<%s:{r%s}>" % (x, x), AVAILABLE_TESTS))
        ida_kernwin.Form.__init__(self,
r"""BUTTON YES* Launch
BUTTON CANCEL NONE
Sibyl Settings

{FormChangeCb}
Apply on:
<One function:{rOneFunc}>
<All functions:{rAllFunc}>{cMode}>

<Targeted function:{cbFunc}>

Testsets to use:
%s{cTest}>

""" % tests_choice, {
    'FormChangeCb': ida_kernwin.Form.FormChangeCb(self.OnFormChange),
    'cMode': ida_kernwin.Form.RadGroupControl(("rOneFunc", "rAllFunc")),
    'cTest': ida_kernwin.Form.ChkGroupControl(map(lambda x: "r%s" % x,
                                      AVAILABLE_TESTS),
                                  value=(1 << len(AVAILABLE_TESTS)) - 1),
    'cbFunc': ida_kernwin.Form.DropdownListControl(
        items=self.available_funcs,
        readonly=False,
        selval="0x%x" % func.startEA),
}
        )

        self.Compile() 
Example #8
Source File: bap_bir_attr.py    From bap-ida-python with MIT License 5 votes vote down vote up
def run(self, arg):
        """
        Ask user for BAP args to pass, BIR attributes to print; and run BAP.

        Allows users to also use {screen_ea} in the BAP args to get the
        address at the location pointed to by the cursor.
        """

        args_msg = "Arguments that will be passed to `bap'"
        # If a user is not fast enough in providing the answer
        # IDA Python will popup a modal window that will block
        # a user from providing the answer.
        idaapi.disable_script_timeout()
        args = idaapi.askstr(ARGS_HISTORY, '--passes=', args_msg)
        if args is None:
            return
        attr_msg = "A comma separated list of attributes,\n"
        attr_msg += "that should be propagated to comments"
        attr_def = self.recipes.get(args, '')
        attr = idaapi.askstr(ATTR_HISTORY, attr_def, attr_msg)

        if attr is None:
            return

        # store a choice of attributes for the given set of arguments
        # TODO: store recipes in IDA's database
        self.recipes[args] = attr
        ea = idc.ScreenEA()
        attrs = []
        if attr != '':
            attrs = attr.split(',')
        analysis = BapScripter(args, attrs)
        analysis.on_finish(lambda bap: self.load_script(bap, ea))
        analysis.run() 
Example #9
Source File: bap_taint.py    From bap-ida-python with MIT License 5 votes vote down vote up
def start(self):
        tainter = PropagateTaint(idc.ScreenEA(), self.kind)
        tainter.on_finish(lambda bap: self.finish(bap))
        tainter.run() 
Example #10
Source File: bap_taint.py    From bap-ida-python with MIT License 5 votes vote down vote up
def _do_callbacks(cls, ptr_or_reg):
        data = {
            'ea': idc.ScreenEA(),
            'ptr_or_reg': ptr_or_reg
        }
        for callback in cls._callbacks[ptr_or_reg]:
            callback(data) 
Example #11
Source File: Reef.py    From Reef with GNU General Public License v3.0 5 votes vote down vote up
def get_current_function_xrefs_from( self ):
    
        addr_in_func = idc.ScreenEA()
        curr_func = idc.GetFunctionName( addr_in_func )

        refs = self.find_xrefs_from( addr_in_func )
        return [ ref.get_row( XrefsFromFinder.XREF_TYPE2STR ) for ref in refs ]


# ------------------------------------------------------------------------------ 
Example #12
Source File: PatternGenerationWidget.py    From grap with MIT License 5 votes vote down vote up
def _onRemoveTargetNode(self):
        try:
            self.cc.PatternGenerator.removeTargetNode(idc.get_screen_ea())
        except:
            self.cc.PatternGenerator.removeTargetNode(idc.ScreenEA())

        self._render_if_real_time() 
Example #13
Source File: PatternGenerationWidget.py    From grap with MIT License 5 votes vote down vote up
def setMatchType(self, type):
        try:
            selection, begin, end = None, None, None
            err = idaapi.read_selection(selection, begin, end)
            if err and selection:
                for ea in range(begin, end+1):
                    self.cc.PatternGenerator.setMatchType(ea, type)
            else:
                self.cc.PatternGenerator.setMatchType(idc.get_screen_ea(), type)  
        except:
            self.cc.PatternGenerator.setMatchType(idc.ScreenEA(), type)

        self._render_if_real_time() 
Example #14
Source File: PatternGenerationWidget.py    From grap with MIT License 5 votes vote down vote up
def _onAddTargetNode(self):
        try:
            self.cc.PatternGenerator.addTargetNode(idc.get_screen_ea())
        except:
            self.cc.PatternGenerator.addTargetNode(idc.ScreenEA())

        self._render_if_real_time() 
Example #15
Source File: PatternGenerationWidget.py    From grap with MIT License 5 votes vote down vote up
def _onSetRootNode(self):
        try:
            self.cc.PatternGenerator.setRootNode(idc.get_screen_ea())
        except:
            self.cc.PatternGenerator.setRootNode(idc.ScreenEA())

        self._render_if_real_time() 
Example #16
Source File: win_driver_plugin.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def activate(self, ctx):
        pos = idc.ScreenEA()
        # Get current comment for this instruction and remove the C define from it, if present
        comment = idc.Comment(pos)
        code = get_operand_value(pos)
        define = ioctl_decoder.get_define(code)
        comment = comment.replace(define, "")
        idc.MakeComm(pos, comment)
        # Remove the ioctl from the valid list and add it to the invalid list to avoid 'find_all_ioctls' accidently re-indexing it.
        ioctl_tracker.remove_ioctl(pos, code) 
Example #17
Source File: win_driver_plugin.py    From win_driver_plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def decode_angr():
	"""Attempts to locate all the IOCTLs in a function and decode them all using symbolic execution"""
	
	path = idaapi.get_input_file_path()
	addr = idc.ScreenEA()
	ioctls = angr_analysis.angr_find_ioctls(path, addr)
	track_ioctls(ioctls) 
Example #18
Source File: PatternGenerationWidget.py    From grap with MIT License 4 votes vote down vote up
def finish_populating_widget_popup(self, form, popup):
        try:
            b = idaapi.get_widget_type(form) == idaapi.BWN_DISASM
        except:
            b = idaapi.get_tform_type(form) == idaapi.BWN_DISASM
    
        if b:
            # Add separator
            idaapi.attach_action_to_popup(form, popup, None, None)

            # Add actions
            try:
                currentAddress = idc.get_screen_ea()
            except:
                currentAddress = idc.ScreenEA()

            #if currentAddress in [node.node_id for node in self.cc.PatternGenerator.targetNodes]:
            if currentAddress in self.cc.PatternGenerator.coloredNodes:
                idaapi.attach_action_to_popup(form, popup, "grap:pg:match_default", None)
                idaapi.attach_action_to_popup(form, popup, "grap:pg:match_full", None)
                idaapi.update_action_label("grap:pg:match_full", self.cc.PatternGenerator.preview_match(currentAddress, "[grap] Full match", "match_full"))
                idaapi.attach_action_to_popup(form, popup, "grap:pg:match_opcode_arg1", None)
                idaapi.update_action_label("grap:pg:match_opcode_arg1", self.cc.PatternGenerator.preview_match(currentAddress, "[grap] Opcode+arg1", "match_opcode_arg1"))
                idaapi.attach_action_to_popup(form, popup, "grap:pg:match_opcode_arg2", None)
                idaapi.update_action_label("grap:pg:match_opcode_arg2", self.cc.PatternGenerator.preview_match(currentAddress, "[grap] Opcode+arg2", "match_opcode_arg2"))
                idaapi.attach_action_to_popup(form, popup, "grap:pg:match_opcode_arg3", None)
                idaapi.update_action_label("grap:pg:match_opcode_arg3", self.cc.PatternGenerator.preview_match(currentAddress, "[grap] Opcode+arg3", "match_opcode_arg3"))
                idaapi.attach_action_to_popup(form, popup, "grap:pg:match_opcode", None)
                idaapi.update_action_label("grap:pg:match_opcode", self.cc.PatternGenerator.preview_match(currentAddress, "[grap] Opcode", "match_opcode"))
                idaapi.attach_action_to_popup(form, popup, "grap:pg:match_wildcard", None)
                idaapi.attach_action_to_popup(form, popup, "grap:pg:remove_target", None)
                
                for type in ["match_default", "match_full", "match_opcode_arg1", "match_opcode_arg2", "match_opcode_arg3", "match_opcode", "match_wildcard"]:
                    idaapi.update_action_icon("grap:pg:"+type, -1)
                
                if currentAddress not in self.cc.PatternGenerator.targetNodeType:
                    type = "match_default"
                else:
                    type = self.cc.PatternGenerator.targetNodeType[currentAddress]
                idaapi.update_action_icon("grap:pg:"+type, self.selected_icon_number)
                    
            elif self.cc.PatternGenerator.rootNode is None or currentAddress != self.cc.PatternGenerator.rootNode.node_id:
                idaapi.attach_action_to_popup(form, popup, "grap:pg:set_root", None)
                idaapi.attach_action_to_popup(form, popup, "grap:pg:add_target", None)