Exemplo n.º 1
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()
Exemplo n.º 2
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()
Exemplo n.º 3
0
    def Sync(self, offset, added, removed):
        """ Sync(offset, added, removed) => None
        Synchronize debug info with gef. This is an internal function. It is
        not recommended using it from the command line.
        """
        global _breakpoints, _current_instruction, _current_instruction_color

        if _current_instruction > 0:
            idc.SetColor(_current_instruction, CIC_ITEM, _current_instruction_color)

        base_addr = idaapi.get_imagebase()
        pc = base_addr + int(offset, 16)
        _current_instruction = long(pc)
        _current_instruction_color = GetColor(_current_instruction, CIC_ITEM)
        idc.SetColor(_current_instruction, CIC_ITEM, 0x00ff00)
        print("PC @ " + hex(_current_instruction).strip('L'))
        # post it to the ida main thread to prevent race conditions
        idaapi.execute_sync(lambda: idc.Jump(_current_instruction), idaapi.MFF_WRITE)

        cur_bps = set([ idc.GetBptEA(n)-base_addr for n in range(idc.GetBptQty()) ])
        ida_added = cur_bps - _breakpoints
        ida_removed = _breakpoints - cur_bps
        _breakpoints = cur_bps

        # update bp from gdb
        for bp in added:
            idc.AddBpt(base_addr+bp)
            _breakpoints.add(bp)
        for bp in removed:
            if bp in _breakpoints:
                _breakpoints.remove(bp)
            idc.DelBpt(base_addr+bp)

        return [list(ida_added), list(ida_removed)]
Exemplo n.º 4
0
 def markupEa(self, markup_ea, colorFunc=True):
     if markup_ea and markup_ea != idc.BADADDR:
         func_color = self._func_color_picker.currentColor()
         ea_color = self._color_picker.currentColor()
         log.debug("Coloring instructions for 0x{:08x}".format(markup_ea))
         idc.SetColor(markup_ea, idc.CIC_FUNC, int("0x{:02x}{:02x}{:02x}".format(*func_color.getRgb()[:3][::-1]), 16))
         if colorFunc:
             idc.SetColor(markup_ea, idc.CIC_ITEM, int("0x{:02x}{:02x}{:02x}".format(*ea_color.getRgb()[:3][::-1]), 16))
Exemplo n.º 5
0
        def __color_write(cls, ea, rgb, what=1):
            if rgb is None:
                return idc.SetColor(ea, what, 0xffffffff)

            a = rgb & 0xff000000
            rgb &= 0x00ffffff

            bgr = 0
            for i in xrange(3):
                bgr,rgb = ((bgr*0x100) + (rgb&0xff), rgb/0x100)
            return idc.SetColor(ea, what, bgr)
Exemplo n.º 6
0
 def removeMarkup(self, ea, force=False):
     if ea in self._marked_up or force:
         log.debug("Removing color")
         idc.SetColor(ea, idc.CIC_FUNC, 0xffffff)
         idc.SetColor(ea, idc.CIC_ITEM, 0xffffff)
         idc.MakeComm(ea, "")
         log.debug("Removing posterior lines")
         i = 0
         while idc.LineB(ea, i):
             idc.DelExtLnB(ea, i)
             i += 1
Exemplo n.º 7
0
def main():
    clist = build_color_list()

    filepath = idaapi.askfile_c(False, "*.*", "Pin log file")
    imagebase = idaapi.get_imagebase()
    try:
        f = open(filepath, "rb")
    except:
        print("Need log file to parse data...")
        return
    buff = f.read()
    functions = set()
    for index in range(0, len(buff)):
        exec_count = ord(buff[index])
        if exec_count == 0:
            continue

        exec_count = exec_count / 10
        if exec_count > 11: exec_count = 11

        ida_color = clist[exec_count]
        if (not (idc.GetFunctionName(imagebase + index) in functions)):
            func = idc.GetFunctionName(imagebase + index)
            print "hit @ 0x%08x function %s" % (imagebase + index, func)
            functions.add(func)

        idc.SetColor(imagebase + index, CIC_ITEM, ida_color)
Exemplo n.º 8
0
def treat_element():
    "Display an element"
    global graphs, comments, sol_nb, settings, addr, ir_arch

    try:
        graph = graphs.next()
    except StopIteration:
        comments = {}
        print "Done: %d solutions" % (sol_nb)
        return

    sol_nb += 1
    print "Get graph number %02d" % sol_nb
    filename = os.path.join(tempfile.gettempdir(), "solution_0x%08x_%02d.dot" % (addr, sol_nb))
    print "Dump the graph to %s" % filename
    open(filename, "w").write(graph.graph.dot())

    for node in graph.relevant_nodes:
        try:
            offset = ir_arch.blocks[node.label].irs[node.line_nb].instr.offset
        except IndexError:
            print "Unable to highlight %s" % node
            continue
        comments[offset] = comments.get(offset, []) + [node.element]
        idc.SetColor(offset, idc.CIC_ITEM, settings.color)

    if graph.has_loop:
        print 'Graph has dependency loop: symbolic execution is inexact'
    else:
        print "Possible value: %s" % graph.emul().values()[0]

    for offset, elements in comments.iteritems():
        idc.MakeComm(offset, ", ".join(map(str, elements)))
Exemplo n.º 9
0
    def PrintMsrTable(self, msr_code, function_ea, inst_ea):
        mnemonic = idc.GetMnem(inst_ea)
        call_addr = self.GetJumpAddr(inst_ea, function_ea)
        function_name = idc.GetFunctionName(function_ea) + '+' + call_addr
        dwSize = 30 - len(function_name)
        delimeter = " " * dwSize

        if (msr_code == None):
            msr_code_hex = 'Not imm value'
        else:
            msr_code_hex = self.NormalizeHexValue(msr_code)

        if (msr_code == None):
            msr_name = msr_code_hex
        else:
            msr_name = msr_list.get(int(msr_code_hex, 16))

        idc.MakeComm(inst_ea, '{}({})'.format(mnemonic, msr_name))
        idc.SetColor(inst_ea, idc.CIC_ITEM, 0xf8abef)

        msr_name_delimeter = (" " * (15 - len(msr_code_hex)))

        print '{}{}| {} | {} {} | {}'.format(function_name, delimeter,
                                             mnemonic, msr_code_hex,
                                             msr_name_delimeter, msr_name)
Exemplo n.º 10
0
    def _load_addr(self):
        if self.cur_ins != 0:
            idc.SetColor(self.cur_ins, CIC_ITEM, 0xFFFFFFFF)

        self.addr_list = []
        addr_0 = self.addr0.text()
        addr_1 = self.addr1.text()
        addr_2 = self.addr2.text()
        addr_3 = self.addr3.text()

        base = self.base_addr.text()
        if base != '':
            self.module_base = int(base, 16)
            self.addr_is_load = True
        else:
            self.browser.append("base can't null")
            return

        if addr_0 != '':
            self.addr_list.append(int(addr_0, 16))
        if addr_1 != '':
            self.addr_list.append(int(addr_1, 16))
        if addr_1 != '':
            self.addr_list.append(int(addr_1, 16))
        if addr_1 != '':
            self.addr_list.append(int(addr_1, 16))

        self.browser.append("load base already")
Exemplo n.º 11
0
 def heatmap_trace(self):
     try:
         index = self.traces_tab.currentIndex()
         trace = self.core.traces[self.id_map[index]]
         if self.heatmaped:
             self.heatmap_button.setText("Heatmap")
             color = lambda x: 0xffffff
         else:
             self.heatmap_button.setText("Heatmap undo")
             self.heatmap_button.setFlat(True)
             hit_map = trace.address_hit_count
             color_map = self.compute_step_map(set(hit_map.values()))
             print color_map
             color = lambda x: color_map[hit_map[x]]
         for inst in trace.instrs.values():
             if idc.isCode(idc.GetFlags(inst.address)):
                 c = color(inst.address)
                 idc.SetColor(inst.address, idc.CIC_ITEM, c)
         if not self.heatmaped:
             self.heatmap_button.setFlat(False)
             self.heatmaped = True
         else:
             self.heatmaped = False
     except KeyError:
         print "No trace found"
Exemplo n.º 12
0
def clean_lines():
    "Remove previous comments"
    global comments
    for offset in comments:
        idc.SetColor(offset, idc.CIC_ITEM, 0xffffff)
        idc.MakeComm(offset, "")
    comments = {}
Exemplo n.º 13
0
    def clear_colors(self):
        ea = idc.ScreenEA()

        for function_ea in idautils.Functions(idc.SegStart(ea),
                                              idc.SegEnd(ea)):
            for ins in idautils.FuncItems(function_ea):
                idc.SetColor(ins, idc.CIC_ITEM, 0xFFFFFFFF)
Exemplo n.º 14
0
def tracing():
    global PRE_ADDR
    event = idc.GetDebuggerEvent(idc.WFNE_ANY, -1)
    if event <= 1:
        idc.RunTo(idc.BeginEA())
    idc.GetDebuggerEvent(idc.WFNE_SUSP, -1)
    idc.EnableTracing(idc.TRACE_STEP, 1)
    idc.GetDebuggerEvent(idc.WFNE_ANY | idc.WFNE_CONT, -1)
    while True:
        event = idc.GetDebuggerEvent(idc.WFNE_ANY, -1)
        if event <= 1:
            break
        addr = idc.GetEventEa()
        print event, "==>", hex(addr)

        # judge breakpoint and same addr
        if PRE_ADDR != addr:
            PRE_ADDR = addr
        else:  # same addr
            if event == idc.BREAKPOINT:  # and now is breakpoint
                break

        current_color = idc.GetColor(addr, idc.CIC_ITEM)
        new_color = get_new_color(current_color)
        idc.SetColor(addr, idc.CIC_ITEM, new_color)
Exemplo n.º 15
0
 def SetColor(self, address, color="0x005500"):
     """ SetColor(int addr [, int color]) => None
     Set the location pointed by `address` in the IDB colored with `color`.
     Example: ida SetColor 0x40000
     """
     addr = long(address, 16) if ishex(address) else long(address)
     color = long(color, 16) if ishex(color) else long(color)
     return idc.SetColor(addr, CIC_ITEM, color)
Exemplo n.º 16
0
 def searchClickedIndex_Slot(self, value, local_comment_data=None):
     a = idaapi.jumpto(value)
     # Highlight the current line in IDA views
     idc.SetColor(value, idc.CIC_ITEM, 0x90EE90)
     if local_comment_data:
         # Add the flow-max information (e.g, call hit 42 times)
         idaapi.add_long_cmt(value, 1, local_comment_data)
     self.selectRow(value)
Exemplo n.º 17
0
 def refresh(self):
     ea = ScreenEA()
     if not (ea == self.current_position):
         # Make sure to reset the color code in IDA
         if self.current_position > 0:
             idc.SetColor(self.current_position, idc.CIC_ITEM, 0xFFFFFFFF)
         self.updatePosition(ea)
     return 200
Exemplo n.º 18
0
    def _step_into(self):
        #
        if self.data == None:
            self.browser.append("please load file before")
            return

        #
        if not self.addr_is_load:
            self.browser.append("please load base addr before")
            return

        #
        ir_list = []
        mark_num = 0
        min_dist = 0xffffffff
        for i in range(self.curr_line, len(self.data)):
            one_ir = self.data[i]
            if 'IMark' in one_ir:
                if mark_num >= 1:
                    self.curr_line = i
                    break
                else:
                    ir_list.append(one_ir)
                    cur_addr = self._get_curr_base(one_ir) - self.module_base
                    self.or_ins = self.cur_ins
                    self.cur_ins = cur_addr

                    if self.or_ins != 0:
                        idc.SetColor(self.or_ins, CIC_ITEM, 0xFFFFFFFF)

                mark_num = mark_num + 1
            else:
                if 'func_' in one_ir:
                    if min_dist == 0xffffffff:
                        ref_addr = self.cur_ins
                        for addr in idautils.CodeRefsTo(ref_addr, 1):
                            if abs(addr - self.or_ins) <= min_dist:
                                min_dist = abs(addr - self.or_ins)
                                self.cur_ins = addr
                ir_list.append(one_ir)

        idc.jumpto(self.cur_ins)
        idc.SetColor(self.cur_ins, CIC_ITEM, 0x2020c0)
        for one_ir in ir_list:
            self.browser.append(one_ir)
Exemplo n.º 19
0
    def color(self, color):
        """Line Color in IDA View.

        Set color to `None` to clear the color.
        """
        if color is None:
            color = 0xFFFFFFFF

        idc.SetColor(self.ea, idc.CIC_ITEM, color)
Exemplo n.º 20
0
    def color(self, color):
        """Function Color in IDA View.

        Set color to `None` to clear the color.
        """
        if color is None:
            color = 0xFFFFFFFF

        idc.SetColor(self.ea, idc.CIC_FUNC, color)
Exemplo n.º 21
0
 def highlight_dependency(self, enabled):
     if self.results.has_formula():
         color = 0xffffff if enabled else 0x98FF98
         for addr in self.formula.get_addresses():
             idc.SetColor(addr, idc.CIC_ITEM, color)
     else:
         print "woot ?"
     self.actions[self.HIGHLIGHT_CODE] = (self.highlight_dependency,
                                          not (enabled))
     self.result_widget.action_selector_changed(self.HIGHLIGHT_CODE)
Exemplo n.º 22
0
    def colorize(self, node, color):
        '''
		Colorize the entire code block.
		'''
        block = self.LookupBlock(node)
        if block and idc.GetColor(block.startEA, idc.CIC_ITEM) != color:
            ea = block.startEA
            while ea < block.endEA:
                idc.SetColor(ea, idc.CIC_ITEM, color)
                ea += idaapi.decode_insn(ea)
Exemplo n.º 23
0
def main():
	ida_color = 0xFFFFFFFF
	start = FirstSeg()
	end = SegEnd(start)
	while(start != idc.BADADDR):
                
                for i in range(start, end):
                        idc.SetColor(i, CIC_ITEM, ida_color);
                start = NextSeg(start)
                end = SegEnd(start)
Exemplo n.º 24
0
 def propagate_dead_code(self, ea, op_map):
     prevs = [x for x in idautils.CodeRefsTo(ea, True) if x not in self.marked_addresses and
              not self.dead_br_of_op(ea, x, op_map)]
     if prevs:  # IF there is no legit predecessors
         idc.SetColor(ea, idc.CIC_ITEM, 0x0000ff)
         self.marked_addresses[ea] = None
         succs = [x for x in idautils.CodeRefsFrom(ea, True)]
         for succ in succs:
             self.propagate_dead_code(succ, op_map)
     else:
         return
Exemplo n.º 25
0
 def highlight_dead(self, enabled):
     opaque_map = {k: self.make_po_pair(k, v.alive_branch) for k, v in self.results.items()
                   if v.status == po_analysis_results.OPAQUE}
     for addr, (good, dead) in opaque_map.items():
         if not enabled:  # Mark instructions
             print "propagate dead branch:%x" % addr
             self.propagate_dead_code(dead, opaque_map)
         else:
             for addr2 in self.marked_addresses.keys():
                 idc.SetColor(addr2, idc.CIC_ITEM, 0xffffff)
             self.marked_addresses.clear()
     self.actions[self.HIGHLIGHT_DEAD_BRANCHES] = (self.highlight_dead, not enabled)
     self.result_widget.action_selector_changed(self.HIGHLIGHT_DEAD_BRANCHES)
Exemplo n.º 26
0
 def highlight_spurious(self, enabled):
     print "Highlight spurious clicked !"
     curr_fun = idaapi.get_func(idc.here()).startEA
     cfg = self.functions_cfg[curr_fun]
     color = 0xFFFFFF if enabled else 0x507cff
     for bb in [x for x in cfg.values()
                if x.is_alive()]:  # Iterate only alive basic blocks
         for i, st in bb.instrs_status.items():
             if st == Status.DEAD:  # Instructions dead in alive basic blocks are spurious
                 idc.SetColor(i, idc.CIC_ITEM, color)
     self.actions[HIGHLIGHT_SPURIOUS_CALCULUS] = (self.highlight_spurious,
                                                  not enabled)
     self.result_widget.action_selector_changed(HIGHLIGHT_SPURIOUS_CALCULUS)
Exemplo n.º 27
0
    def add_instruction(self, line):
        self.n += 1
        self.items.append(line)
        addr = int(line[1].replace("L", ""), 16)
        idc.SetColor(addr, idc.CIC_ITEM, COVERAGE_COLOR)
        func_name = idc.GetFunctionName(addr)
        if func_name != "":
            if func_name != self.callgraph[-1]:
                self.callgraph.append(func_name)

            if not self.coverage.get(func_name):
                self.coverage[func_name] = 1
            else:
                self.coverage[func_name] += 1
Exemplo n.º 28
0
def color_head(ea):
    flags = idc.GetFlags(ea)
    if not idc.isCode(flags):
        return

    mnem = idc.GetMnem(ea)
    if mnem == 'call':
        logger.debug('call: 0x%x', ea)
        idc.SetColor(ea, idc.CIC_ITEM, CALL_COLOR)
    elif mnem == 'xor':
        if idc.GetOpnd(ea, 0) != idc.GetOpnd(ea, 1):
            logger.debug('non-zero xor: 0x%x', ea)
            idc.SetColor(ea, idc.CIC_ITEM, ENCRYPT_COLOR)
    elif mnem in ('sdit', 'sgdt', 'sldt', 'smsw', 'str', 'in', 'cpuid'):
        logger.debug('anti-vm: 0x%x', ea)
        idc.SetColor(ea, idc.CIC_ITEM, ANTIANALYSIS_COLOR)
    elif mnem == 'in':
        if idc.GetOpnd(ea, 0) in ("3", "2D"):
            logger.debug('anti-debug: 0x%x', ea)
            idc.SetColor(ea, idc.CIC_ITEM, ANTIANALYSIS_COLOR)
    elif mnem in ('rdtsc', 'icebp'):
        logger.debug('anti-debug: 0x%x', ea)
        idc.SetColor(ea, idc.CIC_ITEM, ANTIANALYSIS_COLOR)
Exemplo n.º 29
0
 def highlight_dead_code(self, enabled):
     curr_fun = idaapi.get_func(idc.here()).startEA
     cfg = self.functions_cfg[curr_fun]
     #for cfg in self.functions_cfg.values():
     for bb in cfg.values():
         color = {
             Status.DEAD: 0x5754ff,
             Status.ALIVE: 0x98FF98,
             Status.UNKNOWN: 0xaa0071
         }[bb.status]
         color = 0xFFFFFF if enabled else color
         for i in bb:
             idc.SetColor(i, idc.CIC_ITEM, color)
     self.actions[HIGHLIGHT_DEAD_CODE] = (self.highlight_dead_code,
                                          not (enabled))
     self.result_widget.action_selector_changed(HIGHLIGHT_DEAD_CODE)
Exemplo n.º 30
0
    def color_single_profile(self, binprof, color=GREEN):
        """
		Color single profile in IDA
			# default green - trace actually executed
		"""

        ea = idc.ScreenEA()

        actfuncs = []

        for rfunc in idautils.Functions(idc.SegStart(ea), idc.SegEnd(ea)):
            if rfunc in binprof.keys():
                actfuncs.append(rfunc)
                for instr in binprof[rfunc]:
                    idc.SetColor(instr, idc.CIC_ITEM, color)

        return actfuncs