def btn_save_on_click(self): flags = 0 if self.f_prev_inuse.isChecked(): flags |= PREV_INUSE if self.f_is_mmaped.isChecked(): flags |= IS_MMAPPED if self.f_non_main_arena.isChecked(): flags |= NON_MAIN_ARENA try: size = eval(self.t_size.text()) size |= flags fd = eval(self.t_fd.text()) bk = eval(self.t_bk.text()) fd_nextsize = eval(self.t_fd_nextsize.text()) bk_nextsize = eval(self.t_bk_nextsize.text()) self.chunk.size = size self.chunk.fd = fd self.chunk.bk = bk self.chunk.fd_nextsize = fd_nextsize self.chunk.bk_nextsize = bk_nextsize idaapi.patch_bytes(self.addr, self.chunk.data) idaapi.info("Chunk saved") self.done(1) except Exception as e: idaapi.warning("ERROR: " + str(e))
def bulk_prefix(): """ Prefix the Functions window selection with a user defined string. """ # prompt the user for a prefix to apply to the selected functions tag = idaapi.ask_str(PREFIX_DEFAULT, 0, "Function Tag") # the user closed the window... ignore if tag == None: return # the user put a blank string and hit 'okay'... notify & ignore elif tag == '': idaapi.warning("[ERROR] Tag cannot be empty [ERROR]") return # # loop through all the functions selected in the 'Functions window' and # apply the user defined prefix tag to each one. # for func_name in get_selected_funcs(): # ignore functions that already have the specified prefix applied if func_name.startswith(tag): continue # apply the user defined prefix to the function (rename it) new_name = '%s%s%s' % (str(tag), PREFIX_SEPARATOR, func_name) func_addr = idaapi.get_name_ea(idaapi.BADADDR, func_name) idaapi.set_name(func_addr, new_name, idaapi.SN_NOWARN) # refresh the IDA views refresh_views()
def handle_set_struct(self): if self.edit_class is None: return default_struct_name = idc.get_struc_name(self.edit_class.struct_id) \ if self.edit_class.struct_id != idc.BADADDR else \ self.edit_class.name dlg = ChooseStructDialog(default_struct_name, has_none_btn=True) if dlg.exec_() != QtWidgets.QDialog.Accepted: return if dlg.struct_id == self.edit_class.struct_id: return db = database.get() if dlg.struct_id in db.classes_by_struct_id: idaapi.warning( 'The struct "%s" is already linked to the class "%s"' % (idc.get_struc_name( dlg.struct_id), b.classes_by_struct_id[dlg.struct_id])) return delete_orphaned = False if self.edit_class.struct_id != idc.BADADDR: delete_orphaned = util.ask_yes_no( 'Do you want to delete the orphaned class', False) self.edit_class.set_struct_id(dlg.struct_id, delete_orphaned) self.update_fields()
def get_selected_funcs(): """ Return the list of function names selected in the Functions window. """ import sip twidget = idaapi.find_widget("Functions window") widget = sip.wrapinstance(int(twidget), QtWidgets.QWidget) # TODO: test this if not widget: idaapi.warning("Unable to find 'Functions window'") return # # locate the table widget within the Functions window that actually holds # all the visible function metadata # table = widget.findChild(QtWidgets.QTableView) # # scrape the selected function names from the Functions window table # selected_funcs = [str(s.data()) for s in table.selectionModel().selectedRows()] # # re-map the scraped names as they appear in the function table, to their true # names as they are saved in the IDB. See the match_funcs(...) function # comment for more details # return match_funcs(selected_funcs)
def run(self, arg): """ :param arg: Integer, a non-zero value enables auto-run feature for IDA batch (no gui) processing mode. Default is 0. """ log("plugin run") if not is_jni_header_loaded(): idaapi.warning('Please load jni.h first') load_jni_header() st = idc.set_ida_state(idc.IDA_STATUS_WORK) infos = load_methods() failed = [] succ = 0 for ea in idautils.Functions(): fname = idc.GetFunctionName(ea) if fname.startswith('Java_'): info = infos.get(fname) if info is None: failed.append(fname) else: succ += 1 apply_signature(ea, info) if fname == 'JNI_OnLoad': apply_load_unload(ea, True) succ += 1 if fname == 'JNI_OnUnload': apply_load_unload(ea, False) succ += 1 idaapi.info('JNI functions loaded, {} success. {} failed. \n{}'.format( succ, len(failed), '\n'.join(failed) )) idc.set_ida_state(st)
def main(): log("plugin run") if not is_jni_header_loaded(): idaapi.warning('Please load jni.h first') load_jni_header() st = idc.set_ida_state(idc.IDA_STATUS_WORK) infos = load_methods() failed = [] succ = 0 for ea in idautils.Functions(): fname = idc.get_func_name(ea) if fname.startswith('Java_'): info = infos.get(fname) if info is None: failed.append(name) else: succ += 1 apply_signature(ea, info) if fname == 'JNI_OnLoad': apply_load_unload(ea, True) succ += 1 if fname == 'JNI_OnUnload': apply_load_unload(ea, False) succ += 1 idaapi.info('JNI functions loaded, {} success. {} failed. \n{}'.format( succ, len(failed), '\n'.join(failed) )) idc.set_ida_state(st)
def on_click(self, event): if event.dblclick and event.xdata: addr = self.calc_addr_fcn(int(event.xdata)) if addr: idaapi.jumpto(addr) else: idaapi.warning("Unable to calculate the address")
def OnFormChange(self, fid): if fid == -2: # click on ok print "Clicked on login" user_token = try_to_log_in(self.GetControlValue(self.iUserName), self.GetControlValue(self.iPassword)) if user_token == -1: warning("Error, invalid username and password {0} {1}".format( self.GetControlValue(self.iUserName), self.GetControlValue(self.iPassword))) else: try: decoded_token = jwt.decode(user_token, constants.SERVER_PUBLIC_KEY, algorithms=["RS256"], audience=self.GetControlValue( self.iUserName)) shared.USERID = decoded_token["id"] shared.USERNAME = decoded_token["username"] shared.USER_TOKEN = user_token except Exception as e: warning("Problem with server signing!") return 0 return 1 else: return 1
def run(self, arg): # Get the highlighted identifier id = idaapi.get_highlighted_identifier() if not id: print "No identifier was highlighted" return import webbrowser try: import feedparser except: idaapi.warning('Feedparser package not installed') return id = self.sanitize_name(id) print "Looking up '%s' in MSDN online" % id d = feedparser.parse( "http://social.msdn.microsoft.com/Search/Feed.aspx?locale=en-us&format=RSS&Query=%s" % id) if len(d['entries']) > 0: url = d['entries'][0].link webbrowser.open_new_tab(url) else: print "API documentation not found for: %s" % id
def decompile_function(address, use_ghidra_server, ghidra_headless_path, ghidra_plugins_path, ghidra_server_url): """ Decompile function at address @address """ try: print("GhIDA:: [DEBUG] Decompiling %s" % address) xml_file_path, bin_file_path = export_ida_project_to_xml() # Get the decompiled code if use_ghidra_server: decompiled = ghidraaas_decompile(address, xml_file_path, bin_file_path, ghidra_server_url) else: decompiled = ghidra_headless(address, xml_file_path, bin_file_path, ghidra_headless_path, ghidra_plugins_path) return decompiled except Exception: print("GhIDA:: [!] Decompilation error") idaapi.warning("GhIDA decompilation error")
def _get_selected_funcs(self): """ Return the list of function names selected in the Functions window. Warning: It's possible that we don't get the correct name for a function lookup. In that case, this function will fail. See: https://github.com/gaasedelen/prefix/blob/master/plugin/ida_prefix.py#L567 """ twidget = idaapi.find_widget("Functions window") widget = sip.wrapinstance(int(twidget), QWidget) if not widget: idaapi.warning("Unable to find 'Functions window'") return # # locate the table widget within the Functions window that actually holds # all the visible function metadata # table: QTableView = widget.findChild(QTableView) # # scrape the selected function names from the Functions window table # selected_funcs = [ str(s.data()) for s in table.selectionModel().selectedRows() ] return selected_funcs
def handle_set_vtable_range(self): if self.edit_class is None: return selection = idaapi.read_selection() # Check selection if selection[1] == idc.BADADDR or selection[2] == idc.BADADDR: return if selection[1] > selection[2]: return if selection[1] != idc.ScreenEA() and selection[2] != idc.ScreenEA(): return # Warning for large ranges if (selection[2] - selection[1]) > 0x1000: if not util.ask_yes_no( 'Warning: The VTable range is longer than 0x1000 bytes. Continue?', False): return try: self.edit_class.set_vtable_range(selection[1], selection[2]) self.update_fields() except ValueError as e: idaapi.warning(str(e))
def activate(self, ctx): print("[CollaRE] Exporting ...") if ".collare_projects" in ida_nalt.get_input_file_path(): changes = { "function_names": {}, "comments": {}, "base": int(idaapi.get_imagebase()) } for segea in Segments(): for funcea in Functions(segea): # Name functionName = get_func_name(funcea) if hex(funcea)[2:].upper() not in functionName: changes["function_names"][int(funcea)] = { "name": functionName, "end": 0 } for ea in range(segea, get_segm_end(segea)): comment = get_comment(ea) if comment: changes["comments"][ea] = comment with open( os.path.join( os.path.dirname(ida_nalt.get_input_file_path()), "changes.json"), "w") as changes_file: json.dump(changes, changes_file) print("[CollaRE] Export completed!") idaapi.info("CollaRE Export completed!") else: print("[CollaRE] Export failed! Not a CollaRE project!") idaapi.warning("This is not a CollaRE project!") return 1
def _handle_btn_run_query(self): self._commit_settings() settings = self._get_settings() qo = compile_code(settings) if qo: scope = settings.scope if scope == 0: ea_list = list(idautils.Functions()) elif scope == 1 or scope == 2: screen_ea = idaapi.get_screen_ea() ea_list = [] if scope == 1: ea_list.append(screen_ea) else: ea_list = get_func_xrefs(screen_ea) elif scope == 3 and settings.query_type == 0: ea_list = qo.get_scope() else: idaapi.warning("%s: invalid scope!" % SCRIPT_NAME) return # if the query is a function if settings.query_type == 0: # call init() and check whether it is ok to run this query if qo.init(): # run query on ea_list run_query(qo.run, ea_list, settings) # call cleanup/exit function qo.exit() # otherwise it is a lambda expression else: run_query(qo, ea_list, settings) return
def update_address(self): sender = self.sender() value = sender.text() if len(value) == 0 or value == "0x": return try: value = int(value, 16) if sender is self.t_start_addr: self.config.start_addr = value elif sender is self.t_end_addr: self.config.end_addr = value """ update progress bars """ """ if self.config.start_addr and self.config.end_addr \ and self.config.start_addr < self.config.end_addr: self.update_progress_bars() """ except ValueError as e: idaapi.warning("Invalid value for address")
def update_gp(self): if self.init_gp == 0: self.init_gp = PsxExe.__get_real_gp(self.rom_addr, self.rom_addr + self.rom_size) if self.init_gp != 0: idc.process_config_line("MIPS_GP=0x%08X" % self.init_gp) else: idaapi.warning('$GP from header is zero! Check \'start \' function for a $gp loading instruction.\n')
def find_hash(*args): # read le hash needle = idaapi.askstr(0, "ERROR", "Hash value") if needle is None or needle == "ERROR" or len(needle) > 8: idaapi.warning("Bad input, please specify a 8 bytes hash") return fHash(needle) return
def log(cls, level, msg, debug): if level == 'console': msg_t = '%s\n' % msg else: msg_t = '[%s] %s\n' % (level, msg) idaapi.msg(msg_t) if level == 'warn' or level == 'erro': idaapi.warning(msg_t)
def patcherex_finish(proc): if proc.returncode != 0: out_str = "Patcherex failed. See attached terminal." idaapi.warning(out_str) print out_str else: out_str = "Patcherex completed successfully." idaapi.info(out_str) print out_str
def get_libc_offsets(self): libc_symbols = { 'variables': [ 'environ', '__environ', '__free_hook', '__malloc_hook', '__realloc_hook', '_IO_list_all', '_IO_2_1_stdin_', '_IO_2_1_stdout_', '_IO_2_1_stderr_', ], 'functions': [ 'system', '__libc_system', 'execve', 'open', '__open64', 'read', 'write', '__write', '_IO_gets', 'gets', 'setcontext+0x35', ] } result = { 'variables': OrderedDict(), 'functions': OrderedDict(), } self.libc_base = get_libc_base() if not self.libc_base: return result libc_names = get_libc_names() if not libc_names: idaapi.warning("Unable to get glibc symbols") return result for s_type, symbols in libc_symbols.items(): for sym in symbols: name_expr = parse_name_expr(sym) if not name_expr: continue name, offset = name_expr addr = libc_names.get(name) if addr: addr += offset offset = addr - self.libc_base result[s_type][sym] = offset return result
def exportNames(self) -> None: """Exports functions list into a file. """ file_name, ext = QtWidgets.QFileDialog.getSaveFileName(None, "Export functions names", QtCore.QDir.homePath(), "CSV Files (*.csv);;TAG Files (*.tag)") if file_name is not None and len(file_name) > 0: if not self._saveFunctionsNames(file_name, ext): idaapi.warning("Failed exporting functions names!") else: idaapi.info("Exported to: %s", (file_name, ))
def init_heap(self): try: self.config_widget.load_config() self.heap = Heap() self.btn_reload.setEnabled(True) self.tabs.setTabEnabled(3, self.heap.tcache_enabled) except Exception as e: self.show_warning("Please, fix the config file") idaapi.warning(traceback.format_exc())
def jump_in_hex(self): ea = self.get_current_expr_ea() if not ea or not idaapi.is_loaded(ea): idaapi.warning("Unable to resolve current expression\n") widget = self.find_hex_view() if not widget: idaapi.warning("Unable to find hex view") return self.jumpto_in_view(widget, ea)
def set_stack_entries(self): value = idc.AskLong(config.n_stack_entries, "Set the number of stack entries to show") if value is not None: if value <= 0: idaapi.warning("Negative values are not allowed") return False config.n_stack_entries = value self.reload_info() return True return False
def show(self): n_items = len(self.items) if n_items > 0: b = self.Show() if b == 0: self.cmd_exclude_code_xrefs = self.AddCommand("Exclude code xrefs") return True else: idaapi.warning("No xrefs found") return False
def edit_chunk_on_click(self): chunk_addr = self.get_chunk_address() if chunk_addr is None: idaapi.warning("Invalid address / expression") return w = ChunkEditor(chunk_addr, self) if w.exec_() == 1: self.view_chunk_info() # -----------------------------------------------------------------------
def check_before_use(self, check_funcset=False): if not self.client: idaapi.warning("Wrong token!") BinaryAIOptionsForm.change_options(self, check_token=True) return False if (not self.funcset) and \ (check_funcset or not self.cfg['usepublic']): idaapi.warning("Wrong function set!") BinaryAIOptionsForm.change_options(self, check_funcset=True) return False return True
def change_options(mgr, check_token=False): bai_options = BinaryAIOptionsForm(mgr) if bai_options.Execute(): for k, v in bai_options.form_record.items(): bai_config[k] = v if check_token or bai_options.token != bai_config['token']: mgr.update_token(bai_options.token) if not mgr.client: idaapi.warning("Wrong token!") BinaryAIOptionsForm.change_options(mgr, check_token=True)
def __init__(self, host, port, bits): super(PinConnection, self).__init__(AF_INET, SOCK_STREAM) self.bits = bits self.running = False self.settimeout(2) try: self.connect((host, port)) assert self.bits == self.hello() self.running = True except timeout: idaapi.warning("Cannot connect!")
def jump_in_new_window(self): ea = self.get_current_expr_ea() if not ea or not idaapi.is_loaded(ea): return window_name = "D-0x%x" % ea widget = idaapi.open_disasm_window(window_name) if widget: self.jumpto_in_view(widget, ea) else: idaapi.warning("Unable to create the new window")
def jump_to(self): current = self.base_expr if self.base_expr is not None else "" b = idaapi.ask_str(current, 0, "Sync with") if b and len(b) > 0: try: self.base_expr = b self.reload_info() except: idaapi.warning("Invalid expression") else: self.base_addr = None
def OnCommand(self, n, cmd_id): # Apply patches to a file if cmd_id == self.cmd_apply_patches: # Set initial start/end EA values start_ea = 0x0 end_ea = idaapi.cvar.inf.maxEA # Set initial output file values org_file = GetInputFilePath() bkp_file = "%s.bak" % org_file # Create the form f = PatchApplyForm(start_ea, end_ea, org_file, bkp_file) # Execute the form ok = f.Execute() if ok == 1: # Get restore checkbox self.restore = f.rRestore.checked # Get updated ea max/min start_ea = f.intStartEA.value end_ea = f.intEndEA.value # Get updated file path new_org_file = f.orgFile.value # Backup the file before replacing if f.rBackup.checked: bkp_file = f.bkpFile.value shutil.copyfile(org_file, bkp_file) # Apply patches try: self.patch_file = open(new_org_file,'rb+') except Exception, e: idaapi.warning("Cannot update file '%s'" % new_org_file) else: #r = idaapi.visit_patched_bytes(start_ea, end_ea, self.apply_patch_byte) r = visit_patched_bytes(start_ea, end_ea, self.apply_patch_byte) self.patch_file.close() self.restore = False # Update db input file, so we are working # with a patched version. #if not org_file == new_org_file: # idaapi.set_root_filename(new_org_file) # org_file = new_org_file # Dispose the form f.Free()
def createIndexProgressForm(self, funcs, cnn=None): if cnn is None: cnn = self.connector form = IndexProgressForm(cnn, funcs) form.Execute() code = form.ErrorCode content = form.Content form.Free() if code > OK: Connector.getCodeDescription(code, content) idaapi.warning("Connection failed. Please review your connection. \n \"%s\"" % content) self.openConnectionManagmentForm(ctx=None)
def __init__(self, settings): self.trace = [] self.connection = None self.settings = settings global idacmd_packet_t, heap_op_packet_t if self.settings.bits == 32: idacmd_packet_t = idacmd_packet_t_32 heap_op_packet_t = heap_op_packet_t_32 elif self.settings.bits == 64: idacmd_packet_t = idacmd_packet_t_64 heap_op_packet_t = heap_op_packet_t_64 else: idaapi.warning("WTF! Bits not 32 or 64!?")
def run(self, arg=0): try: if "ELF" not in idaapi.get_file_type_name(): raise Exception("Executable must be ELF fomat") if not idaapi.is_debugger_on() or not idaapi.dbg_can_query(): raise Exception("The debugger must be active and suspended before using this plugin") f = HeapPluginForm() f.Show() except Exception as e: idaapi.warning("[%s] %s" % (PLUGNAME, e.message))
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()
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()
def show_import_form(self): selection, start_ea, end_ea = idaapi.read_selection() if not selection: start_ea = idaapi.get_screen_ea() end_ea = start_ea + 1 # Create the form f = DataImportForm(start_ea, end_ea); # Execute the form ok = f.Execute() if ok == 1: start_ea = f.intStartEA.value end_ea = f.intEndEA.value if f.rFile.selected: imp_file = f.impFile.value try: f_imp_file = open(imp_file,'rb+') except Exception, e: idaapi.warning("File I/O error({0}): {1}".format(e.errno, e.strerror)) return else: buf = f_imp_file.read() f_imp_file.close() else: buf = f.strPatch.value # Hex values, unlike string literal, needs additional processing if f.rHex.selected: buf = buf.replace(' ','') # remove spaces buf = buf.replace('\\x','') # remove '\x' prefixes buf = buf.replace('0x','') # remove '0x' prefixes try: buf = binascii.unhexlify(buf) # convert to bytes except Exception, e: idaapi.warning("Invalid input: %s" % e) f.Free() return
def new_trace(self): self.trace = [] self.connection = PinConnection(self.settings.host, self.settings.port, self.settings.bits) if not self.connection.running: self.show_heaptracer_menu() return while 1: try: ops = self.connection.get_heap_ops() for op in ops: print "="*10+heap_op_type_t[op.code]+"="*10 print op.text_dump() sleep(1) except error: self.connection.running = False idaapi.warning("Process finished!") break
def run(self, arg): # Get the highlighted identifier id = idaapi.get_highlighted_identifier() if not id: print "No identifier was highlighted" return import webbrowser try: import feedparser except: idaapi.warning('Feedparser package not installed') return id = self.sanitize_name(id) print "Looking up '%s' in MSDN online" % id d = feedparser.parse("http://social.msdn.microsoft.com/Search/Feed.aspx?locale=en-us&format=RSS&Query=%s" % id) if len(d['entries']) > 0: url = d['entries'][0].link webbrowser.open_new_tab(url) else: print "API documentation not found for: %s" % id
def NasmAssemble(self, function_ea, write_ea): dir = self.opty_dir nasm = "C:\\Program Files\\nasm\\nasm.exe" arg1 = "f_%08x.asm" % function_ea arg2 = "-o f_%08x.o" % function_ea arg3 = "-l f_%08x.lst" % function_ea arg4 = "-Ox" orig_dir = os.getcwd() os.chdir(dir) idc.Batch(0) while 1: try: p = subprocess.Popen([nasm, arg1, arg2, arg3, arg4], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) o, e = p.communicate() if o != "": print o if e != "": print e fop = open("f_%08x.o" % function_ea, "rb") ans = idaapi.askyn_c(0, "HIDECANCEL\nDo you want to manually edit function before writing to IDA?") if ans == 1: os.startfile(arg1, "open") idaapi.warning("Press OK button when you're done editing file.") fop.close() continue else: idc.Batch(1) break except: error_msg = '\n'.join(e.split("\n")[:15]) os.startfile(arg1, "open") ans = idaapi.askyn_c(1, """HIDECANCEL\nNASM failed to assemble [f_%08x.o] file. You can manually edit and NASM this file [f_%08x.asm] and click Yes when you're done. File is located in directory where your IDB is located. If you want to skip this function press No. Nasm output: %s""" % (function_ea, function_ea, error_msg)) if ans == 1: continue else: os.chdir(orig_dir) idc.Batch(1) return None os.chdir(orig_dir) print ">>>Writing function [%08x] @ [%08x]" % (function_ea, write_ea) data = fop.read() data_len = len(data) for offset in xrange(0, data_len): idc.PatchByte(write_ea+offset, ord(data[offset])) fop.close() idc.MakeCode(write_ea) fp = open("%s\\f_%08x.lst" % (dir, function_ea), "r") asm_lst = fp.read() base_addr = re.search(r"ORG ([\dABCDEF]+)H", asm_lst).group(1) base_addr = int(base_addr, 16) for jt in self.jmp_table_refs: m = re.search(r"\s*\d+\s+([\dABCDEF]{8}).*?%s" % re.escape(jt), asm_lst, re.IGNORECASE) if m != None: jt_ea = int(m.group(1), 16) jt_str = re.search(r"SJ_.{8}", jt, re.IGNORECASE).group() for m in re.findall(r"(?i)\n\s*\d+\s+[\dABCDEF]{8}\s+.*?\s+%s" % re.escape(jt_str), asm_lst): r = re.search(r"\d+\s([\dABCDEF]{8})", m.strip(), re.IGNORECASE).group(1) #print "AddCodeXref(0x%08x, 0x%08x, idc.XREF_USER)" % (jt_ea+base_addr, idc.Dword(int(r, 16)+base_addr)) idc.AddCodeXref(jt_ea+base_addr, idc.Dword(int(r, 16)+base_addr), idc.XREF_USER) else: raise MiscError for line in asm_lst.split("\n"): comment = re.search(r"###(.*?)###", line) if comment != None: data = re.search(r"\s*\d+\s([\dABCDEF]+)\s([\dABCDEF\(\)]+)", line) if data != None: offset = int(data.group(1), 16) idc.MakeComm(write_ea+offset, comment.group(1)) fp.close() return write_ea + data_len + 10
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) d = zlib.compress(pickle.dumps(var)) s.send(d) s.close() return None except Exception, e: return str(e) idaapi.info("Please run the Hiew-Names-Server script and press OK") idaapi.show_wait_box("Gathering and sending names to %s:%d" % (HOST, PORT)) info = [] for ea, name in idautils.Names(): offs = idaapi.get_fileregion_offset(ea) if offs == idaapi.BADADDR: continue is_func = False if idaapi.get_func(ea) is None else True info.append((offs, name, is_func)) ok = pickle_sendz(HOST, PORT, info) idaapi.hide_wait_box() if ok is not None: idaapi.warning("Failed to send names:\n" + ok) else: idaapi.info("Names successfully transfered!")
buf = f.strPatch.value # Hex values, unlike string literal, needs additional processing if f.rHex.selected: buf = buf.replace(' ','') # remove spaces buf = buf.replace('\\x','') # remove '\x' prefixes buf = buf.replace('0x','') # remove '0x' prefixes try: buf = binascii.unhexlify(buf) # convert to bytes except Exception, e: idaapi.warning("Invalid input: %s" % e) f.Free() return if not len(buf): idaapi.warning("There was nothing to import.") return # Trim to selection if needed: if f.cSize.checked: buf_size = end_ea - start_ea buf = buf[0:buf_size] # 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