def main(): if len(idc.ARGV) < 2: print("importLister.py <output_file> \n List in the <output_file> the imports of the exe passed to idaPython ") idc.Exit(-1) outputFile = idc.ARGV[1] print("output File "+outputFile) outputF = open(outputFile,"w") nimps = idaapi.get_import_module_qty() print("Found %d import(s)..." % nimps) print(nimps) for i in xrange(0, nimps): name = idaapi.get_import_module_name(i) if not name: print("Failed to get import module name for #%d" % i) continue print("count "+ str(i) +" " + name) idaapi.enum_import_names(i, imp_cb) for imp in imports: outputF.write(str(imp)+"\n") print("All done...") outputF.close()
def main(): if len(idc.ARGV) < 2: print( "importLister.py <output_file> \n List in the <output_file> the imports of the exe passed to idaPython " ) idc.Exit(-1) outputFile = idc.ARGV[1] print("output File " + outputFile) outputF = open(outputFile, "w") nimps = idaapi.get_import_module_qty() print("Found %d import(s)..." % nimps) print(nimps) for i in xrange(0, nimps): name = idaapi.get_import_module_name(i) if not name: print("Failed to get import module name for #%d" % i) continue print("count " + str(i) + " " + name) idaapi.enum_import_names(i, imp_cb) for imp in imports: outputF.write(str(imp) + "\n") print("All done...") outputF.close()
def ToggleBreakpoints(): global bpflag, codeflag, checked, bannedList print "\nRunning banned_functions.py - One moment..." for i in xrange(0, idaapi.get_import_module_qty()): name = idaapi.get_import_module_name(i) idaapi.enum_import_names(i, iatCallback) if codeflag == 0 and checked != []: print "\n=> This PE/COFF program uses an intermediary jmp to IAT." elif codeflag == 1 and checked != []: print "\n=> This PE/COFF program calls direct to IAT." elif codeflag == 2 and checked != []: print "\n=> Looks like an ELF file. CS => PLT => *GOT." else: print "" print "=> The following banned functions were found:\n " for item in checked: if item in bannedList: print "=> %s" % item if bpflag == 0 and codeflag == 1: print "\nFinished! Breakpoints deleted. Run again to add." elif bpflag == 1 and codeflag <= 1: print "\nFinished! Breakpoints added. Run again to delete." elif bpflag == 0 and codeflag == 0: if not checked: print "\nNo banned functions found!" else: print "\n"
def getImportTableData(self): """ Update rt_import_table with current import table data. """ def imp_cb(ea, name, ord): """ Import enumeration callback function. used by idaapi.enum_import_names . """ tmpImports.append([self.current_module_name, ea, name, ord]) return True tmpImports = [ ] # Contains static import table data (w\o real function addresses) imp_num = idaapi.get_import_module_qty() # Number of imported modules for i in xrange(0, imp_num): self.current_module_name = idaapi.get_import_module_name(i).lower() idaapi.enum_import_names(i, imp_cb) # Get runtime function addresses and store in self.rt_import_table if not idaapi.is_debugger_on(): raise RuntimeError("Debugger is not currently active.") for module_name, ea, name, ord in tmpImports: func_real_adrs = get_adrs_mem(ea) self.rt_import_table[func_real_adrs] = (module_name, ea, name, ord)
def find_imported_subroutines(): """Find the address of all imported functions.""" # Collect addresses of imported code. imported_eas = set() num_imports = idaapi.get_import_module_qty() for i in xrange(num_imports): idaapi.enum_import_names(i, lambda ea, name, ord: imported_eas.add(ea)) # Mark IDA-identified stuff imported stuff as imported. for ea in imported_eas: if not program.has_subroutine(ea): log.error("No subroutine associated with import {:08x}.".format(ea)) continue sub = program.get_subroutine(ea) sub.visibility = program.Subroutine.VISIBILITY_IMPORTED # Mark functions in code sections marked as external as being imported. for sub in program.subroutines(): if program.Subroutine.VISIBILITY_INTERNAL != sub.visibility: continue if has_segment_type(sub.ea, idc.SEG_XTRN): log.debug("Subroutine {:08x} is imported".format(sub.ea)) sub.visibility = program.Subroutine.VISIBILITY_IMPORTED if sub.name: log.info("Found imported subroutine {} at {:08x}".format( sub.name, sub.ea))
def get_file_imports(): """get file imports""" imports = {} for idx in range(idaapi.get_import_module_qty()): library = idaapi.get_import_module_name(idx) if not library: continue # IDA uses section names for the library of ELF imports, like ".dynsym" library = library.lstrip(".") def inspect_import(ea, function, ordinal): if function and function.startswith("__imp_"): # handle mangled PE imports function = function[len("__imp_"):] if function and "@@" in function: # handle mangled ELF imports, like "fopen@@glibc_2.2.5" function, _, _ = function.partition("@@") imports[ea] = (library.lower(), function, ordinal) return True idaapi.enum_import_names(idx, inspect_import) return imports
def getApiMap(self): self._api_map = {} num_imports = idaapi.get_import_module_qty() for i in range(0, num_imports): self._import_module_name = idaapi.get_import_module_name(i) idaapi.enum_import_names(i, self._cbEnumImports) return self._api_map
def find_imported_subroutines(): """Find the address of all imported functions.""" # Collect addresses of imported code. imported_eas = set() num_imports = idaapi.get_import_module_qty() for i in xrange(num_imports): idaapi.enum_import_names(i, lambda ea, name, ord: imported_eas.add(ea)) # Mark IDA-identified stuff imported stuff as imported. for ea in imported_eas: if not program.has_subroutine(ea): log.error( "No subroutine associated with import {:08x}.".format(ea)) continue sub = program.get_subroutine(ea) sub.visibility = program.Subroutine.VISIBILITY_IMPORTED # Mark functions in code sections marked as external as being imported. for sub in program.subroutines(): if program.Subroutine.VISIBILITY_INTERNAL != sub.visibility: continue if has_segment_type(sub.ea, idc.SEG_XTRN): log.debug("Subroutine {:08x} is imported".format(sub.ea)) sub.visibility = program.Subroutine.VISIBILITY_IMPORTED if sub.name: log.info("Found imported subroutine {} at {:08x}".format( sub.name, sub.ea))
def get_imports(): ''' enumerate the imports of the currently loaded module. Yields: Tuple[int, str, str, int]: - address of import table pointer - name of imported library - name of imported function - ordinal of import ''' for i in range(idaapi.get_import_module_qty()): dllname = idaapi.get_import_module_name(i) if not dllname: continue entries = [] def cb(ea, name, ordinal): entries.append((ea, name, ordinal)) return True # continue enumeration idaapi.enum_import_names(i, cb) for ea, name, ordinal in entries: yield ea, dllname, name, ordinal
def get_specify_import_modules_info(local_module_list): module_info_list = list() number_of_import_modules = idaapi.get_import_module_qty() for i in xrange(0, number_of_import_modules): print(i) module_info = dict() module_name = idaapi.get_import_module_name(i) print(module_name) if module_name in local_module_list: print("local module: %s" %(module_name)) module_info["index"] = i module_info["name"] = module_name print(module_info) module_info_list.append(module_info) print(module_info_list) return module_info_list
def getDllApiInfo(root_path): with open(root_path + 'dll.json', 'w') as f: # total dll count dll_num = idaapi.get_import_module_qty() dll_list = dict() for i in range(dll_num): # get dll name dll_name = idaapi.get_import_module_name(i) if not dll_name: continue dll_list[dll_name] = [] # get api function of each dll name def imp_cb(ea, name, ord): if not name: dll_list[dll_name].append("error") else: dll_list[dll_name].append(name) return True idaapi.enum_import_names(i, imp_cb) #return json format json.dump(dll_list, f)
def __get_image_iat(self): import_module_num = idaapi.get_import_module_qty() for index in range(import_module_num): module_name = idaapi.get_import_module_name(index) self.module_iat_dict[module_name] = {} self.last_iat_module_name = module_name idaapi.enum_import_names(index, self.__enum_import_func_cb)
def get_imports(library_calls): """ Populate dictionaries with import information. Return imported modules. """ import_modules = [] import_names_callback = make_import_names_callback(library_calls) for i in xrange(0, idaapi.get_import_module_qty()): import_modules.append(idaapi.get_import_module_name(i)) idaapi.enum_import_names(i, import_names_callback) return import_modules
def get_imports(): imports = {} nimps = idaapi.get_import_module_qty() for i in range(0, nimps): name = idaapi.get_import_module_name(i) imp_cb = functools.partial(ConfigHelpers.add_imp_to_dict, imports, name) idaapi.enum_import_names(i, imp_cb) return imports
def __init__(self): #strongly inspired by ex_imports.py in IDAPython examples self.imports_by_name = {} self.imports_by_addr = {} nimps = idaapi.get_import_module_qty() for i in xrange(0, nimps): name = idaapi.get_import_module_name(i) idaapi.enum_import_names(i, functools.partial(self._add_import, name))
def _loadImports(self) -> None: """Enumerates imported functions with the help of IDA API and adds them to the internal sets. """ self._importsSet = set() self._importNamesSet = set() nimps = idaapi.get_import_module_qty() for i in range(0, nimps): idaapi.enum_import_names(i, self.imports_names_callback)
def GetAllImportEntries(): for i in xrange(0, idaapi.get_import_module_qty()): name = idaapi.get_import_module_name(i) if not name: pass idaapi.enum_import_names(i, EnumImportNamesCallback) return imports_list
def get_header_data(self): self.imports = [] #: Types we have already inspected self.seen = set() #: List of structures, to patch .h later self.structs = set() # add missing #defines self.imports.append("#define __cdecl") nimps = idaapi.get_import_module_qty() for ordinal in range(0, nimps): idaapi.enum_import_names(ordinal, self.imp_cb) # Fix local types by iterating until all types are defined while self.add_types() > 0: pass class str_sink(idaapi.text_sink_t): """ Sink to get .h in a string """ def __init__(self): idaapi.text_sink_t.__init__(self) self.text = "" def _print(self, defstr): self.text += defstr return 0 def res(self): return self.text sink = str_sink() idaapi.print_decls( sink, idaapi.cvar.idati, [], idaapi.PDF_INCL_DEPS | idaapi.PDF_DEF_FWD | idaapi.PDF_DEF_BASE) # Generate fixed .h res = sink.res() for s in self.structs: if "struct " not in s: search = r"(^\s*(?:typedef )?)\b%s\b" % re.escape(s) res = re.sub(search, r"\1struct %s" % s, res, flags=re.MULTILINE) res += "\n\n" + "\n".join(self.imports) res = re.sub(r"__attribute__.*? ", " ", res) res = res.replace("$", "D_") res = res.replace("::", "__") return res
def ImportedFuncs(): nimps = idaapi.get_import_module_qty() #print "Found %d import(s)..." % nimps for i in xrange(0, nimps): name = idaapi.get_import_module_name(i) if not name: #print "Failed to get import module name for #%d" % i continue #print "Walking-> %s" % name idaapi.enum_import_names(i, imp_cb) return sorted(IMPORTED)
def handleBuildImport(self): nimps = get_import_module_qty() self.imports = [] for i in xrange(0, nimps): self.currentModuleName = get_import_module_name(i) if not self.currentModuleName: continue enum_import_names(i, self.imports_names_cb)
def imports(): """Iterator containing (ea,(module,name,ordinal)) of imports in database""" for idx,module in ((i,idaapi.get_import_module_name(i)) for i in xrange(idaapi.get_import_module_qty())): result = [] def fn(ea,name,ordinal): result.append( (ea,(name,ordinal)) ) return True idaapi.enum_import_names(idx,fn) for ea,(name,ordinal) in result: yield ea,(module,name,ordinal) continue return
def find_imported_functions(cfg, exclude_blocks): # Try to pattern-match an imported function against an ELF GOT/PLT entry. # # Example: # malloc@plt: # 0x402640 <+0>: jmp QWORD PTR [rip+0x217c22] # 0x61a268 <*****@*****.**> # 0x402646 <+6>: push 0x4a # 0x40264b <+11>: jmp 0x402190 # # Produces: # plt_offset = 0x402646 <-- what we get in IDA. # got_entry_ea = 0x61a268 # plt_jmp_ea = 0x402640 def visit_elf_import(plt_offset, name): exclude_blocks.add(plt_offset) ea = 0 for got_entry_ea in idautils.DataRefsTo(plt_offset): seg_name = idc.SegName(got_entry_ea) if ".got.plt" == seg_name: for plt_jmp_ea in idautils.DataRefsTo(got_entry_ea): if ".plt" != idc.SegName(plt_jmp_ea): continue plt_jmp = idautils.DecodeInstruction(plt_jmp_ea) if plt_jmp and "jmp" == plt_jmp.get_canon_mnem(): ea = plt_jmp_ea elif ".got" == seg_name: #assert idaapi.is_weak_name(plt_offset) pass if ea: func = cfg.functions.add() func.name = name func.address = ea func.is_imported = True func.is_exported = False func.is_weak = idaapi.is_weak_name(plt_offset) exclude_blocks.add(ea) debug("Found import:", name, "at", hex(ea)) else: debug("Didn't find import", name) # Visit an imported function name. def visit_import(ea, name, ord): visit_elf_import(ea, name) return True num_imports = idaapi.get_import_module_qty() for i in range(num_imports): idaapi.enum_import_names(i, visit_import)
def get_all_imports(self): # Note: this fx is courtesy of hexrays number_of_imports = idaapi.get_import_module_qty() for i in xrange(0, number_of_imports): name = idaapi.get_import_module_name(i) if not name: print("Failed to get import module name for #%d" % i) continue idaapi.enum_import_names(i, self.imports_callback) return
def buildImportDictionary(self): """Iterates over each of the import modules (dll's) and enumerates each of the APIs imported from them. enum_import_names implements a visitor pattern which passes each imported API name and it's EA in the import table to imp_cb above.""" nimps = idaapi.get_import_module_qty() for i in xrange(0, nimps): self.curr_mod_name = idaapi.get_import_module_name(i) if not self.curr_mod_name: continue idaapi.enum_import_names(i, self.imp_cb)
def get_block_call(): # we tranverse import table and finally get two functions, which exists in libSystem.B.dylib global globalblock_set, stackblock_set nimps = idaapi.get_import_module_qty() for i in xrange(0, nimps): name = idaapi.get_import_module_name(i) if name.find("libSystem.B.dylib") != -1: idaapi.enum_import_names(i, imp_cb) break # then we find all xref to these two functions if globalblock_addr != 0: find_xref(globalblock_addr, globalblock_set, ["__const"]) if stackblock_addr != 0: find_xref(stackblock_addr, stackblock_set, ["__text"])
def compute_imports(self): imports = {} current = "" def callback(ea, name, ord): imports[current].append((ea, name, ord)) return True nimps = idaapi.get_import_module_qty() for i in xrange(0, nimps): current = idaapi.get_import_module_name(i) imports[current] = [] idaapi.enum_import_names(i, callback) return imports
def make_api_dic(self): def get_api_list(ea, name, ord): self.api_dic[ea] = name # print ea, name return True import_number = idaapi.get_import_module_qty() print("--- Number of Import Modules:" + str(import_number)) for i in range(0, import_number): idaapi.enum_import_names(i, get_api_list) print("--- Number of APIs:" + str(len(self.api_dic)))
def get_typed_imports(): """Queries IDA for functions in the import table that do have a type. Returns a set of (func_ea, func_type) tuples.""" imp_funcs = set() def imp_cb(ea, name, ordn): ftype = idc.GetType(ea) if ftype: imp_funcs.add((ea, ftype)) return True for i in xrange(idaapi.get_import_module_qty()): idaapi.enum_import_names(i, imp_cb) return imp_funcs
def get_imports(dll): def imp_cb(ea, name, ord): imports[name] = ea return True imports = {} nimps = idaapi.get_import_module_qty() for i in xrange(0, nimps): name = idaapi.get_import_module_name(i) if stricmp(name, dll): continue idaapi.enum_import_names(i, imp_cb) break return imports
def find_imported_funcs(from_module): def imp_cb(ea, name, ord): if not name: raise Exception("Import by ordinal unsupported for now") imports.append(name) return True imports = [] nimps = idaapi.get_import_module_qty() for i in xrange(0, nimps): modname = idaapi.get_import_module_name(i).lower() if modname == from_module: idaapi.enum_import_names(i, imp_cb) return imports
def get_dll_api(f1): nimps = idaapi.get_import_module_qty() global fg fg = open(gpus + "\\api.txt", "w") #print "Found %d import(s)..." % nimps for i in xrange(0, nimps): name = idaapi.get_import_module_name(i) if not name: #print "Failed to get import module name for #%d" % i continue f1.write(name + '\n') idaapi.enum_import_names(i, imp_cb) #imp_cb是由enum_import_names回调的规定的函数,有规定的参数和返回值
def find_imported_funcs(dllname): def imp_cb(ea, name, ord): if not name: name = '' imports.append([ea, name, ord]) return True imports = [] nimps = idaapi.get_import_module_qty() for i in xrange(0, nimps): name = idaapi.get_import_module_name(i) if re.match(dllname, name, re.IGNORECASE) is None: continue idaapi.enum_import_names(i, imp_cb) return imports
def iter_module(self): """ Iterate the import libraries to locate a specific import library and obtain the api addresses using the callback func. If the api_names are targeted and they were not obtained using idaapi.enum_import_names then attempt to obtain the targeted apis by function name. :return: """ num_imports = idaapi.get_import_module_qty() for i in xrange(0, num_imports): name = idaapi.get_import_module_name(i) if name == self.module_name: idaapi.enum_import_names(i, self._callback_func) if self.targeted and self.target_api_names: self._obtain_targeted_apis_by_name(self.target_api_names) self._processed = True
def BuildImports(self): print "BuildImports" tree = {} nimps = idaapi.get_import_module_qty() for i in xrange(0, nimps): name = idaapi.get_import_module_name(i) if not name: continue # Create a list for imported names self.items = [] # Enum imported entries in this module idaapi.enum_import_names(i, self.imports_names_cb) if name not in tree: tree[name] = [] tree[name].extend(self.items) return tree
def find_imported_funcs(): def imp_cb(ea, name, ord): if not name: raise Exception("Import by ordinal unsupported for now") imports[modname].append(name) return True imports = {} modname = "" nimps = idaapi.get_import_module_qty() for i in xrange(0, nimps): modname = idaapi.get_import_module_name(i) imports[modname] = [] idaapi.enum_import_names(i, imp_cb) return imports
def collect_imports_data(self): """ Modules and their functions. """ self._imported_modules = [] nimps = idaapi.get_import_module_qty() # number of imports for i in xrange(0, nimps): name = idaapi.get_import_module_name(i) if not name: print ("REDB: Failed to get_current_from_ini_file import" + "module name for #%d" % i) continue module = _ImportModule(name) self._imported_modules.append(module) idaapi.enum_import_names(i, self._add_single_imported_function) return self._imported_modules
def main(): print "AAAAAAAAAAAAAAAAAAAAA" loadInitFunc() nimps = idaapi.get_import_module_qty() print "Found %d import(s)..." % nimps for i in xrange(0, nimps): name = idaapi.get_import_module_name(i) if not name: print "Failed to get import module name for #%d" % i continue idaapi.enum_import_names(i, imp_cb) print "All done..." outputF.close()
def _build_imports(self): '''Build imports table. (Was taken from examples.)''' tree = {} nimps = idaapi.get_import_module_qty() for i in xrange(0, nimps): name = idaapi.get_import_module_name(i) if not name: continue # Create a list for imported names self.tmp_items = [] # Enum imported entries in this module idaapi.enum_import_names(i, self._imports_names_cb) if name not in tree: tree[name] = [] tree[name].extend(self.tmp_items) return tree
def numImports(self): return idaapi.get_import_module_qty()
# ----------------------------------------------------------------------- # This is an example illustrating how to enumerate imports # (c) Hex-Rays # import idaapi def imp_cb(ea, name, ord): if not name: print "%08x: ord#%d" % (ea, ord) else: print "%08x: %s (ord#%d)" % (ea, name, ord) # True -> Continue enumeration # False -> Stop enumeration return True nimps = idaapi.get_import_module_qty() print "Found %d import(s)..." % nimps for i in xrange(0, nimps): name = idaapi.get_import_module_name(i) if not name: print "Failed to get import module name for #%d" % i continue print "Walking-> %s" % name idaapi.enum_import_names(i, imp_cb) print "All done..."
def get_imports(library_calls, library_addr): """ Populate dictionaries with import information. """ import_names_callback = make_import_names_callback(library_calls, library_addr) for i in xrange(0, idaapi.get_import_module_qty()): idaapi.enum_import_names(i, import_names_callback)
def getImportModules(): return [idaapi.get_import_module_name(i) for i in xrange(idaapi.get_import_module_qty())]