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 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 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 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 getImports(modulename): idx = [x.lower() for x in getImportModules()].index(modulename.lower()) result = [] def fn(ea,name,ordinal): result.append((ea,(name,ordinal))) return True idaapi.enum_import_names(idx,fn) return result
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 __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 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 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 getImports(modulename): idx = [x.lower() for x in getImportModules()].index(modulename.lower()) result = [] def fn(ea, name, ordinal): result.append((ea, (name, ordinal))) return True idaapi.enum_import_names(idx, fn) return result
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 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 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 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 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 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_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 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_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 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 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 get_import_funcs(import_module_index): import_funcs_info = [] def imports_callback(ea, name, ord): import_funcs_info.append(('0x%x' % (ea), name)) set_import_function_color(ea) return True idaapi.enum_import_names(import_module_index, imports_callback) return import_funcs_info
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 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 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 find_import_functions(): def imports_names_cb(ea, name, ord): if name is not None: import_function_list.append([ea, name, ord]) # True -> Continue enumeration # False -> Stop enumeration return True import_function_list = [] nimps = idaapi.get_import_module_qty() for i in xrange(nimps): name = idaapi.get_import_module_name(i) idaapi.enum_import_names(i, imports_names_cb) return import_function_list
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 get_iat_data(self): """ Retrive data from IAT """ imp_num = idaapi.get_import_module_qty() # Number of imported modules for i in xrange(0, imp_num): name = idaapi.get_import_module_name(i).lower() if not name: #self.logger.error("Failed to get import module name for #%d", i) continue if not name in self.iat: self.iat[name] = [] self.current_module = self.iat[name] idaapi.enum_import_names(i, self.imp_cb)
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 get_imported_functions(): result = [] def imp_cb(ea, name, ord): result.append(ea) return True nimps = idaapi.get_import_module_qty() for i in xrange(nimps): name = idaapi.get_import_module_name(i) if name is None: print 'Failed to get import module name for #%i' % i continue idaapi.enum_import_names(i, imp_cb) return result
def driver_type(): implist = idaapi.get_import_module_qty() for i in range(0, implist): name = idaapi.get_import_module_name(i) idaapi.enum_import_names(i, cb) for name in names: if name == "FltRegisterFilter": return "Mini-Filter" elif name == "WdfVersionBind": return "WDF" elif name == "StreamClassRegisterMinidriver": return "Stream Minidriver" elif name == "KsCreateFilterFactory": return "AVStream" elif name == "PcRegisterSubdevice": return "PortCls" return "WDM"
def find_pool_tags(): """ Dirty hack around IDA's type information, find references to tag using functions then the comment marking the tag then add the function caller/tag to output dictionary. """ funcs = [ 'ExAllocatePoolWithTag', 'ExFreePoolWithTag', 'ExAllocatePoolWithTagPriority' ] tags = {} def imp_cb(ea, name, ord): if name in funcs: for xref in idautils.XrefsTo(ea): call_addr = xref.frm caller_name = idc.get_func_name(call_addr) prev = idc.prev_head(call_addr) for _ in range(10): if idc.get_cmt(prev, 0) == 'Tag' and idc.get_operand_type( prev, 1) == 5: tag_raw = idc.get_operand_value(prev, 1) tag = '' for i in range(3, -1, -1): tag += chr((tag_raw >> 8 * i) & 0xFF) if tag in tags.keys(): tags[tag].add(caller_name) else: tags[tag] = set([caller_name]) break prev = idc.prev_head(prev) return True nimps = idaapi.get_import_module_qty() for i in range(0, nimps): name = idaapi.get_import_module_name(i) if not name: continue idaapi.enum_import_names(i, imp_cb) return tags
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 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 enumImportNames(self, idx, func): return idaapi.enum_import_names(idx, func)
# ----------------------------------------------------------------------- # 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..."