コード例 #1
0
 def remove_tag(self):
     current_comment = Extract(self._first_addr)._extract_func_cmnt(0)
     if string.find(current_comment, "[REDB: handled") == 0:
         last_index = string.find(current_comment, "]")
         final_comment = current_comment[last_index + 1:]
         Embed(self._first_addr)._embed_func_cmnt(final_comment, 0)
         idaapi.refresh_idaview_anyway()
コード例 #2
0
def InitialAnalysis_main():
    revokeAnalysis()

    # find unidentified functions
    findUnidentifiedFunctions()

    global InstructionCallbacks
    InstructionCallbacks = []
    InstructionCallbacks.append(CryptoTester())
    InstructionCallbacks.append(CallTester())

    iterateInstructions()

    # refresh ida view to display our results
    idaapi.refresh_idaview_anyway()

    #SetColorSiko
    setcolorsiko()

    #FuncRename
    ah = GENAPI()
    # To disable comments assign to False
    ah.comment = True
    # To disable renaming of functions to False
    ah.rename = True    
    ah.generic()

    print "InitialAnalysis completed"
コード例 #3
0
ファイル: SyncPlugin.py プロジェクト: tmr232/ret-sync
    def parse_exec(self, req):
        if req == '':
            return

        if not (req[0:6] == '[sync]'):
            print "\[<] bad hdr %s" % repr(req)
            print '[-] Request dropped due to bad header'
            return

        req = self.normalize(req, 6)
        try:
            hash = json.loads(req)
        except:
            print "[-] Sync failed to parse json\n %s" % req
            print "------------------------------------"
            return

        type = hash['type']
        if not type in self.req_handlers:
            print("[*] unknown request: %s" % type)
            return

        req_handler = self.req_handlers[type]

        # few requests are handled even though idb is not enable
        if type in ['broker', 'dialect', 'bc']:
            req_handler(hash)
        else:
            if self.is_active:
                req_handler(hash)
            else:
                # otherwise, silently drop the request if idb is not enabled
                return

        idaapi.refresh_idaview_anyway()
コード例 #4
0
 def remove_tag(self):
     current_comment = Extract(self._first_addr)._extract_func_cmnt(0)
     if string.find(current_comment, "[REDB: handled") == 0:
         last_index = string.find(current_comment, "]")
         final_comment = current_comment[last_index + 1:]
         Embed(self._first_addr)._embed_func_cmnt(final_comment, 0)
         idaapi.refresh_idaview_anyway()
コード例 #5
0
    def handleQuickInstHook(self, address, once, breakpoint=False):
        # safety checks, can be start of the function
        if address in self.idbHookMap and self.idbHookMap[
                address].hook.type == "func":
            dlg = AskYN(
                0,
                "Address contains function hook!\nDo you want to remove it?")
            if dlg != 1:
                return
            # remove function hook
            self.handleUnhookFunc(address)

        offset, moduleName = self.getAddressDetails(address)

        hook = InstHook()
        hook.id = address
        hook.mnemonic = GetDisasm(address)
        hook.address = offset
        hook.module = moduleName
        hook.once = once
        hook.breakpoint = breakpoint

        entry = HookEntry(hook)
        outJSON = json.dumps({
            "req_id": kFridaLink_SetHookRequest,
            "data": entry.genSetRequest()
        })

        SetColor(address, CIC_ITEM, kIDAViewColor_HookedInst)
        refresh_idaview_anyway()
        self.clientSocket.sendto(outJSON, self.clientAddress)
        self.idbHookMap[address] = entry

        self.idbHooksView.setContent(self.idbHookMap)
コード例 #6
0
ファイル: pathfinder.py プロジェクト: IDA-RE-things/toolbag
    def OnCommand(self, cmd_id):
        """
        Triggered when a menu command is selected through the menu or its hotkey
        @return: None
        """
        #print "command:", cmd_id
        if self.cmd_close == cmd_id:
            self.Close()
            return
        elif self.cmd_color == cmd_id:

            func_item = idaapi.get_func(idc.ScreenEA())


            # get the default color
            idc.Jump(func_item.startEA)
            idautils.ProcessUiActions("GraphDefaultColor", 0)            
            defaultcolor = idc.GetColor(func_item.startEA, idc.CIC_ITEM)

            # reset colors to default
            idc.SetColor(func_item.startEA, idc.CIC_FUNC, defaultcolor)

            # RGB
            for block in self.blocks:
                start,end = self.getBounds(block)
               # color all basic blocks
                for head in idautils.Heads(start, end):
                    idc.SetColor(head, idc.CIC_ITEM, self.options['bb_path_color'])

                #branch_insn = idc.NextHead(end, func_item.endEA)
                #print "branch instruction is at 0x%08x" % branch_insn
                #idc.SetColor(branch_insn, idc.CIC_ITEM, self.options['bb_path_color'])
            
        idaapi.refresh_idaview_anyway()
コード例 #7
0
ファイル: SyncPlugin.py プロジェクト: IDA-RE-things/qb-sync
    def parse_exec(self, req):
        if req == '':
            return

        if not (req[0:6] == '[sync]'):
            print "\[<] bad hdr %s" % repr(req)
            print '[-] Request dropped due to bad header'
            return

        req = self.normalize(req, 6)
        try:
            hash = json.loads(req)
        except:
            print "[-] Sync failed to parse json\n %s" % req
            print "------------------------------------"
            return

        type = hash['type']
        if not type in self.req_handlers:
            print ("[*] unknown request: %s" % type)
            return

        req_handler = self.req_handlers[type]
        if type == 'broker':
            req_handler(hash)
        else:
            if self.is_active:
                req_handler(hash)
            else:
                # idb is not enabled, silently drop the request
                return

        idaapi.refresh_idaview_anyway()
コード例 #8
0
ファイル: gui.py プロジェクト: clayne/Classy
    def handle_vtable_interaction(self, row, column):
        if self.edit_class is None:
            return

        vm = self.edit_class.vmethods[row]

        if column == 0:  # Go to vtable offset
            idc.jumpto(self.edit_class.vtable_start + row * 4)
        elif column == 1:  # Go to address
            idc.jumpto(vm.ea)
        elif column == 2:  # Edit signature
            dlg = SignatureDialog(vm.return_type,
                                  vm.owner.name,
                                  vm.name,
                                  vm.args,
                                  vm.is_const,
                                  vm.ctor_type,
                                  vm.dtor_type,
                                  fixed_owner_type=True)
            if dlg.exec_() != QtWidgets.QDialog.Accepted:
                return
            vm.set_signature(dlg.name, dlg.args, dlg.return_type, dlg.is_const,
                             dlg.ctor_type, dlg.dtor_type)
            self.vtable.setItem(row, 2,
                                QtWidgets.QTableWidgetItem(vm.get_signature()))
            idaapi.refresh_idaview_anyway()
コード例 #9
0
ファイル: gui.py プロジェクト: clayne/Classy
    def handle_methods_interaction(self, row, column):
        if self.edit_class is None:
            return

        m = self.methods.item(row, 0).data(QtCore.Qt.UserRole)
        if type(
                m
        ) != database_entries.Method or m not in self.edit_class.methods:
            return

        elif column == 0:  # Go to address
            idc.jumpto(m.ea)
        elif column == 1:  # Edit signature
            dlg = SignatureDialog(m.return_type,
                                  m.owner.name,
                                  m.name,
                                  m.args,
                                  m.is_const,
                                  m.ctor_type,
                                  m.dtor_type,
                                  fixed_owner_type=True)
            if dlg.exec_() != QtWidgets.QDialog.Accepted:
                return
            m.set_signature(dlg.name, dlg.args, dlg.return_type, dlg.is_const,
                            dlg.ctor_type, dlg.dtor_type)
            self.methods.setItem(row, 1,
                                 QtWidgets.QTableWidgetItem(m.get_signature()))
            idaapi.refresh_idaview_anyway()
コード例 #10
0
    def OnCommand(self, cmd_id):
        """
        Triggered when a menu command is selected through the menu or its hotkey
        @return: None
        """
        #print "command:", cmd_id
        if self.cmd_close == cmd_id:
            self.Close()
            return
        elif self.cmd_color == cmd_id:

            func_item = idaapi.get_func(idc.ScreenEA())

            # get the default color
            idc.Jump(func_item.startEA)
            idautils.ProcessUiActions("GraphDefaultColor", 0)
            defaultcolor = idc.GetColor(func_item.startEA, idc.CIC_ITEM)

            # reset colors to default
            idc.SetColor(func_item.startEA, idc.CIC_FUNC, defaultcolor)

            # RGB
            for block in self.blocks:
                start, end = self.getBounds(block)
                # color all basic blocks
                for head in idautils.Heads(start, end):
                    idc.SetColor(head, idc.CIC_ITEM,
                                 self.options['bb_path_color'])

                #branch_insn = idc.NextHead(end, func_item.endEA)
                #print "branch instruction is at 0x%08x" % branch_insn
                #idc.SetColor(branch_insn, idc.CIC_ITEM, self.options['bb_path_color'])

        idaapi.refresh_idaview_anyway()
コード例 #11
0
ファイル: ui.py プロジェクト: youngjun-chang/Sark
    def __exit__(self, exc_type, exc_val, exc_tb):
        can_update = self.LOCK._is_owned()

        if can_update:
            idaapi.refresh_idaview_anyway()

        self.LOCK.release()
コード例 #12
0
ファイル: SyncPlugin.py プロジェクト: nihilus/qb-sync
    def parse_exec(self, req):
        if req == "":
            return

        if not (req[0:6] == "[sync]"):
            print "\[<] bad hdr %s" % repr(req)
            print "[-] Request dropped due to bad header"
            return

        req = self.normalize(req, 6)
        try:
            hash = json.loads(req)
        except:
            print "[-] Sync failed to parse json\n %s" % req
            print "------------------------------------"
            return

        type = hash["type"]
        if not type in self.req_handlers:
            print ("[*] unknown request: %s" % type)
            return

        req_handler = self.req_handlers[type]

        # few requests are handled even though idb is not enable
        if type in ["broker", "dialect", "bc"]:
            req_handler(hash)
        else:
            if self.is_active:
                req_handler(hash)
            else:
                # otherwise, silently drop the request if idb is not enabled
                return

        idaapi.refresh_idaview_anyway()
コード例 #13
0
	def handleReplaceFuncDel(self, screenEA = None):
		if screenEA is not None:
			func = get_func(screenEA)
		else:
			func = get_func(ScreenEA())
		if func is None:
			return

		repl_id = func.startEA;

		if repl_id not in self.funcReplaceMap:
			return

		entry = self.funcReplaceMap[repl_id]

		outJSON = json.dumps({
			"req_id": kFridaLink_DelReplaceRequest, 
			"data": entry.genDelRequest()
		})

		del self.funcReplaceMap[repl_id]
		self.clientSocket.sendto(outJSON, self.clientAddress)

		if entry.moduleImport == False:
			SetColor(repl_id, CIC_FUNC, kIDAViewColor_Reset)
			refresh_idaview_anyway()

		self.funcReplaceView.setContent(self.funcReplaceMap)
コード例 #14
0
    def handleQuickFuncHook(self, address, once):
        # safety checks, can be start of the function
        if address in self.idbHookMap and self.idbHookMap[
                address].hook.type == "inst":
            dlg = AskYN(
                0,
                "Address contains instruction hook!\nDo you want to remove it?"
            )
            if dlg != 1:
                return
            # remove instruction hook
            self.handleUnhookInst(address)

        offset, moduleName = self.getAddressDetails(address)

        hook = FuncHook()
        hook.id = address
        hook.symbol = get_func_name(address)
        hook.address = offset
        hook.module = moduleName
        hook.once = once

        entry = HookEntry(hook)
        outJSON = json.dumps({
            "req_id": kFridaLink_SetHookRequest,
            "data": entry.genSetRequest()
        })

        SetColor(address, CIC_FUNC, kIDAViewColor_HookedFunc)
        refresh_idaview_anyway()
        self.clientSocket.sendto(outJSON, self.clientAddress)
        self.idbHookMap[address] = entry

        self.idbHooksView.setContent(self.idbHookMap)
コード例 #15
0
 def clear_database(self):
     if ask_yes_no(
             'Are you really sure that you want to clear the Classy databse?\n',
             False):
         database.get().clear()
         self.gui.update_fields()
         idaapi.refresh_idaview_anyway()
コード例 #16
0
    def paint_hexrays(self, cfunc):
        sv = cfunc.get_pseudocode()

        lines_painted = 0

        for sline in sv:
            indexes = lex_citem_indexes(sline.line)
            for index in indexes:
                try:
                    item = cfunc.treeitems[index]
                    ea = item.ea

                # apparently this is a thing on IDA 6.95
                except IndexError as e:
                    continue

                col = idc.get_color(ea, CIC_ITEM)
                if col != BADADDR:
                    sline.bgcolor = col
                    lines_painted += 1

        if not lines_painted:
            return

        col = 0xccffcc

        for line_number in xrange(0, cfunc.hdrlines):
            sv[line_number].bgcolor = col

        idaapi.refresh_idaview_anyway()
コード例 #17
0
    def highlight_bracket2(self, ps, pos_brach, xpos, ypos):
        ln = ps[ypos].line[:]
        if (self.highl_brack.has_key(ypos) == False):
            self.clearbracket(ps, True)
            self.highl_brack[ypos] = ln
        else:
            ln = self.highl_brack[ypos]

        s1pos = idaapi.tag_advance(ln, pos_brach)
        s2pos = idaapi.tag_advance(ln, xpos)
        line = list(ln)
        while (line[s1pos] != idaapi.SCOLOR_ON
               or line[s1pos + 1] != idaapi.SCOLOR_SYMBOL):
            s1pos += 1
            if (s1pos > len(line)):
                return
        while (line[s2pos] != idaapi.SCOLOR_ON
               or line[s2pos + 1] != idaapi.SCOLOR_SYMBOL):
            s2pos += 1
            if (s2pos > len(line)):
                return

        line[s1pos + 1] = idaapi.SCOLOR_ERROR
        line[s1pos + 4] = idaapi.SCOLOR_ERROR
        line[s2pos + 1] = idaapi.SCOLOR_ERROR
        line[s2pos + 4] = idaapi.SCOLOR_ERROR
        ps[ypos].line = ''.join(line)
        idaapi.refresh_idaview_anyway()
コード例 #18
0
 def add_starts(self, bap):
     syms = []
     for line in bap.syms:
         heappush(syms, int(line, 16))
     for i in range(len(syms)):
         idaapi.add_func(heappop(syms), idaapi.BADADDR)
     idc.Refresh()
     idaapi.refresh_idaview_anyway()
コード例 #19
0
ファイル: bap_bir_attr.py プロジェクト: obaby/bap-ida-python
 def load_script(self, bap, ea):
     idc.SetStatus(idc.IDA_STATUS_WORK)
     idaapi.IDAPython_ExecScript(bap.script.name, globals())
     self._do_callbacks(ea)
     idc.Refresh()
     # do we really need to call this?
     idaapi.refresh_idaview_anyway()
     idc.SetStatus(idc.IDA_STATUS_READY)
コード例 #20
0
 def resetHookedColors(self):
     for key in self.idbHookMap:
         entry = self.idbHookMap[key]
         if entry.hook.type == "inst":
             SetColor(entry.hook.id, CIC_ITEM, kIDAViewColor_Reset)
         elif entry.hook.type == "func":
             SetColor(entry.hook.id, CIC_FUNC, kIDAViewColor_Reset)
         refresh_idaview_anyway()
コード例 #21
0
ファイル: ida_painter.py プロジェクト: y-f00l/lighthouse
 def _refresh_ui(self):
     """
     Note that this has been decorated with @execute_paint (vs @execute_ui)
     to help avoid deadlocking on exit.
     """
     for vdui in self._vduis.values():
         if vdui.valid():
             vdui.refresh_ctext(False)
     idaapi.refresh_idaview_anyway()
コード例 #22
0
ファイル: SyncPlugin.py プロジェクト: nihilus/qb-sync
    def stop(self):
        if self.broker_sock:
            self.broker_sock.close()
            self.broker_sock = None

        self.cb_restore_last_line()
        idaapi.refresh_idaview_anyway()
        self.is_active = False
        print "[sync] idb is disabled"
コード例 #23
0
    def stop(self):
        if self.broker_sock:
            self.broker_sock.close()
            self.broker_sock = None

        self.cb_restore_last_line()
        idaapi.refresh_idaview_anyway()
        self.is_active = False
        rs_log("idb is disabled")
コード例 #24
0
    def handleHookFuncCust(self, screenEA=None):
        if screenEA is not None:
            func = get_func(screenEA)
        else:
            func = get_func(ScreenEA())
        if func is None:
            return

        address = func.startEA

        # safety checks, can be start of the function
        if address in self.idbHookMap and self.idbHookMap[
                address].hook.type == "inst":
            dlg = AskYN(
                0,
                "Address contains instruction hook!\nDo you want to remove it?"
            )
            if dlg != 1:
                return
            # remove instruction hook
            self.handleUnhookInst(address)

        offset, moduleName = self.getAddressDetails(address)

        hookDlg = FunctionHookDialog(moduleName, "%X" % address,
                                     get_func_name(address), None, None)
        hookDlg.Compile()
        hookDlg.script_enter.value = ""
        hookDlg.script_leave.value = ""
        ok = hookDlg.Execute()
        if ok != 1:
            return

        hook = FuncHook()
        hook.id = address
        hook.symbol = get_func_name(address)
        hook.address = offset
        hook.module = moduleName
        hook.once = True if hookDlg.trigger.value == 0 else False
        hook.enterRecentSrcFile = hookDlg.recentScriptFileEnter
        hook.enterScript = hookDlg.script_enter.value
        hook.leaveRecentSrcFile = hookDlg.recentScriptFileLeave
        hook.leaveScript = hookDlg.script_leave.value

        entry = HookEntry(hook)
        outJSON = json.dumps({
            "req_id": kFridaLink_SetHookRequest,
            "data": entry.genSetRequest()
        })

        SetColor(address, CIC_FUNC, kIDAViewColor_HookedFunc)
        refresh_idaview_anyway()
        self.clientSocket.sendto(outJSON, self.clientAddress)
        self.idbHookMap[address] = entry

        self.idbHooksView.setContent(self.idbHookMap)
コード例 #25
0
 def add_starts(self, bap):
     idaapi.refresh_idaview_anyway()
     for line in bap.syms:
         line = line.strip()
         if len(line) == 0:
             continue
         addr = int(line, 16)
         end_addr = idaapi.BADADDR
         idaapi.add_func(addr, end_addr)
     idc.Refresh()
コード例 #26
0
	def handleReplaceFunc(self, screenEA = None):
		if screenEA is not None:
			func = get_func(screenEA)
		else:
			func = get_func(ScreenEA())
		if func is None:
			return

		address = func.startEA;

		offset, moduleName = self.getAddressDetails(address)

		replaceDlg = FunctionReplaceDialog(moduleName, "%X" % address, get_func_name(address), None)
		replaceDlg.Compile()
		replaceDlg.script.value = ""
		ok = replaceDlg.Execute()
		if ok != 1:
			return

		replace = FuncReplace()
		replace.id = address
		replace.symbol = get_func_name(address)
		replace.address = offset
		replace.module = moduleName
		replace.moduleImport = False
		replace.ret_type = "\'" + replaceDlg.ret_type.value + "\'"
		replace.recentSrcFile = replaceDlg.recentScriptFile
		replace.script = replaceDlg.script.value
		replace.args_str = replaceDlg.args.value
		replace.arg_types = ""
		replace.arg_names = ""

		if replace.args_str != "":
			args_list = replace.args_str.split(",")

			for arg in args_list:
				arg_list = arg.split()
				replace.arg_types += "\'" + arg_list[0] + "\', "
				replace.arg_names += arg_list[1] + ", " 

			replace.arg_types = replace.arg_types[:-2]
			replace.arg_names = replace.arg_names[:-2]

		outJSON = json.dumps({
			"req_id": kFridaLink_SetReplaceRequest, 
			"data": replace.genSetRequest()
		})

		SetColor(address, CIC_FUNC, kIDAViewColor_ReplacedFunc)
		refresh_idaview_anyway()
		self.clientSocket.sendto(outJSON, self.clientAddress)
		self.funcReplaceMap[address] = replace

		self.funcReplaceView.setContent(self.funcReplaceMap)
コード例 #27
0
    def handleDebugStepOver(self):
        if self.clientSocket is None:
            return

        if self.debugBreakId is None:
            return

        cur_ea = self.debugBreakId
        decode_insn(cur_ea)
        next_ea = cur_ea + idaapi.cmd.size

        if isCode(getFlags(next_ea)) == False:
            return

        entry = None
        # remove current
        if self.debugBreakId in self.idbHookMap:
            entry = self.idbHookMap[self.debugBreakId]
            outJSON = json.dumps({
                "req_id": kFridaLink_DelHookRequest,
                "data": entry.genDelRequest()
            })

            del self.idbHookMap[self.debugBreakId]
            self.clientSocket.sendto(outJSON, self.clientAddress)
            SetColor(self.debugBreakId, CIC_ITEM, kIDAViewColor_Reset)
            refresh_idaview_anyway()

        offset, moduleName = self.getAddressDetails(next_ea)

        # install next
        if entry == None:
            hook = InstHook()
            hook.id = next_ea
            hook.once = once
            hook.breakpoint = True
            entry = HookEntry(hook)

        entry.hook.id = next_ea
        entry.hook.mnemonic = GetDisasm(next_ea)
        entry.hook.address = offset
        entry.hook.module = moduleName

        outJSON = json.dumps({
            "req_id": kFridaLink_SetHookRequest,
            "data": entry.genSetRequest()
        })

        self.clientSocket.sendto(outJSON, self.clientAddress)
        self.idbHookMap[next_ea] = entry

        self.idbHooksView.setContent(self.idbHookMap)

        self.handleDebugContinue()
コード例 #28
0
    def _merge_cmnts(self, comments, repeatable):
        for ea_rel in comments:
            ea = int(ea_rel) + self._first_addr
            comment = comments[ea_rel]
            current_comment = idc.GetCommentEx(ea, repeatable)

            if current_comment is None:
                current_comment = ""

            final_comment = current_comment + "; REDB: " + comment
            self._embed_comment(ea, final_comment, repeatable)
            idaapi.refresh_idaview_anyway()
コード例 #29
0
    def _merge_cmnts(self, comments, repeatable):
        for ea_rel in comments:
            ea = int(ea_rel) + self._first_addr
            comment = comments[ea_rel]
            current_comment = idc.GetCommentEx(ea, repeatable)

            if current_comment is None:
                current_comment = ""

            final_comment = current_comment + "; REDB: " + comment
            self._embed_comment(ea, final_comment, repeatable)
            idaapi.refresh_idaview_anyway()
コード例 #30
0
def revokeAnalysis():
	n = idaapi.netnode("$ initialAnalysis", 0, False)
	
	if (n == idaapi.BADNODE):	return
	
	idx = n.alt1st()
	while idx != idaapi.BADNODE:
		colorize(idx, DEFCOLOR)
		idx = n.altnxt(idx)
	
	n.kill()
	
	idaapi.refresh_idaview_anyway()
コード例 #31
0
ファイル: ida_prefix.py プロジェクト: mfkiwl/prefix
def refresh_views():
    """
    Refresh the IDA views.
    """

    # refresh IDA views
    idaapi.refresh_idaview_anyway()

    # refresh hexrays
    current_widget = idaapi.get_current_widget()
    vu = idaapi.get_widget_vdui(current_widget)
    if vu:
        vu.refresh_ctext()
コード例 #32
0
ファイル: ida_prefix.py プロジェクト: lucasg/prefix
def refresh_views():
    """
    Refresh the IDA views.
    """

    # refresh IDA views
    idaapi.refresh_idaview_anyway()

    # refresh hexrays view, if active
    current_tform = idaapi.get_current_tform()
    vu = idaapi.get_tform_vdui(current_tform)
    if vu:
        vu.refresh_ctext()
コード例 #33
0
def revokeAnalysis():
    n = idaapi.netnode("$ initialAnalysis", 0, False)

    if (n == idaapi.BADNODE): return

    idx = n.alt1st()
    while idx != idaapi.BADNODE:
        colorize(idx, DEFCOLOR)
        idx = n.altnxt(idx)

    n.kill()

    idaapi.refresh_idaview_anyway()
コード例 #34
0
def refresh_views():
    """
    Refresh the IDA views.
    """

    # refresh IDA views
    idaapi.refresh_idaview_anyway()

    # refresh hexrays view, if active
    current_tform = idaapi.get_current_tform()
    vu = idaapi.get_tform_vdui(current_tform)
    if vu:
        vu.refresh_ctext()
コード例 #35
0
    def clearbracket(self, ps, refresh=True):
        ctr = 0
        for i in self.highl_brack:
            try:
                ps[i].line = self.highl_brack[i]
                ctr += 1
                #print('clear' + ps[i].line)
            except:
                pass

        self.highl_brack = {}
        if ((ctr > 0) and refresh):
            idaapi.refresh_idaview_anyway()
コード例 #36
0
    def parse_exec(self, req):
        if self.prev_req:
            if self.prev_req != "":
                if rsconfig.DEBUG_JSON:
                    rs_log("JSON merge with request: \"%s\"" % req)

            req = self.prev_req + req
            self.prev_req = ""
        if req == '':
            return
        if rsconfig.DEBUG_JSON:
            rs_log("parse_exec -> " + str(req))

        if not (req.startswith('[sync]')):
            rs_log("[<] bad hdr %s" % repr(req))
            rs_log('[-] Request dropped due to bad header')
            return

        req_ = self.normalize(req, 6)

        try:
            hash = json.loads(req_)
        except ValueError:
            if rsconfig.DEBUG_JSON:
                rs_log(
                    "[x] Sync failed to parse json\n '%s'. Caching for next req..."
                    % req_)
                rs_log("------------------------------------")
            self.prev_req = req
            return

        type = hash['type']
        if type not in self.req_handlers:
            rs_log("unknown request: %s" % type)
            return

        req_handler = self.req_handlers[type]

        # few requests are handled even though idb is not enable
        if type in ['broker', 'dialect', 'bc']:
            req_handler(hash)
        else:
            if self.is_active:
                req_handler(hash)
            else:
                rs_debug("[-] Drop the %s request because idb is not enabled" %
                         type)
                return

        idaapi.refresh_idaview_anyway()
コード例 #37
0
	def handleReplaceResponse(self, response):
		repl_id = int(response['id'], 16)
		if repl_id not in self.funcReplaceMap:
			return
		
		entry = self.funcReplaceMap[repl_id]

		# unable to install hook
		if response['count'] == 0:
			if entry.moduleImport == False:
				SetColor(repl_id, CIC_FUNC, kIDAViewColor_Reset)
				refresh_idaview_anyway()
			del self.funcReplaceMap[repl_id]
			self.funcReplaceView.setContent(self.funcReplaceMap)
コード例 #38
0
ファイル: ida_taint2_plugin.py プロジェクト: rawsample/panda
 def run(self, arg):
     # this is called when select the plugin from the Edit>Plugins menu
     if (not self.have_taint_info()):
         # don't even have a file of taint information selected yet
         filename, _ = QFileDialog.getOpenFileName(None,
         self.OPEN_CAPTION, self.OPEN_DIRECTORY, self.OPEN_FILTER)
         if filename == "":
             # taint must already be disabled, so no need to re-disable
             return
         self._taint_file = filename
         if (self._update_process()):
             self.show_taint_info()
             self._seen_file = True
     elif (self.showing_taint()):
         request = ReuseTaintDialog.askToReuse(self._taint_file, self._tainted_process)
         if (ReuseTaintDialog.GET_NEW_PROCESS == request):
             if (self._update_process()):
                 idaapi.refresh_idaview_anyway()
                 ida_kernwin.refresh_chooser(ShowTaintedFuncs.TITLE)
         elif (ReuseTaintDialog.GET_NEW_FILE == request):
             filename, _ = QFileDialog.getOpenFileName(None,
             self.OPEN_CAPTION, self.OPEN_DIRECTORY, self.OPEN_FILTER)
             if filename == "":
                 # user must've changed his mind
                 return
             self._taint_file = filename
             self._seen_file = False
             if (self._update_process()):
                 self._seen_file = True
                 idaapi.refresh_idaview_anyway()
                 ida_kernwin.refresh_chooser(ShowTaintedFuncs.TITLE)
     else:
         # must have an old file and process selected, but taint disabled
         # note that _update_process wipes _tainted_process and _taint_file
         # if the user cancels the process selection, so we should not have
         # _taint_file set without _tainted_process also being set
         request = ReuseTaintDialog.askToReuse(self._taint_file, self._tainted_process)
         if (ReuseTaintDialog.GET_NEW_PROCESS == request):
             if (self._update_process()):
                 self.show_taint_info()
         elif (ReuseTaintDialog.GET_NEW_FILE == request):
             filename, _ = QFileDialog.getOpenFileName(None,
             self.OPEN_CAPTION, self.OPEN_DIRECTORY, self.OPEN_FILTER)
             if (filename == ""):
                 return
             self._taint_file = filename
             self._seen_file = False
             if (self._update_process()):
                 self.show_taint_info()
                 self._seen_file = True
コード例 #39
0
    def syncIdbHooks(self):
        # install IDB hooks
        for key in self.idbHookMap:
            entry = self.idbHookMap[key]
            outJSON = json.dumps({
                "req_id": kFridaLink_SetHookRequest,
                "data": entry.genSetRequest()
            })

            if entry.hook.type == "inst":
                SetColor(entry.hook.id, CIC_ITEM, kIDAViewColor_HookedInst)
            elif entry.hook.type == "func":
                SetColor(entry.hook.id, CIC_FUNC, kIDAViewColor_HookedFunc)
            self.clientSocket.sendto(outJSON, self.clientAddress)
        refresh_idaview_anyway()
コード例 #40
0
    def OnEditLine(self, n):

        # Empty list
        if n == -1:
            return

        # Multiselect START_SEL/END_SEL protocol
        if n == -2 or n ==-3:
            return

        ea = self.items_data[n][0]
        fpos =  self.items_data[n][1]
        patch_buf = self.items_data[n][3]
        orig_buf = self.items_data[n][4]

        addr_str = "%#x" % ea
        fpos_str = "%#x" % fpos if fpos != -1 else "N/A"     
        patch_str = self.items[n][3]
        org_str = self.items[n][4]    

        # Create the form
        f = PatchEditForm(addr_str, fpos_str, patch_str, org_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

            # Restore original bytes first
            idaapi.put_many_bytes(ea, struct.pack("B"*len(orig_buf), *orig_buf))

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

            # Refresh all IDA views
            self.refreshitems()
            idaapi.refresh_idaview_anyway()
コード例 #41
0
ファイル: descriptions.py プロジェクト: ChenSvirsky/REDB-1
    def set_all(cls, start_addr, description_dict, append=None):
        """
        append => append to current if True, prepend to current if False,
        discard current if null.
        """
        func_name = description_dict["func_name"]
        comments = description_dict["comments"]
        func_comments = description_dict["func_comments"]
        stack_members = description_dict["stack_members"]

        if append is None:
            cls.remove_all_comments(start_addr)
        cls.set_func_name(start_addr, func_name)
        cls.set_stack_members(start_addr, stack_members)
        cls.set_comments(start_addr, comments, append)
        cls.set_both_func_comments(start_addr, func_comments, append)
        idaapi.refresh_idaview_anyway()
コード例 #42
0
    def add_tag(self, user=True, index=None, outof=None, mg=None):
        self.remove_tag()

        tag = "[REDB: handled"
        if user:
            tag += ", user's description"
        else:
            tag += (", public description" +
                    " (" + str(index) + "/" + str(outof) + ")" +
                    ", Matching Grade: " + str(mg))
        tag += "]"

        current_comment = Extract(self._first_addr)._extract_func_cmnt(0)
        final_comment = tag
        if current_comment is not None:
            final_comment += current_comment
        Embed(self._first_addr)._embed_func_cmnt(final_comment, 0)
        idaapi.refresh_idaview_anyway()
コード例 #43
0
    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()
コード例 #44
0
    def show_desc(self, index=None, outof=None):
        """
        If self.can_be_embedded embed each comments in it's place.
        O.w. embed short version in the beginning of the function.
        """
        if self._can_be_embedded or self._is_user_description:
            redb_client_utils.Embed(self._first_addr).\
                embed_all(self._func_name_and_cmts)
        else:
            redb_client_utils.Embed(self._first_addr).\
                embed_short(self._func_name_and_cmts)

        self._add_tag(index, outof)

        idaapi.refresh_idaview_anyway()
        if not self._is_user_description:
            print ("REDB: Showing public description " + str(index) +
                   "/" + str(outof))
        else:
            print "REDB: Showing user's description."
コード例 #45
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 = 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()
コード例 #46
0
ファイル: Assembler.py プロジェクト: gljiva/optimice
    def Assemble(self, function, nasm=True):
        '''
            Main Assemble Function
        '''

        if self.functions.has_key(function.start_ea):
            ans = idaapi.askyn_c(1, "HIDECANCEL\nFunction @ [%08x] was already optimized, are you sure you want to overwrite old one?")
            if ans == 0:
                return

        idc.Batch(1)

        self.jmp_table = ""
        self.jmp_table_refs = []
        self.jmp_deps = {}
        self.ref_instr = {}
        self.bb_head_ea = {}

        function_ea = self.free_ea
        function_end = None

        if debug:
            print ">Assemble(%08x) - Starting" % function.start_ea

        if nasm:
            if self.opty_dir == None:
                self.opty_dir = idc.GetIdbPath()
                self.opty_dir = self.opty_dir[:self.opty_dir.rfind(os.sep)] + os.sep + "optimice_%s" % idc.GetInputFile()
                if not os.path.isdir(self.opty_dir):
                    os.mkdir(self.opty_dir)

            self.nasm = True
            self.nasmfw = open(self.opty_dir + os.sep + 'f_%08x.asm' % function.start_ea, "w+")
            self.NasmWriteToFile("[BITS 32]\n")
            self.NasmWriteToFile("\torg %09xh\n" % function_ea)
        else:
            self.nasm = False

        for bb_ea in function.DFSFalseTraverseBlocks():
            if self.nasm:
                self.NasmWriteToFile("\nL%08x:\n" % bb_ea)
                self.bb_head_ea[bb_ea] = True
            else:
                self.bb_head_ea[bb_ea] = self.free_ea

            for instr in function.GetBBInstructions(bb_ea):
                if instr == None:
                    continue

                mnem = self.BuildAsmString(instr, function)

                if debug:
                    print ">Assemble - Assembling @ %08x [%s]" % (instr.GetOriginEA(), mnem)

                if not self.nasm:
                    self.AsmAndWrite(mnem, instr, function=function)

            if not instr.IsCFI():
                ref_from = list(function.GetRefsFrom(instr.GetOriginEA()))[0][0]

                if self.bb_head_ea.has_key(ref_from):
                    if self.nasm:
                        self.NasmWriteToFile("\tjmp L%08x ; \n" % ref_from)
                    else:
                        self.AsmAndWrite("jmp %09xh" % self.bb_head_ea[ref_from])

            elif instr.GetMnem() == "call":
                for ref,path in function.GetRefsFrom(instr.GetOriginEA()):
                    if path == False:
                        if self.bb_head_ea.has_key(ref):
                            if self.nasm:
                                self.NasmWriteToFile("\tjmp L%08x ; ###FAKE 2 JMP###\n" % ref)
                            else:
                                self.AsmAndWrite("jmp %09xh" % self.bb_head_ea[ref])

            elif instr.IsJcc():
                ref_from = list(function.GetRefsFrom(instr.GetOriginEA()))
                for ref,path in ref_from:
                    if path == False:
                        break

                if path == True:
                    raise MiscError

                elif self.bb_head_ea.has_key(ref):
                    print "Check this out @ [%08x] ref:[%08x]" % (instr.GetOriginEA(), ref)
                    if self.nasm:
                        self.NasmWriteToFile("\tjmp L%08x ; ###FAKE 2 JMP###\n" % ref)
                    else:
                        self.AsmAndWrite("jmp %09xh" % self.bb_head_ea[ref])

        ret = None
        if self.nasm:
            self.NasmWriteToFile(self.jmp_table)

            self.nasmfw.close()
            self.nasmfw = None

            ret = self.NasmAssemble(function.start_ea, self.free_ea)
            if ret != None:
                self.free_ea = ret
        else:
            ret = self.AsmAndWriteBranches(function)
            self.free_ea = ret

        self.ref_instr = {}
        idc.Batch(0)

        if ret != None:
            idc.MakeFunction(function_ea)

            comment = idc.Comment(function_ea)
            if comment != None:
                comment = 'Origin@[%08x]; %s' % (function.start_ea, comment)
            else:
                comment = 'Origin@[%08x];' % function.start_ea

            idc.MakeComm(function_ea, comment)

            comment = idc.Comment(function.start_ea)
            if comment != None:
                comment = 'OPTY@[%08x]; %s' % (function_ea, comment)
            else:
                comment = 'OPTY@[%08x];' % function_ea

            idc.MakeComm(function.start_ea, comment)

            idaapi.set_name(function_ea, "om_%s" % idc.Name(function.start_ea))

        function_end = self.free_ea
        self.functions[function.start_ea] = (function_ea, function_end)

        idaapi.refresh_idaview_anyway()
コード例 #47
0
ファイル: ui.py プロジェクト: arizvisa/idascripts
 def refresh(cls):
     '''Refresh the main IDA disassembly view.'''
     return idaapi.refresh_idaview_anyway()
コード例 #48
0
 def finish(self, bap):
     idaapi.IDAPython_ExecScript(bap.script.name, globals())
     idaapi.refresh_idaview_anyway()
     BapTaint._do_callbacks(self.kind)
     idc.Refresh()
コード例 #49
0
ファイル: ida.py プロジェクト: IDA-RE-things/toolbag
 def refreshView(self):
     idaapi.refresh_idaview_anyway()
コード例 #50
0
			setInfo(cmd.ea, COLOR_CALL)


def iterateInstructions():
	next = 0
	while next != idaapi.BADADDR:
		
		# get next instruction
		next = idc.NextHead(next)
		
		idaapi.decode_insn(next)
		for handlers in InstructionCallbacks:
			handlers.instruction(idaapi.cmd)


### main ###
revokeAnalysis()

# find unidentified functions
findUnidentifiedFunctions()

InstructionCallbacks = []
InstructionCallbacks.append(CryptoTester())
InstructionCallbacks.append(CallTester())

iterateInstructions()

# refresh ida view to display our results
idaapi.refresh_idaview_anyway()

print "done. have a nice day :-)"