def ask_file(self, filename, caption, filter="", save=False): """Open/save file dialog""" if not save: # Open file dialog self.ret = ida_kernwin.ask_file(0, os.path.basename(str(filename)), str(caption)) else: # Save file dialog if filename[0] == ".": # Remove leading dot from section names filename = filename[1:] self.ret = ida_kernwin.ask_file(1, os.path.basename(str(filename)), str(caption)) return self.ret
def main(): path = ida_kernwin.ask_file(0, '*.*', 'Select a dumped IAT file.') if not path: return for line in open(path, 'r'): line = line.replace('`', '') # take out ' if exists # parse an address if re.match('^[0-9a-f]{8} ', line): # 32bit addr = line[0:9] symbol = line[19:] bytewise = 4 optype = ida_bytes.FF_DWORD elif re.match('^[0-9a-f]{16} ', line): # 64bit addr = line[0:17] symbol = line[27:] bytewise = 8 optype = ida_bytes.FF_DWORD else: continue if re.match('^.+!.+$', symbol) is None: continue addr = int(addr, 16) _, api = symbol.rstrip().split('!') # only needs a function name # Remove garbage to make IDA understand API's signature # Discard after space (source code path) api = api.split(' ')[0] # Fix for ExitProcess often gets a wrong name if api.endswith('FSPErrorMessages::CMessageMapper::StaticCleanup+0xc'): api = api.replace( 'FSPErrorMessages::CMessageMapper::StaticCleanup+0xc', 'ExitProcess') # Fix for kernelbase.dll related stub functions if api.endswith('Implementation'): api = api.replace('Implementation', '') elif api.endswith('Stub'): api = api.replace('Stub', '') # IDA does not like + api = api.replace('+', '_') print(hex(addr), api) # Set a data type on the IDB ida_bytes.del_items(addr, bytewise, ida_bytes.DELIT_EXPAND) ida_bytes.create_data(addr, optype, bytewise, 0) if idc.set_name(addr, api, SN_CHECK | SN_NOWARN) == 1: continue # Try to name it as <name>_N up to _99 for i in range(100): if idc.set_name(addr, api + '_' + str(i), SN_CHECK | SN_NOWARN) == 1: break if i == 99: idc.set_name(addr, api, SN_CHECK) # Display an error message print( 'Load an appropriate FLIRT signature if it is not applied yet.\n' 'Then, use [Options] > [General] > [Analysis] > [Reanalyze program] to' ' reflect those API signatures.')
def activate(self, ctx): fname = ida_kernwin.ask_file(1, '*.riz', 'Save signature file as') if fname: if '.' not in fname: fname += ".riz" RizzoBuild(fname) return 0
def run(self, arg): file = ida_kernwin.ask_file(0, "*.txt", "Load IAT") idaapi.msg(f"{file} Selected!\n") if file == None: idaapi.msg("Please select a file!") labeled_iat_dump_file_name = self.parse_iat(file) self.apply_iat(labeled_iat_dump_file_name)
def extract_binary(li, name, offset, size): name = ida_kernwin.ask_file(True, decode(name), decode(b"Please enter a file name")) if name: with open(name, "wb") as f: li.seek(offset) f.write(li.read(size))
def activate(self, ctx): import json filepath = ida_kernwin.ask_file(False, "*.zmu;*.overlay;*", "Load Zelos Overlay...") if filepath is None: return f = open(filepath, "r") zelos_data = f.read() f.close() zelos_data = zelos_data[len("DISAS\n"):] zelos_dump = json.loads(zelos_data) # Apply the overlay data for comment in zelos_dump["comments"]: ea = comment["address"] try: comment_text = str(comment["text"]) except UnicodeEncodeError: comment_text = "" color = comment.get("color", 0x73F0DF) # Set color of instruction line idaapi.set_item_color(ea, color) idaapi.set_cmt(ea, comment_text, False) # Set function name if not already changed idc.get_func_attr(ea, idc.FUNCATTR_START) name = idc.get_func_name(ea) if len(name) > 0 and name.startswith("zmu_") is False: idc.set_name(ea, "zmu_" + name) return 1
def export(): path = kw.ask_file(1, '*.txt', 'Save to') if not path: print('Cancelled') return with open(path, 'a') as fp: classdump = ClassDump(output=fp) classdump.parse()
def activate(self, ctx): filename = ida_kernwin.ask_file(True, '*.json', 'Export IDA-Sync JSON file') if filename is not None: print('[IDA-Sync] Exporting %s...' % filename) j = {item.KEY: item.dump() for item in items} with open(filename, 'w') as file: json.dump(j, file, indent=2, sort_keys=True, separators=(',', ': ')) print('[IDA-Sync] Done') return 1
def load_methods(): sigfile = ida_kernwin.ask_file(0, "*.json", "Select json signature file") log("loading signature file: %s", sigfile) with open(sigfile, 'r') as f: infos = json.load(f) log("loaded %d methods from JSON", len(infos)) return infos
def main(): path = ida_kernwin.ask_file(False, "*", "capa report") if not path: return 0 with open(path, "rb") as f: doc = json.loads(f.read().decode("utf-8")) if "meta" not in doc or "rules" not in doc: logger.error("doesn't appear to be a capa report") return -1 # in IDA 7.4, the MD5 hash may be truncated, for example: # wanted: 84882c9d43e23d63b82004fae74ebb61 # found: b'84882C9D43E23D63B82004FAE74EBB6\x00' # # see: https://github.com/idapython/bin/issues/11 a = doc["meta"]["sample"]["md5"].lower() b = idautils.GetInputFileMD5().decode("ascii").lower().rstrip("\x00") if not a.startswith(b): logger.error("sample mismatch") return -2 rows = [] for rule in doc["rules"].values(): if rule["meta"].get("lib"): continue if rule["meta"].get("capa/subscope"): continue if rule["meta"]["scope"] != "function": continue name = rule["meta"]["name"] ns = rule["meta"].get("namespace", "") for va in rule["matches"].keys(): va = int(va) rows.append((ns, name, va)) # order by (namespace, name) so that like things show up together rows = sorted(rows) for ns, name, va in rows: if ns: cmt = "%s (%s)" % (name, ns) else: cmt = "%s" % (name, ) logger.info("0x%x: %s", va, cmt) try: # message will look something like: # # capa: delete service (host-interaction/service/delete) append_func_cmt(va, "capa: " + cmt, repeatable=False) except ValueError: continue logger.info("ok")
def _parse_exe_file(): input_file_path = ida_kernwin.ask_file(False, idc.get_input_file_path(), 'Input file') parsed_file = tdinfo_structs.DOS_MZ_EXE_STRUCT.parse_file(input_file_path) print('Borland TLink symbolic information version: {}.{}'.format( parsed_file.tdinfo_header.major_version, parsed_file.tdinfo_header.minor_version)) return parsed_file
def activate(self, ctx): filename = ida_kernwin.ask_file(False, '*.json', 'Import IDA-Sync JSON file') if filename is not None: print('[IDA-Sync] Importing %s...' % filename) with open(filename) as f: j = json.load(f, object_hook=convert_name_str) for item in items: item.load(j.get(item.KEY, [])) print('[IDA-Sync] Done') return 1
def activate(self, ctx): user_input = ida_kernwin.ask_yn( ida_kernwin.ASKBTN_YES, "Would you like to export all functions?") if user_input == ida_kernwin.ASKBTN_CANCEL: return 1 output_file_name_hint = "" p = anvill.get_program() if user_input == ida_kernwin.ASKBTN_NO: screen_cursor = ida_kernwin.get_screen_ea() function_name = ida_funcs.get_func_name(screen_cursor) if function_name is None: print("anvill: The cursor is not located inside a function") return 1 output_file_name_hint = function_name + ".json" try: p.add_function_definition(screen_cursor) except: print( "anvill: Failed to process the function at address {0:x}". format(screen_cursor)) return 1 else: function_address_list = idautils.Functions() for function_address in function_address_list: try: p.add_function_definition(function_address) except: print( "anvill: Failed to process the function at address {0:x}" .format(function_address)) output_file_name_hint = "program.json" output_path = ida_kernwin.ask_file( True, output_file_name_hint, "Select where to save the spec file") if not output_path: return 1 output = json.dumps(p.proto(), sort_keys=False, indent=2) print("anvill: Saving the spec file to {}".format(output_path)) with open(output_path, "w") as f: f.write(output)
def activate(self, ctx): addr = ida_kernwin.askaddr(0, "Target address") if addr == BADADDR: print('[Export-Xref] Bad address given') return 1 filename = ida_kernwin.ask_file(True, '*', 'Export Xrefs to...') if filename is None: return 1 print('[Export-Xref] Exporting %s...' % filename) with open(filename, 'w') as f: for x in XrefsTo(addr, 0): print("0x%08x," % x.frm, file=f) print('[Export-Xref] Done') return 1
def run(self, arg): if self.view: self.Close() fn = ida_kernwin.ask_file(0, "*.asm", "Select ASM file to view") if not fn: return self.view = asmview_t() if not self.view.Create(fn): return self.view.Show() widget = self.view.GetWidget() # Attach actions to this widget's popup menu ida_kernwin.attach_action_to_popup(widget, None, ACTNAME_REFRESH) ida_kernwin.attach_action_to_popup(widget, None, ACTNAME_CLOSE)
def activate(self, ctx): importer = OffsetsImporter() print('FakePDB/import offsets:') f = ida_kernwin.ask_file(False, "*.json", "Select the file to load") if f and os.path.exists(f): importer.process_json(f) print(' * finished') else: print(' * canceled') print('') return 1
def run(self, arg): s = """Memory Dumper Enter the memory region: begin: <:n::12::> size: <:n::12::> (optional, fill it to ignore the end address) or end: <:n::12::> """ currea = idaapi.get_screen_ea() begin = idaapi.Form.NumericArgument('N', currea) size = idaapi.Form.NumericArgument('N', 0x0) end = idaapi.Form.NumericArgument('N', 0x0) ok = idaapi.ask_form(s, begin.arg, size.arg, end.arg) if ok == 1: print("Begin dump") if size.value == 0: if end.value <= begin.value: idaapi.warning("Incorrect Address!") return else: dumpsize = end.value - begin.value else: dumpsize = size.value print("begin: 0x%x, end: 0x%x" % (begin.value, begin.value + dumpsize)) path = ida_kernwin.ask_file(True, "*", "Save dump to?") if not path: return print("path: %s" % path) if idc.savefile(path, 0, begin.value, dumpsize) is not 0: idaapi.info("Save successed!") else: idaapi.warning("Failed to save dump file!")
def do_export(): db = {} module = idaapi.get_root_filename().lower() base = idaapi.get_imagebase() file = ida_kernwin.ask_file(1, "x64dbg database|{}".format(get_file_mask()), "Export database") if not file: return print("Exporting database {}".format(file)) db["labels"] = [{ "text": name, "manual": False, "module": module, "address": "{:#x}".format(ea - base) } for (ea, name) in idautils.Names()] print("{:d} label(s) exported".format(len(db["labels"]))) db["comments"] = [{ "text": comment.replace("{", "{{").replace("}", "}}"), "manual": False, "module": module, "address": "{:#x}".format((ea - base)) } for (ea, comment) in Comments()] print("{:d} comment(s) exported".format(len(db["comments"]))) db["breakpoints"] = [{ "address": "{:#x}".format(ea - base), "enabled": True, "type": bptype, "titantype": "{:#x}".format(titantype), "oldbytes": "{:#x}".format(oldbytes), "module": module, } for (ea, bptype, titantype, oldbytes) in Breakpoints()] print("{:d} breakpoint(s) exported".format(len(db["breakpoints"]))) with open(file, "w") as outfile: json.dump(db, outfile, indent=1) print("Done!")
def main(): path = ida_kernwin.ask_file(False, "*", "file to load") if not path: return with open(path, "rb") as f: buf = tuple(f.read()) if len(buf) == 0: print("empty file, cancelling") return size = idawilli.align(len(buf), 0x1000) print("size: 0x%x" % (len(buf))) print("aligned size: 0x%x" % (size)) addr = idawilli.dbg.allocate_rwx(size) print("allocated 0x%x bytes at 0x%x" % (size, addr)) idawilli.dbg.patch_bytes(addr, buf) print("patched file to 0x%x" % (addr)) print("ok")
def main(): out_file_name = ida_kernwin.ask_file(True, 'basicblocks.bb', 'Select output file') print('Will save to %s' % out_file_name) if os.path.isfile(out_file_name): # validate existing file before appending to it with open(out_file_name, 'r') as f: for line in f: if line.startswith('[') and module_name in line: warning('Module %s already exists in %s' % (module_name, os.path.basename(out_file_name))) return with open(out_file_name, 'a') as f: f.write('[%s]\n' % (module_name, )) for fva in idautils.Functions(): dump_bbs(fva, f) f.close() print('OK, done. Found %d basic blocks' % (len(dumped), )) ida_kernwin.info('Saved to %s' % (out_file_name, ))
def main(): path = ida_kernwin.ask_file(False, "*", "file to load") if not path: return with open(path, "rb") as f: buf = tuple(map(ord, f.read())) if len(buf) == 0: print("empty file, cancelling") return size = idawilli.align(len(buf), 0x1000) print("size: 0x%x" % (len(buf))) print("aligned size: 0x%x" % (size)) addr = ida_kernwin.ask_addr(idc.ScreenEA(), "location to write") if not addr: return idawilli.dbg.patch_bytes(addr, buf) print("ok")
def askfile(types, prompt): fname = ida_kernwin.ask_file(1, types, prompt) return ConfigHelpers.string_decode(fname)
for reg, val in index["regs"].items(): cmt += f"{reg.ljust(6)} : {hex(val)}\n" progctr = get_pc_by_arch(index) if progctr is None: raise ArchNotSupportedError( "Architecture not fully supported, skipping register status comment" ) ida_bytes.set_cmt(progctr, cmt, 0) ida_kernwin.jumpto(progctr) def main(filepath): """Main - parse _index.json input and map context files into the database :param filepath: Path to the _index.json file """ try: index = parse_mapping_index(filepath) context_dir = Path(filepath).parent rebase_program(index) create_segments(index, context_dir) write_reg_info(index) except ContextLoaderError as ex: print(ex) if __name__ == "__main__": main(ida_kernwin.ask_file(1, "*.json", "Import file name"))
__tablename__ = 'basic_blocks' id = Column(Integer, primary_key=True) offset = Column(Integer) reached = Column(Boolean) when = Column(Date) testcase = Column(String) def __init__(self, offset, reached, when, testcase): 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
def load_jni_header(): jni_h = ida_kernwin.ask_file(0, "*.h", "Select JNI header file") idaapi.idc_parse_types(jni_h, idc.PT_FILE)
import ida_ua import ida_bytes import ida_funcs import ida_kernwin from ida_idaapi import BADADDR def read_addrs(file): lines = [] with open(file, "r") as f: lines = f.readlines() for l in lines: yield int(l.strip(), 16) pto_file = ida_kernwin.ask_file(0, "*.fad", "Choose a function address file") for addr in read_addrs(pto_file): ida_ua.create_insn(addr) ida_funcs.add_func(addr, BADADDR) ptr_file = ida_kernwin.ask_file(0, "*.fpt", "Choose a function pointer file") for addr in read_addrs(ptr_file): ida_bytes.create_dword(addr, 4)
def run(self, arg): yara_file = ida_kernwin.ask_file(0, "*.yara", 'Choose Yara File...') if yara_file == None: print("ERROR: You must choose a yara file to scan with") else: self.search(yara_file)
def AskFile(for_saving, mask, prompt): return ida_kernwin.ask_file(for_saving, mask, prompt)
import os import ida_segment import ida_kernwin import ida_name filename = ida_kernwin.ask_file(0, "", "FILTER *.MAP\nSelect MAP file") if filename is not None and os.path.isfile(filename): real_base = {} map_base = {} real_base['DGROUP'] = ida_segment.get_segm_by_name("DATA").start_ea real_base['IGROUP'] = ida_segment.get_segm_by_name("TEXT").start_ea with open(filename, "r") as f: data = f.read().split('\n') insection = None for line in data: if line.strip() == 'Origin Group': insection = "groups" elif line.strip() == 'Address Publics by Value': insection = "publics_" elif line.strip() == '' and insection == "publics_": insection = "publics" elif line.strip() == '': insection = None else: if insection == "groups": (addr, name) = line.strip().split(' ')
from ida_kernwin import ask_file from idaapi import require require('ida_utils') path = ask_file(False, '*.like.json', 'build-vmlinux output') if path is not None: ida_utils.apply_like(path) # noqa: F821