Exemple #1
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)
        file_name = '{}.cpp'.format(self.tools.to_file_name(demangled_name))

        cache_path = os.path.sep.join(
            [self.current_dir, 'data', 'cache', self._bin_name])
        if not os.path.isdir(cache_path):
            os.mkdir(cache_path)

        complete_path = os.path.sep.join([cache_path, file_name])
        if not os.path.isfile(complete_path):
            src = str(idaapi.decompile(idaapi.get_screen_ea()))
            self.tools.save_file(complete_path, src)
        self.tools.set_file_path(complete_path)

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

        self.parser = include.syntax.Parser(self)
        self.parser.run(complete_path)
        return
Exemple #2
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)
        file_name = '{}.cpp'.format(self.tools.to_file_name(demangled_name))

        cache_path = os.path.sep.join([self.current_dir,
                                       'data', 'cache',
                                       self._bin_name])
        if not os.path.isdir(cache_path):
            os.mkdir(cache_path)

        complete_path = os.path.sep.join([cache_path, file_name])
        if not os.path.isfile(complete_path):
            src = str(idaapi.decompile(idaapi.get_screen_ea()))
            self.tools.save_file(complete_path, src)
        self.tools.set_file_path(complete_path)

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

        self.parser = include.syntax.Parser(self)
        self.parser.run(complete_path)
        return
Exemple #3
0
 def activate(self, ctx):
     global _idangr_ctx, _idangr_panel
     if self.action == "Find":
         addr = idaapi.get_screen_ea()
         if addr in _idangr_ctx.avoid:
             _idangr_ctx.avoid.remove(addr)
             _idangr_panel.remove_avoid(addr)
         if addr in _idangr_ctx.find:
             return
         _idangr_ctx.find.append(addr)
         _idangr_panel.add_find(addr)
     elif self.action == "Avoid":
         addr = idaapi.get_screen_ea()
         if addr in _idangr_ctx.find:
             _idangr_ctx.find.remove(addr)
             _idangr_panel.remove_find(addr)
         if addr in _idangr_ctx.avoid:
             return
         _idangr_ctx.avoid.append(addr)
         _idangr_panel.add_avoid(addr)
     elif self.action == "Symbolic":
         addr = idaapi.get_screen_ea()
         #if addr in _idangr_ctx.simmem:
         #    return
         m = IDAngrAddMemDialog.get_mem(addr)
         if m != None:
             _idangr_panel.add_mem(m[0], m[1])
Exemple #4
0
	def OnViewCurpos(self):
		if(not(self.is_unloading) and self.bps_shared_memory[0] == 's'):
			self.Unload()
			return 
		
		#change with whatever key you want to use see:https://docs.microsoft.com/en-us/windows/desktop/inputdev/virtual-key-codes
		if(is_key_down(0x4a)): 
			#note: don't rebase if you have breakpoints that are already set (since bp_list won't be updated (todo)) (maybe could store them in base 0 so no need to rebase)
			self.HandleBp(idaapi.get_screen_ea()-idaapi.get_imagebase(), idaapi.get_screen_ea())
Exemple #5
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
Exemple #6
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)
        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 require 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))

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

        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))

        # Check if file is already in cache
        if not os.path.isfile(complete_path):
            self.tools.save_file(complete_path, str(src))

        self.tools.set_file_path(complete_path)

        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)
        self.parser.run(complete_path)
        return
Exemple #7
0
    def __init__(self):
        print 'Aqualung -- An experimental ARM decompiler'
        print 'Copyright 2007 Cody Brocious (cody DOT brocious AT gmail DOT com)'
        
        self.shiftMap = dict(
            ASL='<<',
            ASR='>>',
            LSL='<<',
            LSR='>>',
        )
        
        self.arithMap = dict(
            ADD='+',
            AND='&',
            BIC='&',
            LSL='<<',
            LSR='>>',
            MUL='*',
            ORR='|',
            SUB='-',
            SUBS='-',
            EOR='^',
        )
        
        self.suffixMap = dict(
            NE='!=',
            EQ='==',
            GE='>=',
            PL='>=',
            CS='<=',
            GT='>',
            VC='>',
            HI='>',
            CC='<',
            LT='<',
            MI='<',
            LS='<',
            VS='<',
        )
        
        self.ida = IDA()

        self.decompiled = []
        
        self.func = self.ida.getFunc()
        self.cmp = None
        self.decompile(self.func[0])
        
        if idaapi.get_screen_ea() not in self.decompiled:
            self.decompile(idaapi.get_screen_ea())
Exemple #8
0
    def __init__(self):
        print 'Aqualung -- An experimental ARM decompiler'
        print 'Copyright 2007 Cody Brocious (cody DOT brocious AT gmail DOT com)'

        self.shiftMap = dict(
            ASL='<<',
            ASR='>>',
            LSL='<<',
            LSR='>>',
        )

        self.arithMap = dict(
            ADD='+',
            AND='&',
            BIC='&',
            LSL='<<',
            LSR='>>',
            MUL='*',
            ORR='|',
            SUB='-',
            SUBS='-',
            EOR='^',
        )

        self.suffixMap = dict(
            NE='!=',
            EQ='==',
            GE='>=',
            PL='>=',
            CS='<=',
            GT='>',
            VC='>',
            HI='>',
            CC='<',
            LT='<',
            MI='<',
            LS='<',
            VS='<',
        )

        self.ida = IDA()

        self.decompiled = []

        self.func = self.ida.getFunc()
        self.cmp = None
        self.decompile(self.func[0])

        if idaapi.get_screen_ea() not in self.decompiled:
            self.decompile(idaapi.get_screen_ea())
Exemple #9
0
 def create_table(self):
     screen_ea = idaapi.get_screen_ea()
     print("Creating table at: ", hex(screen_ea))
     ida_bytes.del_items(screen_ea, 0, 4*6)
     ret = ida_bytes.create_data(screen_ea, ida_bytes.FF_DWORD, 4, idaapi.BADNODE)
     print("got return: ", ret)
     idc.MakeArray(screen_ea, 6)
Exemple #10
0
def get_codeblock(ea=None):
    if ea is None:
        ea = idaapi.get_screen_ea()
    flowchart_ = get_flowchart(ea)
    for code_block in flowchart_:
        if code_block.startEA <= ea < code_block.endEA:
            return code_block
Exemple #11
0
    def show_fill_form(self):
        selection, start_ea, end_ea = idaapi.read_selection()

        if not selection:
            start_ea = idaapi.get_screen_ea()
            end_ea = start_ea + 1

        # Default fill value
        fill_value = 0x00

        # Create the form
        f = PatchFillForm(start_ea, end_ea, fill_value)

        # Execute the form
        ok = f.Execute()
        if ok == 1:

            # Get updated values
            start_ea = f.intStartEA.value
            end_ea = f.intEndEA.value
            fill_value = f.intPatch.value

            # Now apply newly patched bytes
            # NOTE: fill_value is expected to be one byte
            #       so if a user provides a larger patch_byte()
            #       will trim the value as expected.

            for ea in range(start_ea, end_ea):
                idaapi.patch_byte(ea, fill_value)

            # Refresh all IDA views
            self.patch_view.Refresh()

        # Dispose the form
        f.Free()
Exemple #12
0
def JumpToTop():
    curr_ea = idaapi.get_screen_ea()
    curr_func = idaapi.get_func(curr_ea)
    if not curr_func:
        return
    begin = curr_func.startEA
    idaapi.jumpto(begin)
def google_search():
    """
    Search for the API function at cursor.
    """

    if using_ida7api:
        current_instruction = idaapi.get_screen_ea(
        )  #get the address at the cursor
        API = idc.print_operand(current_instruction, 0)  #get the function name
        if ' ' in API or len(API) < 4:
            print('SearchApi: Please select a call instruction.')
        else:
            #in case a segment register gets copied with the API

            API = API[API.index(':') + 1:] if ':' in API else API
            webbrowser.open_new_tab('https://www.google.com/search?q=' + API +
                                    '+MSDN')
    else:

        current_instruction = idaapi.ScreenEA()
        API = idc.GetOpnd(current_instruction, 0)
        if ' ' in API or len(API) < 4:
            print('SearchApi: Please select a call instruction.')
        else:
            API = API[API.index(':') + 1:] if ':' in API else API
            webbrowser.open_new_tab('https://www.google.com/search?q=' + API +
                                    '+MSDN')

    return
    def auto_map_lvars(self, vdui=None, start_ea=None):
        func = None
        if start_ea is None:
            func = idaapi.get_func(idaapi.get_screen_ea())
            start_ea = func.startEA
        if vdui is None:
            vdui = idaapi.get_tform_vdui(idaapi.get_current_tform())
            if vdui is None:
                idaapi.jumpto(start_ea)
                vdui = idaapi.get_tform_vdui(idaapi.get_current_tform())
        if func is None:
            func = idaapi.get_func(start_ea)
        self.de = idaapi.decompile(func)
        mapped_vars = False
        did_stuff = False
        self.assignments, overall_refs = self.analyze_fn()
        if self.map_vars_used_only_once(vdui, overall_refs):
            did_stuff = True
            mapped_vars = True
        elif self.map_lvars(vdui):
            did_stuff = True
            mapped_vars = True

        if mapped_vars:
            vdui.refresh_view(True)
        elif did_stuff:
            vdui.refresh_ctext()
        return did_stuff
Exemple #15
0
def get_codeblock(ea=None):
    if ea is None:
        ea = idaapi.get_screen_ea()
    flowchart_ = get_flowchart(ea)
    for code_block in flowchart_:
        if code_block.startEA <= ea < code_block.endEA:
            return code_block
Exemple #16
0
    def activate(self, ctx):
        if self.action == ACTION_HX_REMOVERETTYPE:
            if IDA7:
                vdui = idaapi.get_widget_vdui(ctx.widget)
            else:
                vdui = idaapi.get_tform_vdui(ctx.form)
            self.remove_rettype(vdui)
            vdui.refresh_ctext()
        elif self.action == ACTION_HX_COPYEA:
            ea = idaapi.get_screen_ea()
            if ea != idaapi.BADADDR:
                copy_to_clip("0x%X" % ea)
                print "Address 0x%X has been copied to clipboard" % ea
        elif self.action == ACTION_HX_COPYNAME:
            if IDA7:
                name = idaapi.get_highlight(idaapi.get_current_viewer())[0]
            else:
                name = idaapi.get_highlighted_identifier()
            if name:
                copy_to_clip(name)
                print "%s has been copied to clipboard" % name
        else:
            return 0

        return 1
Exemple #17
0
def main():
    ea = idaapi.get_screen_ea()

    # export entry = tuple(index, ordinal, address, name)
    exports = {export[2]: export for export in idautils.Entries()}

    # list of tuple(xref_address, export_name, xref_offset)
    exported_xrefs = []

    xrefs = [x.frm for x in idautils.XrefsTo(ea)]
    for xref in xrefs:
        func = idaapi.get_func(xref)
        if func and func.startEA in exports:
            exported_xrefs.append(
                (xref, exports[func.startEA][3], xref - func.startEA))

    if exported_xrefs:
        delim = "=" * 80
        print delim
        print "Dumping exported xrefs for:  %s  %s" % (idaapi.get_name(
            ea, ea), idahex(ea))
        print delim
        for exported_xref in exported_xrefs:
            print "%s  %s + 0x%X" % (idahex(
                exported_xref[0]), exported_xref[1], exported_xref[2])
    else:
        print "%s  %shas no exported xrefs." % (idahex(ea),
                                                idaapi.get_name(ea, ea) or "")
Exemple #18
0
    def activate(self, ctx):
        if self.action == ACTION_HX_REMOVERETTYPE:
            if IDA7:
                vdui = idaapi.get_widget_vdui(ctx.widget)
            else:
                vdui = idaapi.get_tform_vdui(ctx.form)
            self.remove_rettype(vdui)
            vdui.refresh_ctext()
        elif self.action == ACTION_HX_COPYEA:
            ea = idaapi.get_screen_ea()
            if ea != idaapi.BADADDR:
                copy_to_clip("0x%X" % ea)
                print("Address 0x%X has been copied to clipboard" % ea)
        elif self.action == ACTION_HX_COPYNAME:
            if IDA7:
                name = idaapi.get_highlight(idaapi.get_current_viewer())[0]
            else:
                name = idaapi.get_highlighted_identifier()
            if name:
                copy_to_clip(name)
                print("%s has been copied to clipboard" % name)
        elif self.action == ACTION_HX_GOTOCLIP:
            loc = parse_location(clip_text())
            print("Goto location 0x%x" % loc)
            Jump(loc)
        else:
            return 0

        return 1
Exemple #19
0
    def _handle_btn_run_query(self):
        self._commit_settings()
        settings = self._get_settings()
        qo = compile_code(settings)
        if qo:
            scope = settings.scope
            if scope == 0:
                ea_list = list(idautils.Functions())
            elif scope == 1 or scope == 2:
                screen_ea = idaapi.get_screen_ea()
                ea_list = []
                if scope == 1:
                    ea_list.append(screen_ea)
                else:
                    ea_list = get_func_xrefs(screen_ea)
            elif scope == 3 and settings.query_type == 0:
                ea_list = qo.get_scope()
            else:
                idaapi.warning("%s: invalid scope!" % SCRIPT_NAME)
                return

            # if the query is a function
            if settings.query_type == 0:
                # call init() and check whether it is ok to run this query
                if qo.init():
                    # run query on ea_list
                    run_query(qo.run, ea_list, settings)
                    # call cleanup/exit function
                    qo.exit()
            # otherwise it is a lambda expression
            else:
                run_query(qo, ea_list, settings)
        return
Exemple #20
0
 def slot_checkbox_limit_features_by_ea(self, state):
     """ """
     if state == QtCore.Qt.Checked:
         self.view_rulegen_features.filter_items_by_ea(
             idaapi.get_screen_ea())
     else:
         self.view_rulegen_features.show_all_items()
Exemple #21
0
def main():
        eip = idaapi.get_screen_ea();
        function = idaapi.func_item_iterator_t();
        function.set(idaapi.get_func(eip));
        	
        b_ok = function.first();
        while b_ok:
                pc = function.current();
                inslen = idaapi.decode_insn(function.current());
                if inslen == 0:
                        b_ok = function.next_code();
                        continue;	
                if inst_is_call(pc):
			color = get_blue();
			if is_indirect(pc):
				color = get_green();
			idc.SetColor(pc, CIC_ITEM, color);
		elif inst_is_ret(pc):			                      
                        color = get_red();
			idc.SetColor(pc, CIC_ITEM, color);	
                elif inst_is_jcc(pc):                                      
                        color = get_yellow();
			if is_indirect(pc):
				color = get_green();
			idc.SetColor(pc, CIC_ITEM, color);
                b_ok = function.next_code();		
Exemple #22
0
def main():
    if not idaapi.init_hexrays_plugin():
        return False

    f = idaapi.get_func(idaapi.get_screen_ea())
    if f is None:
        print "Please position the cursor within a function"
        return True

    cfunc = idaapi.decompile(f)
    if cfunc is None:
        print "Failed to decompile!"
        return True

    with open(SUPER_DUPER_OUTPUT, 'w') as f:
        sv = cfunc.get_pseudocode()
        for sline in sv:
            removido = idaapi.tag_remove(sline.line)
            if 'DoAssert' in removido:
                #This might be the ugliest code I've ever written, but hey it works ¯\_(ツ)_/¯
                removido = removido.lstrip()[9:].replace(');', '').split(',')
                removido = map(lambda x: x.lstrip(), removido)

                if len(removido[0]) > 4 and removido[0][0] == 'a':
                    removido = removido[0]
                else:
                    removido = removido[1]
                f.write(get_string(get_name_ea_simple(removido)) + '\n')
            elif 'case' in removido:
                #lstrip is bae and saviour of bad code
                f.write('Command ' +
                        removido.lstrip()[4:].replace(':', '').lstrip() + '\n')

    return True
Exemple #23
0
 def activate(self, ctx):
     screen_ea = idaapi.get_screen_ea()
     gen_xrefs = idautils.XrefsTo(screen_ea, 0)
     for xx in gen_xrefs:
         ref_loc = xx.frm
         print("Creating switch idiom at ea: ", hex(ref_loc))
         jmp_loc = ref_loc + 14
         print("Jump instruction should be at: ", hex(jmp_loc))
         ins = idautils.DecodeInstruction(jmp_loc)
         name = ins.get_canon_mnem()
         if name != "jmp":
             print("Warning found instruction ", name)
             continue
         if ins.Op1.type != idaapi.o_reg:
             print("Warning found non reg as operand")
             continue
         reg_num = ins.Op1.reg
         reg_name = idaapi.get_reg_name(reg_num, 8)
         print("Jump register is named ", reg_name)
         s = idaapi.switch_info_t()
         s.flags |= idaapi.SWI_SIGNED | idaapi.SWI_ELBASE
         s.elbase = screen_ea
         s.set_jtable_element_size(4)
         s.ncases = 6
         s.set_expr(reg_num, 7)
         s.jumps = screen_ea
         s.startea = jmp_loc
         idaapi.set_switch_info(jmp_loc, s)
         idaapi.create_switch_table(jmp_loc, s)
     return 1
Exemple #24
0
 def currentType(self, check=CHECK_NONE, **kwargs):
     tnm = None
     if self.typeid:
         tnm = self.typeid
     else:
         nm = idc.Name(idaapi.get_screen_ea())
         if nm and nm.startswith('vtbl_'):
             tnm = nm[5:]
     if not tnm:
         obj = MODS.explore.Explore(self.typeid).getVar()
         if obj:
             tnm = obj[-1].get('type')
     if not tnm:
         raise self.TypeNotExistsError("Type not found")
     tnm = tnm.replace('*', '').strip()
     tpdescr = {'name': tnm}
     sid = idc.GetStrucIdByName(tnm)
     if sid != idc.BADADDR:
         tpdescr['id'] = sid
     svid = idc.GetStrucIdByName(tnm + 'Vtbl')
     if svid != idc.BADADDR:
         tpdescr['vtblid'] = svid
         tpdescr['vtblnm'] = tnm + 'Vtbl'
     else:
         tpdescr = self.getTypeVtbl(tpdescr)
     ea = idc.LocByName('vtbl_' + tnm)
     if ea != idc.BADADDR:
         tpdescr['vtblea'] = ea
     if check == self.CHECK_VTBL and not tpdescr.get('vtblea'):
         raise self.TypeNotExistsError("vtbl not found", tnm)
     return tpdescr
Exemple #25
0
def main():
    eip = idaapi.get_screen_ea()
    function = idaapi.func_item_iterator_t()
    function.set(idaapi.get_func(eip))

    b_ok = function.first()
    while b_ok:
        pc = function.current()
        inslen = idaapi.decode_insn(function.current())
        if inslen == 0:
            b_ok = function.next_code()
            continue
        if inst_is_call(pc):
            color = get_blue()
            if is_indirect(pc):
                color = get_green()
            idc.SetColor(pc, CIC_ITEM, color)
        elif inst_is_ret(pc):
            color = get_red()
            idc.SetColor(pc, CIC_ITEM, color)
        elif inst_is_jcc(pc):
            color = get_yellow()
            if is_indirect(pc):
                color = get_green()
            idc.SetColor(pc, CIC_ITEM, color)
        b_ok = function.next_code()
Exemple #26
0
def JumpToBottom():
    curr_ea = idaapi.get_screen_ea()
    curr_func = idaapi.get_func(curr_ea)
    if not curr_func:
        return
    begin = idaapi.prevaddr(curr_func.endEA)
    idaapi.jumpto(begin)    
Exemple #27
0
    def run(self, arg):
        try:
            self._data = dict()
            fn = idaapi.get_func(idaapi.get_screen_ea())

            if idaapi.IDA_SDK_VERSION >= 700:
                orig_name = idaapi.get_func_name(idaapi.get_screen_ea())
                addr_str = '{:x}'.format(self.start_ea_of(fn))
                print("checking function start addr: ", addr_str)

                #set default name
                if orig_name.lower().find(addr_str):
                    default_name = orig_name
                else:
                    default_name = orig_name + '_' + addr_str  #append current function address as sufix as default

                user_name = idaapi.ask_str(default_name, 0, 'New name:')
            else:
                user_name = idaapi.askstr(
                    0, default_name,
                    'New name:')  #jeanfixme: check old version support

            if user_name == '':
                return
            if orig_name == user_name:
                return

            #if len(fn_an['math']) < self._MIN_MAX_MATH_OPS_TO_ALLOW_RENAME: jeanfixme: check the max length can be set here
            force_name(self.start_ea_of(fn), user_name)

            print("rename \"" + str(orig_name) + "\" to " + str(user_name))

            user_prefix = user_name.lower().replace(addr_str, '')
            query = 'Use \"' + user_prefix + '\" to rename the callers\' names'
            #yesno= idaapi.askyn_c(1, query) jeanfixme: check how to interact with user
            yesno = idaapi.ask_str(
                "yes", 0, query)  #jeanfixme: check how to interact with user
            #user the rename the parrents

            if yesno == 'yes':
                #rename the parent
                print "start rename parents.."
                self.rename_parents(fn, user_prefix, 1)

        except:
            idaapi.msg('Ancestor RE: error: %s\n' % traceback.format_exc())
Exemple #28
0
 def __init__(self, id_ea=None, bb=None, fc=None):
     if bb is None and fc is None:
         if id_ea is None:
             id_ea = idaapi.get_screen_ea()
         temp_codeblock = get_codeblock(id_ea)
         self.__dict__.update(temp_codeblock.__dict__)
     else:
         super(CodeBlock, self).__init__(id=id_ea, bb=bb, fc=fc)
Exemple #29
0
 def __init__(self, id_ea=None, bb=None, fc=None):
     if bb is None and fc is None:
         if id_ea is None:
             id_ea = idaapi.get_screen_ea()
         temp_codeblock = get_codeblock(id_ea)
         self.__dict__.update(temp_codeblock.__dict__)
     else:
         super(CodeBlock, self).__init__(id=id_ea, bb=bb, fc=fc)
Exemple #30
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))
Exemple #31
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))
Exemple #32
0
def get_codeblock(ea=None):
    if ea is None:
        ea = idaapi.get_screen_ea()
    flowchart_ = get_flowchart(ea)
    for code_block in flowchart_:
        if code_block.startEA == ea:  # External blocks can be zero-sized.
            return code_block
        if code_block.startEA <= ea < code_block.endEA:
            return code_block
Exemple #33
0
def nop():
    """Nops-out the current instruction and advance the cursor to the next instruction."""
    ea = idaapi.get_screen_ea()
    num_bytes = idc.get_item_size(ea)
    for i in range(num_bytes):
        ida_bytes.patch_byte(ea, 0x90)
        ea += 1
    ida_kernwin.refresh_idaview_anyway()
    ida_kernwin.jumpto(ea)
Exemple #34
0
 def query_function_callback(self, threshold=0.4):
     func_ea = idaapi.get_screen_ea()
     targets = self.query_function(func_ea)
     func_name = idaapi.get_func_name(func_ea)
     if targets[0]['score'] < threshold:
         print(
             "[BinaryAI] {} is skipped because top1_score lower than threshold({})"
             .format(func_name, threshold))
         return
     SourceCodeViewer(func_name, targets).Show()
Exemple #35
0
    def translate_notice(self):
        if not self.dbg_dialect:
            rs_log("idb isn't synced yet, can't translate")
            return

        ea = idaapi.get_screen_ea()
        mod = self.name.split('.')[0].strip()
        cmd = self.dbg_dialect['prefix'] + "translate 0x%x 0x%x %s" % (self.base, ea, mod)
        self.notice_broker("cmd", "\"cmd\":\"%s\"" % cmd)
        rs_debug("translate address 0x%x" % ea)
Exemple #36
0
    def decompile(self, ea, regs=None):
        if regs == None:
            self.regs = dict(r0='arg0',
                             r1='arg1',
                             r2='arg2',
                             r3=None,
                             r4=None,
                             r5=None,
                             r6=None,
                             r7=None,
                             r8=None,
                             r9=None,
                             r10=None,
                             r11=None,
                             r12=None,
                             r13=None,
                             r14=None,
                             r15=None,
                             trash=None)
        else:
            self.regs = regs

        if ea in self.decompiled:
            return

        # print 'Decompiling %08X' % ea

        while True:
            if ea in self.decompiled:
                break
            self.decompiled.append(ea)
            self.ea = ea

            if ea == idaapi.get_screen_ea():
                for name in self.regs:
                    print '%s == %s' % (name, self.regs[name])

            mnem, ops, branches = self.ida.getInsn(ea)
            self.dispatch(ea, mnem, ops)

            if len(branches) == 0:
                break
            elif len(branches) == 1:
                ea = branches[0]
                continue
            else:
                curfunc = self.ida.getFunc(ea)
                for branch in branches:
                    nextfunc = self.ida.getFunc(branch)

                    if nextfunc != curfunc:
                        self.decompile(branch)
                    else:
                        self.decompile(branch, regs=self.regs)
                break
Exemple #37
0
    def bp_notice(self, oneshot=False):
        if not self.is_active:
            print "[sync] idb isn't enabled, bp can't be set"
            return

        ea = idaapi.get_screen_ea()
        offset = self.rebase_remote(ea)
        cmd = "%s0x%x" % (self.dbg_dialect['bp1' if oneshot else 'bp'], offset)

        self.notice_broker("cmd", "\"cmd\":\"%s\"" % cmd)
        print "[sync] >> set %s" % cmd
Exemple #38
0
    def hbp_notice(self, oneshot=False):
        if not self.is_active:
            print "[sync] idb isn't enabled, hbp can't be set"
            return

        ea = idaapi.get_screen_ea()
        offset = self.rebase_remote(ea)
        cmd = "ba e 1 %s 0x%x" % ("/1" if oneshot else "", offset)

        self.notice_broker("cmd", "\"cmd\":\"%s\"" % cmd)
        print "[sync] >> set %s" % cmd
Exemple #39
0
    def hbp_notice(self, oneshot=False):
        if not self.is_active:
            rs_log("idb isn't enabled, hbp can't be set")
            return

        ea = idaapi.get_screen_ea()
        offset = self.rebase_remote(ea)
        cmd = "%s0x%x" % (self.dbg_dialect['hbp1' if oneshot else 'hbp'], offset)

        self.notice_broker("cmd", "\"cmd\":\"%s\"" % cmd)
        rs_log(">> set %s" % cmd)
Exemple #40
0
    def hbp_notice(self, oneshot=False):
        if not self.is_active:
            print "[sync] idb isn't enabled, hbp can't be set"
            return

        ea = idaapi.get_screen_ea()
        offset = self.rebase_remote(ea)
        cmd = "%s0x%x" % (self.dbg_dialect["hbp1" if oneshot else "hbp"], offset)

        self.notice_broker("cmd", '"cmd":"%s"' % cmd)
        print "[sync] >> set %s" % cmd
Exemple #41
0
    def translate_notice(self):
        if not self.dbg_dialect:
            print "[sync] idb isn't synced yet, can't translate"
            return

        ea = idaapi.get_screen_ea()
        mod = self.name.split(".")[0].strip()
        cmd = self.dbg_dialect["prefix"] + "translate 0x%x 0x%x %s" % (self.base, ea, mod)

        self.notice_broker("cmd", '"cmd":"%s"' % cmd)
        print "[sync] translate address 0x%x" % ea
Exemple #42
0
    def bp_notice(self, oneshot=False):
        if not self.is_active:
            print "[sync] idb isn't enabled, bp can't be set"
            return

        ea = idaapi.get_screen_ea()
        offset = self.rebase_remote(ea)
        cmd = "%s0x%x" % (self.dbg_dialect['bp1' if oneshot else 'bp'], offset)

        self.notice_broker("cmd", "\"cmd\":\"%s\"" % cmd)
        print "[sync] >> set %s" % cmd
Exemple #43
0
def get_cursor_func_ref():
    """
    Get the function reference under the user cursor.

    Returns BADADDR or a valid function address.
    """
    current_tform  = idaapi.get_current_tform()
    tform_type     = idaapi.get_tform_type(current_tform)

    # get the hexrays vdui (if available)
    vu = idaapi.get_tform_vdui(current_tform)

    #
    # hexrays view is active
    #

    if vu:
        cursor_addr = vu.item.get_ea()

    #
    # disassembly view is active
    #

    elif tform_type == idaapi.BWN_DISASM:
        cursor_addr = idaapi.get_screen_ea()

        #
        # if the cursor is over an operand value that has a function ref,
        # use that as a valid rename target
        #

        op_addr = idc.GetOperandValue(cursor_addr, idaapi.get_opnum())
        op_func = idaapi.get_func(op_addr)
        if op_func and op_func.startEA == op_addr:
            return op_addr

    # unsupported/unknown view is active
    else:
        return idaapi.BADADDR

    #
    # if the cursor is over a function definition or other reference, use that
    # as a valid rename target
    #

    cursor_func = idaapi.get_func(cursor_addr)
    if cursor_func and cursor_func.startEA == cursor_addr:
        return cursor_addr

    # fail
    return idaapi.BADADDR
Exemple #44
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
Exemple #45
0
 def getFunc(self, ea=None, next=False):
     if ea == None:
         ea = idaapi.get_screen_ea()
     
     if next:
         ea = idc.NextFunction(ea)
         if ea == -1:
             return (0xFFFFFFFFL, 0xFFFFFFFFL)
     
     if ea < 0:
         return (0xFFFFFFFFL, 0xFFFFFFFFL)
     elif idc.GetFunctionName(ea) == idc.GetFunctionName(idc.PrevAddr(ea)):
         ea = idc.PrevFunction(ea)
     return (ea, idc.FindFuncEnd(ea))
Exemple #46
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
Exemple #47
0
 def OnViewCurpos(self):
   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 or None
       if (self.addr is not None) and (self.addr != qira_address):
         #idaapi.msg("[QIRA Plugin] Qira Address %x \n" % (self.addr))
         # 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
Exemple #48
0
 def decompile(self, ea, regs=None):
     if regs == None:
         self.regs = dict(
             r0 ='arg0', r1 ='arg1', r2 ='arg2', r3 =None,
             r4 =None, r5 =None, r6 =None, r7 =None,
             r8 =None, r9 =None, r10=None, r11=None,
             r12=None, r13=None, r14=None, r15=None,
             trash=None
         )
     else:
         self.regs = regs
     
     if ea in self.decompiled:
         return
     
     # print 'Decompiling %08X' % ea
     
     while True:
         if ea in self.decompiled:
             break
         self.decompiled.append(ea)
         self.ea = ea
         
         if ea == idaapi.get_screen_ea():
             for name in self.regs:
                 print '%s == %s' % (name, self.regs[name])
         
         mnem, ops, branches = self.ida.getInsn(ea)
         self.dispatch(ea, mnem, ops)
         
         if len(branches) == 0:
             break
         elif len(branches) == 1:
             ea = branches[0]
             continue
         else:
             curfunc = self.ida.getFunc(ea)
             for branch in branches:
                 nextfunc = self.ida.getFunc(branch)
                 
                 if nextfunc != curfunc:
                     self.decompile(branch)
                 else:
                     self.decompile(branch, regs=self.regs)
             break
    def show_import_form(self):
        selection, start_ea, end_ea = idaapi.read_selection()

        if not selection:
            start_ea = idaapi.get_screen_ea()
            end_ea = start_ea + 1

        # Create the form
        f = DataImportForm(start_ea, end_ea);

        # Execute the form
        ok = f.Execute()
        if ok == 1:

            start_ea = f.intStartEA.value
            end_ea = f.intEndEA.value

            if f.rFile.selected:
                imp_file = f.impFile.value

                try:
                    f_imp_file = open(imp_file,'rb+')
                except Exception, e:
                    idaapi.warning("File I/O error({0}): {1}".format(e.errno, e.strerror))
                    return
                else:
                    buf = f_imp_file.read()
                    f_imp_file.close()

            else:

                buf = f.strPatch.value

                # Hex values, unlike string literal, needs additional processing
                if f.rHex.selected:
                    buf = buf.replace(' ','')       # remove spaces
                    buf = buf.replace('\\x','')     # remove '\x' prefixes
                    buf = buf.replace('0x','')      # remove '0x' prefixes
                    try:
                        buf = binascii.unhexlify(buf)   # convert to bytes
                    except Exception, e:
                        idaapi.warning("Invalid input: %s" % e)
                        f.Free()
                        return
    def show_edit_form(self):
        selection, start_ea, end_ea = idaapi.read_selection()
        
        if not selection:
            start_ea = idaapi.get_screen_ea()
            end_ea = start_ea + 1
        if start_ea != idaapi.BADADDR and end_ea != idaapi.BADADDR:
            if end_ea > start_ea:
                buf_len = end_ea - start_ea
                buf = get_many_bytes(start_ea, buf_len) or "\xFF"*buf_len
                buf_str = " ".join(["%02X" % ord(x) for x in buf])

                fpos = idaapi.get_fileregion_offset(start_ea)

                addr_str = "%#X" % start_ea
                fpos_str = "%#x" % fpos if fpos != -1 else "N/A" 

                f = PatchEditForm(addr_str, fpos_str, buf_str, buf_str)

                # Execute the form
                ok = f.Execute()
                if ok == 1:

                    # Convert hex bytes to binary
                    buf = f.strPatch.value
                    buf = buf.replace(' ','')       # remove spaces
                    buf = buf.replace('\\x','')     # remove '\x' prefixes
                    buf = buf.replace('0x','')      # remove '0x' prefixes
                    try:
                        buf = binascii.unhexlify(buf)   # convert to bytes
                    except Exception, e:
                        idaapi.warning("Invalid input: %s" % e)
                        f.Free()
                        return

                    # Now apply newly patched bytes
                    idaapi.patch_many_bytes(start_ea, buf)

                    # Refresh all IDA views
                    self.patch_view.refreshitems()
                    idaapi.refresh_idaview_anyway()

                # Dispose the form
                f.Free()
Exemple #51
0
    def run(self, arg):
        idaapi.msg("[%s] Syncing with WS Server\n" % (self.wanted_name,))
        self.addr = idaapi.get_screen_ea()
        if self.old_addr != self.addr:
            # check against idc.BADADDR and None before going
            if (self.addr is not None) and (self.addr != idc.BADADDR):
                # Code Address
                if idaapi.isCode(idaapi.getFlags(self.addr)):
                    # don't set the address if it's already the qira_address
                    if self.addr != self.qira_address:
                        # debugging
                        if DEBUG:
                            idaapi.msg(
                                "[%s] Qira Address 0x%x \n" %
                                (self.wanted_name, self.addr,))
                        # Instruction Address
                        self.set_qira_address(self.addr)
                        self.update_address("iaddr", self.addr)
                # Data Address
                elif idaapi.isData(idaapi.getFlags(self.addr)):
                    self.update_address("daddr", self.addr)
                # Tail Address
                elif idaapi.isTail(idaapi.getFlags(self.addr)):
                    self.update_address("taddr", self.addr)
                # Unknown Address
                elif idaapi.isUnknown(idaapi.getFlags(self.addr)):
                    self.update_address("uaddr", self.addr)
                # Head Address
                elif idaapi.isHead(idaapi.getFlags(self.addr)):
                    self.update_address("haddr", self.addr)
                # Flow Address
                elif idaapi.isFlow(idaapi.getFlags(self.addr)):
                    self.update_address("faddr", self.addr)
                # Var Address
                elif idaapi.isVar(idaapi.getFlags(self.addr)):
                    self.update_address("vaddr", self.addr)
                # Data Address
                else:
                    self.update_address("daddr", self.addr)

        self.old_addr = self.addr
Exemple #52
0
def main():
    if not idaapi.init_hexrays_plugin():
        return False

    print "Hex-rays version %s has been detected" % idaapi.get_hexrays_version()

    f = idaapi.get_func(idaapi.get_screen_ea());
    if f is None:
        print "Please position the cursor within a function"
        return True

    cfunc = idaapi.decompile(f);
    if cfunc is None:
        print "Failed to decompile!"
        return True

    sv = cfunc.get_pseudocode();
    for sline in sv:
        print idaapi.tag_remove(sline.line);

    return True
    def show_fill_form(self):
        selection, start_ea, end_ea = idaapi.read_selection()
        
        if not selection:
            start_ea = idaapi.get_screen_ea()
            end_ea = start_ea + 1
        
        # Default fill value
        fill_value = 0x90 #nop

        # Create the form
        f = PatchFillForm(start_ea, end_ea, fill_value)

        # Execute the form
        ok = f.Execute()
        if ok == 1:

            # Get updated values
            start_ea = f.intStartEA.value
            end_ea = f.intEndEA.value
            fill_value = f.intPatch.value

            # Now apply newly patched bytes
            # NOTE: fill_value is expected to be one byte
            #       so if a user provides a larger patch_byte()
            #       will trim the value as expected.


            for ea in range(start_ea, end_ea):
                idaapi.patch_byte(ea, fill_value)

            # Refresh all IDA views
            self.patch_view.refreshitems()
            idaapi.refresh_idaview_anyway()

        # Dispose the form
        f.Free()
Exemple #54
0
import idc
import idaapi
import idautils
from sets import Set
from collections import defaultdict

c = idaapi.decompile(idaapi.get_screen_ea())
func_ea = c.entry_ea

class BasicBlock():
    def __init__(self):
        self.start = 0
        self.end = 0
        self.succs = Set()
        self.preds = Set()
    def isIn(ea):
        return ea>=self.start and ea<=self.end

def CFG(function_ea):

    f_start = function_ea
    f_end = FindFuncEnd(function_ea)
    
    edges = Set()
    boundaries = Set((f_start,))
    
    # For each defined element in the function.
    for head in Heads(f_start, f_end):
    
        # If the element is an instruction
        if isCode(GetFlags(head)):
Exemple #55
0
 def translate_notice(self):
     ea = idaapi.get_screen_ea()
     mod = self.name.split('.')[0].strip()
     cmd = "!translate 0x%x 0x%x %s" % (self.base, ea, mod)
     self.notice_broker("cmd", "\"cmd\":\"%s\"" % cmd)
     print "[sync] translate address 0x%x" % ea
Exemple #56
0
def run():
    
    cfunc = idaapi.decompile(idaapi.get_screen_ea())
    if not cfunc:
        print 'Please move the cursor into a function.'
        return
    
    entry_ea = cfunc.entry_ea
    print "Dump of user-defined information for function at %x" % (entry_ea, )
    
    # Display user defined labels.
    labels = idaapi.restore_user_labels(entry_ea);
    if labels is not None:
        print "------- %u user defined labels" % (len(labels), )
        for org_label, name in labels.iteritems():
            print "Label %d: %s" % (org_label, str(name))
        idaapi.user_labels_free(labels)
    
    # Display user defined comments
    cmts = idaapi.restore_user_cmts(entry_ea);
    if cmts is not None:
        print "------- %u user defined comments" % (len(cmts), )
        for tl, cmt in cmts.iteritems():
            print "Comment at %x, preciser %x:\n%s\n" % (tl.ea, tl.itp, str(cmt))
        idaapi.user_cmts_free(cmts)
    
    # Display user defined citem iflags
    iflags = idaapi.restore_user_iflags(entry_ea)
    if iflags is not None:
        print "------- %u user defined citem iflags" % (len(iflags), )
        for cl, t in iflags.iteritems():
            print "%a(%d): %08X%s" % (cl.ea, cl.op, f, " CIT_COLLAPSED" if f & CIT_COLLAPSED else "")
        idaapi.user_iflags_free(iflags)

    # Display user defined number formats
    numforms = idaapi.restore_user_numforms(entry_ea)
    if numforms is not None:
        print "------- %u user defined number formats" % (len(numforms), )
        for ol, nf in numforms.iteritems():
            
            print "Number format at %a, operand %d: %s" % (ol.ea, ol.opnum, "negated " if (nf.props & NF_NEGATE) != 0 else "")
            
            if nf.isEnum():
                print "enum %s (serial %d)" % (str(nf.type_name), nf.serial)
                
            elif nf.isChar():
                print "char"
                
            elif nf.isStroff():
                print "struct offset %s" % (str(nf.type_name), )
                
            else:
                print "number base=%d" % (idaapi.getRadix(nf.flags, ol.opnum), )
        
        idaapi.user_numforms_free(numforms)

    # Display user-defined local variable information
    # First defined the visitor class
    class dump_lvar_info_t(idaapi.user_lvar_visitor_t):
    
        def __init__(self):
            idaapi.user_lvar_visitor_t.__init__(self)
            self.displayed_header = False
            return
        
        def get_info_qty_for_saving(self):
            return 0
        
        def get_info_for_saving(self, lv):
            return False
        
        def handle_retrieved_info(self, lv):
            
            try:
                if not self.displayed_header:
                    self.displayed_header = True;
                    print "------- User defined local variable information"
                
                print "Lvar defined at %x" % (lv.ll.defea, )
                
                if len(str(lv.name)):
                    print "  Name: %s" % (str(lv.name), )
                
                if len(str(lv.type)):
                    #~ print_type_to_one_line(buf, sizeof(buf), idati, .c_str());
                    print "  Type: %s" % (str(lv.type), )
                
                if len(str(lv.cmt)):
                    print "  Comment: %s" % (str(lv.cmt), )
            except:
                traceback.print_exc()
            return 0
    
        def handle_retrieved_mapping(self, lm):
            return 0
        
        def get_info_mapping_for_saving(self):
            return None
    
    # Now iterate over all user definitions
    dli = dump_lvar_info_t();
    idaapi.restore_user_lvar_settings(entry_ea, dli)
    
    return
Exemple #57
0
 def address(cls):
     """Current address"""
     return idaapi.get_screen_ea()
Exemple #58
0
def get_flowchart(ea=None):
    if ea is None:
        ea = idaapi.get_screen_ea()
    func = idaapi.get_func(ea)
    flowchart_ = FlowChart(func)
    return flowchart_