def treat_element(): "Display an element" global graphs, comments, sol_nb, settings, addr, ir_arch, ircfg try: graph = next(graphs) 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 = ircfg.blocks[node.loc_key][node.line_nb].instr.offset except IndexError: print("Unable to highlight %s" % node) continue comments[offset] = comments.get(offset, []) + [node.element] idc.set_color(offset, idc.CIC_ITEM, settings.color) if graph.has_loop: print('Graph has dependency loop: symbolic execution is inexact') else: print("Possible value: %s" % next(iter(viewvalues(graph.emul(ir_arch))))) for offset, elements in viewitems(comments): idc.set_cmt(offset, ", ".join(map(str, elements)), 0)
def color(self, value): """ Setter which allow to set the color of the current element. :param int value: the color to which set the item. """ idc.set_color(self.ea, idc.CIC_ITEM, value)
def query_all_callback(self, threshold=0.8, minsize=3): for ea in idautils.Functions(): pfn = idaapi.get_func(ea) func_name = idaapi.get_func_name(ea) if idaapi.FlowChart(pfn).size < minsize: print( "[BinaryAI] {} is skipped because basicblock size lower than minsize({})" .format(func_name, minsize)) continue funcs = self.query_function(ea) if funcs is None: print( "[BinaryAI] {} is skipped because get function feature error" .format(func_name, threshold)) continue func = funcs[0] if func['score'] < threshold: print( "[BinaryAI] {} is skipped because top1_score lower than threshold({})" .format(func_name, threshold)) continue idc.set_color(ea, idc.CIC_FUNC, 0xFFFFE1) idc.set_func_flags(ea, idc.get_func_flags(ea) | 0x10000) comment = SourceCodeViewer.source_code_comment(func_name, func) idaapi.set_func_cmt(pfn, comment, 0)
def _btn_trace_color_clicked(self): col = 0xccffcc col2 = 0xbbeebb if False: for ea, basic_block in self.infoparser.basic_blocks.iteritems(): while ea != idaapi.BADADDR: idc.set_color(ea, idc.CIC_ITEM, col) ea = idc.next_head(ea, basic_block['end']) for target_pc, flow in self.infoparser.flows.iteritems(): refs = [] for xref in idautils.XrefsTo(target_pc): refs.append(xref.frm) for jump_from_pc, flowtype in flow.iteritems(): if jump_from_pc in refs: continue if ida_ua.ua_mnem(jump_from_pc) == 'call': flowtype = idaapi.fl_CN else: flowtype = idaapi.fl_JN idc.set_color(jump_from_pc, idc.CIC_ITEM, col2) idc.AddCodeXref(jump_from_pc, target_pc, flowtype)
def format_args(call_addr, fmt_num, index): func = idaapi.get_func(call_addr) start = func.start_ea string = "" # 这里i是指对应在整个调用中的参数的位置, # !! 从1开始因为测试的时候考虑printf第一个格式化字符串,后面的就是后推一个, # !! 应该snprintf参数解析错误的bug就是这里, 应该..1改成format_function_offset_dict[func_name]就好了 for i in range(index + 1, fmt_num + index + 1): # 只查寄存器传递的,push传递的还没考虑, if (i >= 6): break # 从调用位置向上遍历查找对应的传参寄存器 line = call_addr reg = arg_reg[i] while line >= start: line = prev_head(line) line_arg = idc.print_operand(line, 0) # !! 只比较寄存器存在bug (add rdi, 0x10), 可能被认为是0x10是参数, if reg == line_arg: idc.set_color(line, CIC_ITEM, 0x00fff0) # 如果是寄存器传寄存器(mov rdi, rax;), 调用函数尝试回溯rax, if (idc.get_operand_type(line, 1) != 1) and (idc.print_insn_mnem(line) in ['mov', 'lea']): string += ", '%s'" % (idc.print_operand(line, 1)) else: string += ", '%s'" % (hand_register( line, start, idc.print_operand(line, 1))) break return string
def reset_ida_highlighting(self, item, checked): """reset IDA highlight for item @param item: CapaExplorerDataItem @param checked: True, item checked, False item not checked """ if not isinstance( item, (CapaExplorerStringViewItem, CapaExplorerInstructionViewItem, CapaExplorerByteViewItem)): # ignore other item types return curr_highlight = idc.get_color(item.location, idc.CIC_ITEM) if checked: # item checked - record current highlight and set to new item.ida_highlight = curr_highlight idc.set_color(item.location, idc.CIC_ITEM, DEFAULT_HIGHLIGHT) else: # item unchecked - reset highlight if curr_highlight != DEFAULT_HIGHLIGHT: # user modified highlight - record new highlight and do not modify item.ida_highlight = curr_highlight else: # reset highlight to previous idc.set_color(item.location, idc.CIC_ITEM, item.ida_highlight)
def clean_lines(): "Remove previous comments" global comments for offset in comments: idc.set_color(offset, idc.CIC_ITEM, 0xffffff) idc.set_cmt(offset, "", 0) comments = {}
def enum_arg(call_addr): idc.set_color(call_addr, CIC_ITEM, 0x00ff00) arg = [] for arg_addr in idaapi.get_arg_addrs(call_addr): idc.set_cmt(arg_addr, "addr: 0x%x" % (call_addr), 0) idc.set_color(arg_addr, CIC_ITEM, 0x00fff0) arg.append(find_arg(arg_addr)) return arg
def highlight_matches(self): """Highlight all the matches.""" for insts in self._matches_colors.itervalues(): for ea, color in insts.iteritems(): try: set_color(ea, CIC_ITEM, ColorCore.rgb_to_bgr(color['new'])) except: SetColor(ea, CIC_ITEM, ColorCore.rgb_to_bgr(color['new']))
def color(self, color): """Line Color in IDA View. Set color to `None` to clear the color. """ if color is None: color = 0xFFFFFFFF idc.set_color(self.ea, idc.CIC_ITEM, color)
def color(self, color): """Function Color in IDA View. Set color to `None` to clear the color. """ if color is None: color = 0xFFFFFFFF idc.set_color(self.ea, idc.CIC_FUNC, color)
def hilight_addr(self, addr: int) -> None: if self.prev_addr != BADADDR: ea = self.prev_addr self._set_segment_color(ea, COLOR_NORMAL) set_color(ea, CIC_ITEM, COLOR_NORMAL) if addr != BADADDR: ea = addr self._set_segment_color(ea, COLOR_NORMAL) set_color(addr, CIC_ITEM, self.color_hilight) self.prev_addr = addr
def clean(): """Removes the background color of all the database. It can be used to remove the colors added by `apply()`, but it doesn't remove the prefixes.""" ida_auto.auto_wait() ea = idc.next_head(0) while ea != idaapi.BADADDR: idc.set_color(ea, idc.CIC_ITEM, 0xFFFFFF) ea = idc.next_head(ea) print("ANA color: Enjoy your boring database")
def audit(func_name): func_addr = getFuncAddr(func_name) if func_addr == False: return False # get arg num and set table if func_name in one_arg_function: arg_num = 1 elif func_name in two_arg_function: arg_num = 2 elif func_name in three_arg_function: arg_num = 3 elif func_name in format_function_offset_dict: arg_num = format_function_offset_dict[func_name] + 1 else: print( "The %s function didn't write in the describe arg num of function array,please add it to,such as add to `two_arg_function` arary" % func_name) return # mispcall = ["jal", "jalr", "bal", "jr"] table_head = ["func_name", "addr"] for num in range(0, arg_num): table_head.append("arg" + str(num + 1)) if func_name in format_function_offset_dict: table_head.append("format&value[string_addr, num of '%', fmt_arg...]") table_head.append("local_buf_size") table = PrettyTable(table_head) # get first call call_addr = get_first_cref_to(func_addr) while call_addr != BADADDR: # set color ———— green (red=0x0000ff,blue = 0xff0000) idc.set_color(call_addr, idc.CIC_ITEM, 0x00ff00) # set break point # AddBpt(call_addr) # DelBpt(call_addr) # if you want to use condition # SetBptCnd(ea, 'strstr(GetString(Dword(esp+4),-1, 0), "SAEXT.DLL") != -1') Mnemonics = print_insn_mnem(call_addr) # print "Mnemonics : %s" % Mnemonics # if Mnemonics in mispcall: if Mnemonics[0:1] == "j" or Mnemonics[0:1] == "b": # print func + " addr : 0x%x" % call_addr if func_name in format_function_offset_dict: info = auditFormat(call_addr, func_name, arg_num) else: info = auditAddr(call_addr, func_name, arg_num) table.add_row(info) call_addr = get_next_cref_to(func_addr, call_addr) print(table)
def hook_code(uc, address, size, user_data): instruction = uc.mem_read(address, size) if instruction == b'\xc3': uc.emu_stop() if address == 0: uc.emu_stop() if address != 0 and address != IMAGE_BASE: idc.set_color(address, idc.CIC_ITEM, 0xFFB6C1) if DEBUG: _code = idc.GetDisasm(address) print("0x%016x \t%s" % (address, _code))
def hilight_addr(self, addr: int) -> None: if is_dark_theme(): color_hilight = color_to_val(QtGui.QColor(self.color_hilight).darker(200)) else: color_hilight = self.color_hilight if self.prev_addr != BADADDR: ea = self.prev_addr self._set_segment_color(ea, self.color_normal) set_color(ea, CIC_ITEM, self.color_normal) if addr != BADADDR: ea = addr self._set_segment_color(ea, self.color_normal) set_color(addr, CIC_ITEM, color_hilight) self.prev_addr = addr
def retrieve_selected_functions(self, funcs): for ea in funcs: pfn = idaapi.get_func(ea) func_name = idaapi.get_func_name(ea) if idaapi.FlowChart(pfn).size < self.cfg['minsize']: continue targets = self.retrieve_function(ea, topk=1) if targets is None: print("[{}] {} is skipped because get function feature error".format(self.name, func_name)) continue func = targets[0] if func['score'] < self.cfg['threshold']: print("[{}] {} is skipped because top1_score lower than threshold({})".format( self.name, func_name, self.cfg['threshold'])) continue idc.set_color(ea, idc.CIC_FUNC, self.get_binaryai_function_color()) self.mark_function_as_binaryai(ea) comment = SourceCodeViewer.source_code_comment(func_name, func) idaapi.set_func_cmt(pfn, comment, 0)
def audit(func_name): func_addr = getFuncAddr(func_name) if func_addr == False: return False # get arg num and set table if func_name in one_arg_function: arg_num = 1 elif func_name in two_arg_function: arg_num = 2 elif func_name in three_arg_function: arg_num = 3 elif func_name in format_function_offset_dict: arg_num = format_function_offset_dict[func_name] + 1 else: print( "The %s function didn't write in the describe arg num of function array,please add it to,such as add to `two_arg_function` arary" % func_name) return table_head = ["func_name", "addr"] for num in range(0, arg_num): table_head.append("arg" + str(num + 1)) if func_name in format_function_offset_dict: table_head.append("format&value[string_addr, num of '%', fmt_arg...]") table_head.append("local_buf_size") table = PrettyTable(table_head) # get first call call_addr = get_first_cref_to(func_addr) while call_addr != BADADDR: idc.set_color(call_addr, idc.CIC_ITEM, 0x00ff00) Mnemonics = print_insn_mnem(call_addr) if Mnemonics[0:1] == "j" or Mnemonics[0:1] == "b": if func_name in format_function_offset_dict: info = auditFormat(call_addr, func_name, arg_num) else: info = auditAddr(call_addr, func_name, arg_num) table.add_row(info) call_addr = get_next_cref_to(func_addr, call_addr) print(table)
def run(self, arg=0): print("hell2") idaapi.msg("run() called with %d!\n" % arg) heads = Heads(get_segm_start(get_screen_ea()), get_segm_end(get_screen_ea())) funcCalls = [] xor = [] antiVM = [] for i in heads: # Color the Calls off-white if print_insn_mnem(i) == "call": funcCalls.append(i) # Color Anti-VM instructions Red and print their location elif print_insn_mnem(i) in ("sidt", "sgdt", "sldt", "smsw", "str", "in", "cpuid"): antiVM.append(i) # Color non-zeroing out xor instructions Orange elif print_insn_mnem(i) == "xor" and (print_operand(i,0) != print_operand(i,1)): xor.append(i) print("Number of calls: %d" % (len(funcCalls))) for i in funcCalls: set_color(i, CIC_ITEM, 0xc7fdff) print("Number of potential Anti-VM instructions: %d" % (len(antiVM))) for i in antiVM: print("Anti-VM potential at %x" % i) set_color(i, CIC_ITEM, 0x0000ff) print("Number of xor: %d" % (len(xor))) for i in xor: set_color(i, CIC_ITEM, 0x00a5ff)
def color_head(ea): flags = ida_bytes.get_flags(ea) if not ida_bytes.is_code(flags): return mnem = ida_ua.print_insn_mnem(ea) if mnem == 'call': logger.debug('call: 0x%x', ea) idc.set_color(ea, idc.CIC_ITEM, CALL_COLOR) elif mnem == 'xor': if idc.get_operand_value(ea, 0) != idc.get_operand_value(ea, 1): logger.debug('non-zero xor: 0x%x', ea) idc.set_color(ea, idc.CIC_ITEM, ENCRYPT_COLOR) elif mnem in ('sdit', 'sgdt', 'sldt', 'smsw', 'str', 'in', 'cpuid'): logger.debug('anti-vm: 0x%x', ea) idc.set_color(ea, idc.CIC_ITEM, ANTIANALYSIS_COLOR) elif mnem == 'in': if idc.get_operand_value(ea, 0) in ("3", "2D"): logger.debug('anti-debug: 0x%x', ea) idc.set_color(ea, idc.CIC_ITEM, ANTIANALYSIS_COLOR) elif mnem in ('rdtsc', 'icebp'): logger.debug('anti-debug: 0x%x', ea) idc.set_color(ea, idc.CIC_ITEM, ANTIANALYSIS_COLOR)
def apply(): """Provides an `apply()` method to color and mark your database and a `clean()` method to undo it. The `apply()` method colors `call`, `push` and `pop` instructions (sets background color). It also adds the prefix `>>` to`call` instructions and the number of argument to its parameters (only available if the function declaration is defined). This is useful to quickly identify function calls, their parameters and the calling convention.""" ida_auto.auto_wait() ea = idc.next_head(0) while ea != idaapi.BADADDR: instruction = idc.print_insn_mnem(ea) if instruction == "call": idc.set_color(ea, idc.CIC_ITEM, COLOR_CALL) addresses = idaapi.get_arg_addrs(ea) if addresses: _PARAMETERS.update({e: i + 1 for i, e in enumerate(addresses)}) elif instruction == "push": idc.set_color(ea, idc.CIC_ITEM, COLOR_PUSH) elif instruction == "pop": idc.set_color(ea, idc.CIC_ITEM, COLOR_POP) ea = idc.next_head(ea) ida_lines.set_user_defined_prefix(ALL_PREFIX_WIDTH, _prefix_callback) print("ANA color: Enjoy your colorful database!")
self.when = when self.testcase = testcase filename = idaapi.ask_file(False, '*.csv', 'Please select csv') blocks = [] with open(filename) as csvfile: readCSV = csv.reader(csvfile, delimiter=";", quotechar='"') next(readCSV) for row in readCSV: print row blocks.append(int(row[4])) for bb in blocks: absPos = bb + ida_nalt.get_imagebase() f = idaapi.get_func(absPos) if f is None: continue fc = idaapi.FlowChart(f) # Highlight the complete function idc.SetColor(absPos, idc.CIC_FUNC, 0xFFF000) for block in fc: if block.startEA <= absPos and block.endEA > absPos: #print "Setting colour for %x" % absPos for i in Heads(block.startEA, block.endEA): idc.set_color(i, CIC_ITEM, 0xFFAA00)
def _set_item_color(self, addr: int, color: int) -> None: ea = addr # reset to default self._set_segment_color(ea, self.color_normal) # set desired item color set_color(addr, CIC_ITEM, color)
def reset_colors(orig_colors): if orig_colors: for va, color in orig_colors.iteritems(): idc.set_color(va, idc.CIC_ITEM, orig_colors[va])
self.offset = offset self.reached = reached self.when = when self.testcase = testcase filename = ida_kernwin.ask_file(False, '*.csv', 'Please select csv') blocks = [] with open(filename) as csvfile: readCSV = csv.reader(csvfile, delimiter=";", quotechar='"') next(readCSV) for row in readCSV: print row blocks.append(int(row[4])) for bb in blocks: absPos = bb + ida_nalt.get_imagebase() f = ida_funcs.get_func(absPos) if f is None: continue fc = ida_gdl.FlowChart(f) # Highlight the complete function idc.set_color(absPos, idc.CIC_FUNC, 0xFFF000) for block in fc: if block.start_ea <= absPos and block.end_ea > absPos: #print "Setting colour for %x" % absPos for i in Heads(block.startEA, block.endEA): idc.set_color(i, CIC_ITEM, 0xFFAA00)
from __future__ import print_function #--------------------------------------------------------------------- # This illustrates the setting/retrievel of background colours, # using the IDC wrappers BG_BLUE = 0xc02020 BG_GREEN = 0x208020 BG_RED = 0x2020c0 import idc ea = idc.here() idc.set_color(ea, idc.CIC_SEGM, BG_BLUE) idc.set_color(ea, idc.CIC_FUNC, BG_GREEN) idc.set_color(ea, idc.CIC_ITEM, BG_RED) print("Segment: %x" % idc.get_color(ea, idc.CIC_SEGM)) print("Function: %x" % idc.get_color(ea, idc.CIC_FUNC)) print("Item: %x" % idc.get_color(ea, idc.CIC_ITEM))
def colorNode(self, node, color): try: set_color(node, CIC_ITEM, ColorCore.rgb_to_bgr(color)) except: SetColor(node, CIC_ITEM, ColorCore.rgb_to_bgr(color))
def highlight_insn(ea, color, comment="", repeatable=0): idc.set_color(ea, CIC_ITEM, color) idc.set_cmt(ea, comment, repeatable)
# show the address next to each command idc.set_inf_attr(INF_OUTFLAGS, OFLG_SHOW_PREF) idc.set_inf_attr(INF_PREFFLAG, 0) print("Finished setting options") currentEA = idc.get_first_seg() currentEA = idc.next_head(currentEA, 0xFFFFFFFFFFFFFFFF) while (currentEA != BADADDR): currentMnem = idc.print_insn_mnem(currentEA) #Highlight call functions if (currentMnem == "call"): #check to see if it's a call pop nextMnem = idc.print_insn_mnem(idc.get_operand_value(currentEA, 0)) if nextMnem == "pop": idc.set_color(currentEA, CIC_ITEM, 0xff1d4a) idc.set_color(idc.get_operand_value(currentEA, 0), CIC_ITEM, 0x4a1dFF) else: idc.set_color(currentEA, CIC_ITEM, 0xc7c7ff) #Non-zeroing XORs are often signs of data encoding if (currentMnem == "xor"): if (idc.print_operand(currentEA, 0) != idc.print_operand(currentEA, 1)): idc.set_color(currentEA, CIC_ITEM, 0xFFFF00) currentEA = idc.next_head(currentEA, 0xFFFFFFFFFFFFFFFF) prevMnem = currentMnem
def colorize(self): idc.set_color(self.ea - 4, CIC_ITEM, COLOR_ORANGE) for addr in self.class_lines: idc.set_color(addr, CIC_ITEM, COLOR_DARK_CYAN)