def pp_main(): global pp if pp and not pp.is_dead(): pp.die() pp = None return w = ida_kernwin.get_current_widget() title = "IDA View-A" if w: title = ida_kernwin.get_widget_title(w) title = ida_kernwin.ask_str(title, 0, "Please specify title of widget") if title: path = ida_kernwin.ask_str( "", ida_kernwin.HIST_DIR, "Please specify path containing png files to play back") if path and os.path.exists(path): files = find_files(path, "*.png") print("found %d files" % len(files)) if len(files): interval = ida_kernwin.ask_long( 100, "Please specify timer interval") if interval: pp = png_player_t(title, files, interval=interval) print("PNGs playing in widget %s" % title)
def OnFormChange(self, fid): if fid == self.iButtonSetString.id: s = ask_str("none", 0, "Enter value") if s: self.SetControlValue(self.cbEditable, s) elif fid == self.iButtonSetIndex.id: s = ask_str("1", 0, "Enter index value:") if s: try: i = int(s) except: i = 0 self.SetControlValue(self.cbReadonly, i) elif fid == self.iButtonAddelement.id: # add a value to the string list self.__n += 1 self.cbReadonly.add("some text #%d" % self.__n) # Refresh the control self.RefreshField(self.cbReadonly) elif fid == -2: s = self.GetControlValue(self.cbEditable) print "user entered: %s" % s sel_idx = self.GetControlValue(self.cbReadonly) return 1
def OnFormChange(self, fid): if fid == self.iButtonSetString.id: s = ask_str("none", 0, "Enter value") if s: self.SetControlValue(self.cbEditable, s) elif fid == self.iButtonSetIndex.id: s = ask_str("1", 0, "Enter index value:") if s: try: i = int(s) except: i = 0 self.SetControlValue(self.cbReadonly, i) elif fid == self.iButtonAddelement.id: # add a value to the string list self.__n += 1 self.cbReadonly.add("some text #%d" % self.__n) # Refresh the control self.RefreshField(self.cbReadonly) elif fid == -2: s = self.GetControlValue(self.cbEditable) print("user entered: %s" % s) sel_idx = self.GetControlValue(self.cbReadonly) return 1
def OnKeydown(self, vkey, shift): """ User pressed a key @param vkey: Virtual key code @param shift: Shift flag @return: Boolean. True if you handled the event """ print("OnKeydown, vk=%d shift=%d" % (vkey, shift)) # ESCAPE? if vkey == 27: self.Close() # VK_DELETE elif vkey == 46: n = self.GetLineNo() if n is not None: self.DelLine(n) self.Refresh() print("Deleted line %d" % n) # Goto? elif vkey == ord('G'): n = self.GetLineNo() if n is not None: v = ida_kernwin.ask_long(self.GetLineNo(), "Where to go?") if v: self.Jump(v, 0, 5) elif vkey == ord('R'): print("refreshing....") self.Refresh() elif vkey == ord('C'): print("refreshing current line...") self.RefreshCurrent() elif vkey == ord('A'): s = ida_kernwin.ask_str("NewLine%d" % self.Count(), 0, "Append new line") self.AddLine(s) self.Refresh() elif vkey == ord('X'): print("Clearing all lines") self.ClearLines() self.Refresh() elif vkey == ord('I'): n = self.GetLineNo() s = ida_kernwin.ask_str("InsertedLine%d" % n, 0, "Insert new line") self.InsertLine(n, s) self.Refresh() elif vkey == ord('E'): l = self.GetCurrentLine(notags=1) if not l: return False n = self.GetLineNo() print("curline=<%s>" % l) l = l + ida_lines.COLSTR("*", ida_lines.SCOLOR_VOIDOP) self.EditLine(n, l) self.RefreshCurrent() print("Edited line %d" % n) else: return False return True
def kernelcache_process(untag_pointers=True): """Process the kernelcache in IDA for the first time. This function performs all the standard processing available in this module: * Convert iOS 12's new static tagged pointers into normal kernel pointers. * Parse the kernel's `__PRELINK_INFO.__info` section into a dictionary. * Renames segments in IDA according to the names from the __PRELINK_INFO dictionary (split kext format kernelcaches only). * Converts pointers in data segments into offsets. * Locates virtual method tables, converts them to offsets, and adds vtable symbols. * Locates OSMetaClass instances for top-level classes and adds OSMetaClass symbols. * Symbolicates offsets in `__got` sections and stub functions in `__stubs` sections. * Symbolicates methods in vtables based on the method names in superclasses. * Creates IDA structs representing the C++ classes in the kernel. """ import ida_kernwin iometa = ida_kernwin.ask_str("/tmp/kernel.txt", 0, "iometa result file location") jtool2 = ida_kernwin.ask_str("/tmp/kernel_jtool2.txt", 0, "jtool2 analyze file location") joker.analyze(iometa, jtool2) import idaapi import idc autoanalyze() if (kernel.kernelcache_format == kernel.KC_12_MERGED and untag_pointers and idaapi.IDA_SDK_VERSION < 720): print 'Processing tagged kernelcache pointers' tagged_pointers.untag_pointers() autoanalyze() segment.initialize_segments() print 'Initializing data offsets' offset.initialize_data_offsets() autoanalyze() print 'Initializing vtables' vtable.initialize_vtables() autoanalyze() vtable.initialize_vtable_symbols() autoanalyze() metaclass.initialize_metaclass_symbols() if kernel.kernelcache_format == kernel.KC_11_NORMAL: print 'Creating offset and stub symbols' offset.initialize_offset_symbols() autoanalyze() stub.initialize_stub_symbols() autoanalyze() print 'Propagating vtable method symbols' vtable.initialize_vtable_method_symbols() print 'Initializing class structs' class_struct.initialize_vtable_structs() class_struct.initialize_class_structs() autoanalyze() print 'Done'
def add_or_del_one_xref_bpt(self, is_add): if is_add == True: action = idc.add_bpt act_info = '添加' else: action = idc.del_bpt act_info = '删除' tgt_t = ida_kernwin.ask_str('', 0, '请输入危险函数名') if tgt_t in SINK_FUNC: if not tgt_t in self.sink_func_xref_dict: mgr_t = FESinkFuncMgr() xref_list = mgr_t.get_one_func_xref(tgt_t) if not xref_list: FELogger.warn("未找到函数%s" % tgt_t) return tmp_list = [] for xref_addr in xref_list: tmp_list.append(xref_addr) action(xref_addr) self.sink_func_xref_dict[tgt_t] = tmp_list else: for xref_addr_t in self.sink_func_xref_dict[tgt_t]: action(xref_addr_t) FELogger.info("已%s断点:危险函数调用地址(%s)" % (act_info, tgt_t)) else: FELogger.warn("未支持函数")
def run(self, arg): if self.imported: if not self.psida_module.idb_push.CONFIGURATION["backend_hostname"]: connected = False while not connected: backend_hostname = ida_kernwin.ask_str("Hostname or IP", 0, "Backend not initialized, input your backend's name or IP:") if not backend_hostname: # User canceled return try: print backend_hostname self.psida_module.zmq_primitives.configure(backend_hostname=backend_hostname) reload(self.psida_module) reload(self.psida_module.zmq_primitives) # test connectivity self.psida_module.zmq_primitives.zmq_test_connectivity() connected = True except self.psida_module.zmq_primitives.ZMQConnectionException: idaapi.msg("ERROR - Run - ZMQ Connectivity failed, make sure your server is set-up correctly.\n") except socket.gaierror: idaapi.msg("ERROR - Run - Could not resolve server name. Make sure it's spelled correctly, and that you get DNS responses from it\n") if self.running: # Reload only if in debug mode. Do nothing otherwise if self.psida_module.idb_push.CONFIGURATION["debug"]: self.reload() else: reload(self.psida_module) self.psida_module.idb_push.start() if self.psida_module.idb_push.CONFIGURATION["debug"]: idaapi.msg("DEBUG - Run - Successfully started idb_push\n") self.running = True
def add(self): name = ida_kernwin.ask_str("", 0, "Target address") addr = convertVarName(name) if addr > 0: self.watch.add(addr, name) self.model.update() debugline("Watch %d added: 0x%X" % (self.watch.count(), addr))
def btn_get_one_sink_func_xref(self, code=0): """ 查看某个危险函数调用地址 """ tgt_t = ida_kernwin.ask_str('', 0, '请输入要查看的危险函数名') if tgt_t in SINK_FUNC: cols = [['', 0 | ida_kernwin.Choose.CHCOL_DEC], ['函数名', 10 | ida_kernwin.Choose.CHCOL_PLAIN], ['函数地址', 10 | ida_kernwin.Choose.CHCOL_HEX]] items = [] mgr_t = FESinkFuncMgr() xref_list = mgr_t.get_one_func_xref(tgt_t) if not xref_list: FELogger.warn("未找到函数%s" % tgt_t) return tmp_list = [] for xref_addr in xref_list: data = AnalysisChooseData(vuln=0, name=tgt_t, ea=xref_addr) items.append(data) tmp_list.append(xref_addr) self.sink_func_xref_dict[tgt_t] = tmp_list chooser = AnalysisChooser(title='危险函数调用地址', cols=cols, item=items) chooser.Show() else: FELogger.warn("未支持函数")
def btn_imp_ghidra_funcs(self, code=0): """ 导入Ghidra函数列表 """ ghidra_filepath = os.path.join(os.getcwd(), 'ghidra_func_addrs.csv') ghidra_path = ida_kernwin.ask_str(ghidra_filepath, 0, '导入的Ghidra导出函数文件路径') func_addrs = list(idautils.Functions()) make_func_addrs = [] if ghidra_path and ghidra_path != '': if os.path.exists(ghidra_path): with open(ghidra_path, 'rb') as f: next(f) reader = csv.reader(f) for row in reader: addr = int(row[0].strip('\"'), 16) if ida_funcs.add_func(addr) == True: make_func_addrs.append(addr) else: if addr not in func_addrs: FELogger.info("创建函数%s失败" % hexstr(addr)) FELogger.info("Ghidra导出函数文件:%s,已导入" % ghidra_path) else: FELogger.erro("未找到Ghidra导出函数文件:%s" % ghidra_path) else: FELogger.warn("请输入Ghidra导出函数文件路径") FELogger.info("成功创建%d个新函数" % len(make_func_addrs))
def btn_dfs_test_1(self, code=0): addr_t = ida_kernwin.ask_str('', 0, '请输入回溯起点地址') reg_t = ida_kernwin.ask_str('', 0, '请输入回溯寄存器') if (addr_t and addr_t != '') and (reg_t and reg_t != ''): try: addr_t = int(addr_t, 16) except Exception: FELogger.warn("无效地址") return FELogger.info("从地址%s回溯寄存器%s" % (hexstr(addr_t), reg_t)) tracer = FEArgsTracer(addr_t, reg_t) source_addr = tracer.run() print('source_addr: ', source_addr) else: FELogger.warn("请输入起点地址和寄存器")
def OnEditLine(self, sel): self._print_prev_frame() for idx in sel: repl = ida_kernwin.ask_str("", 0, "Please enter replacement for index %d" % idx) if repl: self.netnode.supset(idx, repl, SUPVAL_COL0_DATA_TAG) self._dump_items() return [ida_kernwin.Choose.ALL_CHANGED] + sel
def btn_dfs_test_2(self, code=0): tgt_t = ida_kernwin.ask_str('', 0, '请输入函数名') reg_t = ida_kernwin.ask_str('', 0, '请输入回溯寄存器') if (tgt_t and tgt_t != '') and (reg_t and reg_t != ''): for func_addr_t in idautils.Functions(): func_name_t = ida_funcs.get_func_name(func_addr_t) if func_name_t == tgt_t: for xref_addr_t in idautils.CodeRefsTo(func_addr_t, 0): if ida_funcs.get_func(xref_addr_t): FELogger.info("从地址%s回溯寄存器%s" % (hexstr(xref_addr_t), reg_t)) tracer = FEArgsTracer(xref_addr_t, reg_t, max_node=256) source_addr = tracer.run() print('source_addr: ', source_addr) break else: FELogger.warn("请输入函数名和寄存器")
def btn_del_one_vuln_bpt(self, code=0): """删除断点 某个危险函数漏洞地址""" tgt_t = ida_kernwin.ask_str('', 0, '请输入危险函数名') if tgt_t in SINK_FUNC: if tgt_t in self.vuln_func_fast_dict: for xref_addr_t in self.vuln_func_fast_dict[tgt_t]: ida_dbg.del_bpt(xref_addr_t) FELogger.info("已删除断点:危险函数漏洞分析(%s)" % tgt_t) else: FELogger.warn("未支持函数")
def main(): va = ida_kernwin.get_screen_ea() f = ida_funcs.get_func(va) if not f: logger.error("function not found: 0x%x", va) return path = find_function_dirtree_path(f.start_ea) if not path: logger.error("function directory entry not found: 0x%x", f.start_ea) return func_dir: dirtree_t = ida_dirtree.get_std_dirtree( ida_dirtree.DIRTREE_FUNCS) dirent = func_dir.resolve_path(path) name = func_dir.get_entry_name(dirent) existing_tag = path[:-(len("/") + len(name))].lstrip("/") # ask_str(defval, hist, prompt) -> PyObject * # I'm not sure what "history id" does. tag = ida_kernwin.ask_str(existing_tag, 69, "tag:") if not tag: return tag_path = f"/{tag}" if not func_dir.isdir(tag_path): logger.info("creating tag: %s", tag) e = dirtree_mkdirs(func_dir, tag_path) if e != ida_dirtree.DTE_OK: logger.error("error: failed to create tag: %s", tag) return else: logger.debug("tag exists: %s", tag) src_path = path src_dirent = func_dir.resolve_path(src_path) src_name = func_dir.get_entry_name(src_dirent) dst_name = src_name dst_path = f"{tag_path}/{dst_name}" if src_path == dst_path: logger.info("skipping move to itself") return logger.info("moving %s from %s to %s", src_name, src_path, dst_path) e = func_dir.rename(src_path, dst_path) if e != ida_dirtree.DTE_OK: logger.error("error: %s", ida_dirtree.dirtree_t_errstr(e)) return set_func_folder_cmt(f.start_ea, tag)
def btn_del_tmp_func_bpt(self, code=0): """删除临时函数断点""" tgt_t = ida_kernwin.ask_str('', 0, '请输入任意函数名') try: if tgt_t in self.tmp_func_dict: for xref_addr_t in self.tmp_func_dict[tgt_t]: ida_dbg.del_bpt(xref_addr_t) CUSTOM_FUNC.pop(tgt_t) FELogger.info("已删除断点:指定函数调用地址 %s" % tgt_t) except Exception: FELogger.warn("请输入函数名")
def main(): dllname = ida_kernwin.ask_str('kernel32', 0, "Enter module name") if not dllname: print("Cancelled") return imports, R = find_import_ref(dllname) for k, v in R.items(): print(imports[k][1]) for ea in v: print("\t%x" % ea)
def sr_main(): global sr if sr: del sr sr = None print("Stopped recording") else: w = ida_kernwin.get_current_widget() title = "IDA View-A" if w: title = ida_kernwin.get_widget_title(w) title = ida_kernwin.ask_str( title, 0, "Please specify title of widget to capture") if title: path = ida_kernwin.ask_str("", ida_kernwin.HIST_DIR, "Please specify destination path") if path and os.path.exists(path): sr = screen_record_t(title, path) print("Started recording")
def changeName(self): if len(self.tree.selectedIndexes()) <= 0: return index = self.tree.selectedIndexes()[0] item = index.internalPointer() inp = ida_kernwin.ask_str("", 0, "New Name") if inp != None and inp.rstrip() != "": item.setName(inp) self.update()
def _set_user_expr(self): while True: xpr = ask_str(self.xpr, 0, "Please enter expression") if xpr is None: break try: r = g = b = 0 r, g, b = eval(xpr) self.xpr = xpr break except: warning("Invalid expression!") continue
def _set_pattern(self): while True: pat = ask_str(self.pattern, 0, "Regular expression:") if pat is None: break try: c = 0 prog = re.compile(pat) self.pattern = pat self.regex = prog break except: warning("Invalid expression!") continue
def rename_func(): """rename function, suggests current identifier as function name""" name = _get_identifier() if name: str = ida_kernwin.ask_str(name, -1, "Rename function") if str: f = ida_funcs.get_func(ida_kernwin.get_screen_ea()) if f: if ida_name.set_name(f.start_ea, str, ida_name.SN_NOCHECK): cv = ida_kernwin.get_current_viewer() if ida_kernwin.get_widget_type( cv) == ida_kernwin.BWN_PSEUDOCODE: vd = ida_hexrays.get_widget_vdui(cv) if vd: vd.refresh_view(True) return
def main(): sig = ida_kernwin.ask_str("", 0, "Insert signature: ") # wtfwtfwtfwtf oldsig = sig sig = sig.replace(r"\x", " ").replace("2A", "?").replace("2a", "?").strip() # print(sig) count = checksig(sig) if not count: print(r"INVALID: {}".format(oldsig)) print("Could not find any matching signatures for input") elif count == 1: print(r"VALID: {}".format(oldsig)) else: print(r"INVALID: {}".format(oldsig)) print("Found {} instances of input signature".format(count))
def OnPopupMenu(self, menu_id): if menu_id == self.menu_update: self.update(True) elif menu_id == self.menu_lookup: inst = ask_str(self.last_inst, 0, "Instruction: ") if inst != None: self.load_inst(inst, True) elif menu_id == self.menu_autorefresh: self.do_auto = not self.do_auto elif menu_id == self.change_arch: arch = self.askArchitecture(self.archs) if arch != None: self.loadArchitecture(arch) self.update(True) else: # Unhandled return False return True
def changeType(self): if len(self.tree.selectedIndexes()) <= 0: return index = self.tree.selectedIndexes()[0] if not index.internalPointer().canchangetype: return inp = ida_kernwin.ask_str("", 0, "New Type") if inp != None and inp.rstrip() != "": typ = parseType(inp) if typ == None: return debugline("change type to %s" % typ.typerepr()) self.model.changeType(index, typ) self.update()
def run(self, arg): """ run the fastFix.py will call this """ arch = fastFixArch() arch_info = arch.getArch() if arch_info[0]=='metapc' and arch_info[1]=='64' and arch_info[2]=='Little': """ Ensure the ARCH is x86_64 Litlle endian """ print("Program ARCH information:{},{},{}".format(arch_info[0],arch_info[1],arch_info[2])) else: print("Sorry! fastFix doesn't support your ARCH!") exit(0) try: l = (ida_kernwin.ask_str("", 0, "Please enter start and end address:")).split(",") # popup a windows to ask user getAddr = fastFixGetAddr(int(l[0],16),int(l[1],16),search_eh_frame()) # Init addr information. print("[0x%lx]:%s\n[0x%lx]:%s\n"%(getAddr.start,idc.GetDisasm(getAddr.start),getAddr.end,idc.GetDisasm(getAddr.end))) except Exception,err: print(err) exit(0)
def activate(self, ctx): vu = ida_hexrays.get_widget_vdui(ctx.widget) if not IsPtrSizedLvar(vu): return 1 lvar = vu.item.get_lvar() name = ida_kernwin.ask_str( "", ida_kernwin.HIST_IDENT, "Please enter the API name for which to set the type") if name is None: return 1 ptrTif = GetTypeSignature(name) if ptrTif is None: ida_kernwin.warning("Could not get type for \"%s\"" % name) return 1 ChangeVariableType(vu.cfunc.entry_ea, lvar, ptrTif) vu.cfunc.refresh_func_ctext() return 1
def IssueCommand(self): s = ida_kernwin.ask_str(self.last_cmd, 0, "Please enter a debugger command") if not s: return # Save last command self.last_cmd = s # Add it using a different color self.AddLine("debugger>" + ida_lines.COLSTR(s, ida_lines.SCOLOR_VOIDOP)) ok, out = ida_dbg.send_dbg_command(s) if ok: for line in out.split("\n"): self.AddLine(ida_lines.COLSTR(line, ida_lines.SCOLOR_LIBNAME)) else: self.AddLine( ida_lines.COLSTR( "Debugger is not active or does not export ida_dbg.send_dbg_command() (%s)" % out, ida_lines.SCOLOR_ERROR)) self.Refresh()
def btn_checksec(self, code=0): """ ELF Checksec """ elfpath = ida_nalt.get_input_file_path() if os.path.exists(elfpath): result = Checksec(elfpath) FELogger.info("-" * 10 + "Checksec" + "-" * 10 + elfpath + "-" * 10) FELogger.info(result.sec) else: input_path = ida_kernwin.ask_str(elfpath, 0, "请输入原始Binary路径") if input_path and input_path != "": if os.path.exists(input_path): result = Checksec(input_path) FELogger.info("-" * 10 + "Checksec" + "-" * 10 + input_path + "-" * 10) FELogger.info(result.sec) else: FELogger.info("原始Binary不存在:%s" % input_path) else: FELogger.info("原始Binary不存在:%s" % elfpath)
def btn_add_one_vuln_bpt(self, code=0): """添加断点 某个危险函数漏洞地址""" tgt_t = ida_kernwin.ask_str('', 0, '请输入危险函数名') if tgt_t in SINK_FUNC: if not tgt_t in self.vuln_func_fast_dict: mgr_t = FESinkFuncMgr() xref_list = mgr_t.get_one_func_xref(tgt_t) tag = SINK_FUNC[tgt_t]['tag'] if not xref_list: FELogger.warn("未找到函数%s" % tgt_t) return if tag == FUNC_TAG['PRINTF']: items = printf_func_analysis(tgt_t, xref_list) self.add_fast_dict_from_items(items) elif tag == FUNC_TAG['STRING']: items = str_func_analysis(tgt_t, xref_list) self.add_fast_dict_from_items(items) elif tag == FUNC_TAG['SCANF']: items = scanf_func_analysis(tgt_t, xref_list) self.add_fast_dict_from_items(items) elif tag == FUNC_TAG['SYSTEM']: items = system_func_analysis(tgt_t, xref_list) self.add_fast_dict_from_items(items) elif tag == FUNC_TAG['MEMORY']: items = mem_func_analysis(tgt_t, xref_list) self.add_fast_dict_from_items(items) else: FELogger.info("未支持函数%s" % tgt_t) if tgt_t in self.vuln_func_fast_dict: for xref_addr_t in self.vuln_func_fast_dict[tgt_t]: ida_dbg.add_bpt(xref_addr_t, 0, idc.BPT_DEFAULT) FELogger.info('已添加断点:危险函数漏洞分析(%s)' % tgt_t) else: FELogger.warn("未支持函数")
def readline(self): return ida_kernwin.ask_str('', 0, 'Help topic?')
def ask_str(default, label, hist=0): if idaapi.IDA_SDK_VERSION <= 699: mark = idc.AskStr(default, label) else: mark = ida_kernwin.ask_str(default, hist, label) return mark