def clear_names(): """for some reason deleting names seems to need several takes. This will loop until all names are deleted. """ names = list(idautils.Names()) while names: for name_ea, _ in names: idc.set_name(name_ea, "") # deletes name ida_auto.auto_wait() names = list(idautils.Names())
def name_exists(name): """ Return 'True' if name exists in current IDB file. """ f = open("names.txt", "w") for _, names in idautils.Names(): f.write(names) f.close() for _, existing_names in idautils.Names(): # generates (addr, name) tuples if name in existing_names: return True return False
def refreshitems(self): if self.encoding == None: return self.items = [] self.items_data = [] prev_string_start = 0 prev_string_length = 0 names_list = idautils.Names() for name_pair in names_list: if GetStringType(name_pair[0]) == None: continue else: try: if name_pair[0] < prev_string_start + prev_string_length: continue prev_string_start = 0 prev_string_length = 0 unicode_string = read_unicode_string(name_pair[0]) if unicode_string == None: continue korean_string = unicode_string #korean_string = korean_string.decode('utf-16') korean_string = korean_string.decode(self.encoding) korean_string = korean_string.encode('euc-kr') self.items.append(["%08X" % (name_pair[0]), korean_string]) self.items_data.append([name_pair[0], korean_string]) prev_string_start = name_pair[0] prev_string_length = len(unicode_string) except: continue
def extract_all_user_names(filename=None): """ Get all user-named labels inside IDA. Also prints into output window. :return: dictionary of all user named labels: label_name -> ea """ results = {} output = '' for ea, name in idautils.Names(): if ida_kernwin.user_cancelled(): return results if '_' in name: if name.split('_')[0] in ('def', 'sub', 'loc', 'jpt', 'j', 'nullsub'): continue flags = ida_bytes.get_full_flags(ea) if ida_bytes.has_user_name(flags): results[name] = ea output += '{} = 0x{:08x};\n'.format(name, ea) if filename is not None: with open(filename, 'w') as f: f.write(output) return results
def create_binary_table(ea, tables, name_tables): print("Creating %s from at 0x%08X..." % (name_tables, ea)) for xname, xhex_mask, xbyte_size, xelement_type in tables: list_addr = find_binary_strings(ea, xhex_mask, xbyte_size) if list_addr and list_addr[0] == ea: # make name addr_name = xname nm = [b for a, b in idautils.Names()] iname = 2 while addr_name in nm: addr_name = "%s_%d" % (xname, iname) iname += 1 if not gui.ask("Found %s. Create %s?" % (xname, addr_name)): return # rename in IDA rename_public(ea, addr_name) # make array in IDA make_array(ea, xbyte_size, xelement_type) return print "No known %s found at 0x%08X" % name_tables, ea
def dump(): ret = [] for addr, name in idautils.Names(): flags = ida_bytes.get_flags(addr) # The 'a' heuristic is fairly bad but we need to filter out IDA's default # naming for strings if ida_bytes.has_dummy_name(flags) or ida_bytes.has_auto_name(flags) or not ida_bytes.is_data(flags) or name[0] == 'a': continue # Sometimes the auto-generated names don't actually usually have the # right flags set, so skip these auto-looking names. if any(name.startswith(s) for s in ['byte_', 'word_', 'dword_', 'unk_', 'jpt_']): continue sz = ida_bytes.get_item_size(addr) if ida_bytes.is_struct(flags): ti = ida_nalt.opinfo_t() ida_bytes.get_opinfo(ti, addr, 0, flags) typ = ida_struct.get_struc_name(ti.tid) else: typ = None ret.append(filter_none({ 'address': addr, 'name': name, 'type': typ, 'sz': sz, 'flags': flags, })) return ret
def _locate_objc_runtime_functions(self): ''' Find the references to id objc_msgSend(id self, SEL op, ...); This is the target of all calls and jmps for ObjC calls. RDI == self RSI == selector X86/64 args: RDI, RSI, RDX, RCX, R8, R9 ... This function populates self.target_objc_msgsend with the intention of using this array in other functions to find indirect calls to the various ways objc_msgsend is referenced in binaries. The negative_reg variable below is blank, but is included in case some functions need to be excluded... TODO: Handle all other objective c runtime functions, not just objc_msgsend TODO: generalize to all architectures TODO: check that the matched names are in the proper mach-o sections based on the address in the tuple ''' positive_reg = re.compile('.*_objc_msgsend', re.IGNORECASE) negative_reg = re.compile('^$', re.IGNORECASE) if self.printflag: print "Finding Objective C runtime functions..." for name_tuple in idautils.Names(): # returns a tuple (address, name) addr, name = name_tuple if positive_reg.match(name) and not negative_reg.match(name): if self.printflag: print "0x%08x\t%s" % (addr, name) self.target_objc_msgsend.append(name_tuple) return None
def patch_to_call_puts(addr): #.text:0000114D E8 DE FE FF FF call _printf count = idc.ItemSize(addr) #get value v = idc.GetOperandValue(addr, 0) #要CALL的地址 - 下一条指令地址 = E8 后面的硬编码 plt_names = idautils.Names() for address, name in plt_names: if name == '.puts': puts_addr = address elif name == '.printf': printf_addr = address op = puts_addr - (addr + count) op = op & 0xffffffff #print('op: %s' %hex(op)) idc.PatchDword(addr + 1, op) idc.MakeCode(addr) print('patch [call _printf] ok, addr: %s' % hex(addr)) return
def get_seg_start_addr_from_rdata(seg_names): for seg_name in seg_names: for ea, name in idautils.Names(): if name == seg_name: return ea return None
def rename(self, nuname=None, **kwargs): tp = self.currentType(**kwargs) cnm = tp['name'] if not nuname: nuname = idc.AskStr(cnm, "Set new type name for " + cnm + ":") if not nuname or nuname == cnm: Logger.debug("Rename cancelled") return sid = idc.GetStrucIdByName(nuname) if sid and sid != idc.BADADDR: raise self.WrongTypeError("Type already exists", nuname) Logger.debug("Renaming class %s to %s", str(tp), nuname) if tp.get('vtblea'): idc.MakeName(tp['vtblea'], 'vtbl_' + nuname) if tp.get('id'): idc.SetStrucName(tp['id'], nuname) if tp.get('vtblid'): tp['vtblnm'] = nuname + 'Vtbl' idc.SetStrucName(tp['vtblid'], tp['vtblnm']) for nm in idautils.Names(): if nm[1].startswith(cnm): fn = nm[1].replace(cnm, nuname) Logger.debug("Renaming function " + nm[1] + " to " + fn) idc.MakeName(nm[0], fn) self.typeid = nuname self.update()
def get_seg_by_symname(sym_names): for sym_name in sym_names: for ea, name in idautils.Names(): if name == sym_name: return idaapi.getseg(ea) return None
def __initFunctionsInNames(self): nameList = idautils.Names() addrInNameList = [] for addr_name_pairs in nameList: addrInNameList.append(addr_name_pairs[0]) return [funcaddr for funcaddr in self._functions if funcaddr in addrInNameList]
def find_moduledata(): pModuleData = 0 if common.check_is_stripped(): log._info("binary is not stripped!") for addr, name in idautils.Names(): if name == "runtime.firstmoduledata": pModuleData = addr break else: log._info("binary is stripped..") log._info("Now find the moduledata by using brute force searching") GO1_16_MAGIC = 0xFFFFFFFA # <-- go 1.16 magic text_section = common.get_segment_addr_by_name(name=".text") rdata_section = common.get_segment_addr_by_name(name=".rdata") data_section = common.get_segment_addr_by_name(name=".data") sections = [(".text", text_section), (".rdata", rdata_section), (".data", data_section)] for sec_name, section_addr in sections: cur_addr = section_addr next_section_addr = common.get_next_segment_addr(addr=cur_addr) pModuleData = find_module_data_bruteforce( start_addr=section_addr, break_addr=next_section_addr, magic=GO1_16_MAGIC) if pModuleData != 0: log._info("ModuleData Structure locate at [%s] - @0x%x" % (sec_name, pModuleData)) break if pModuleData == 0: log._error("Cannot find ModuleData Structre in current binary...") return pModuleData
def send_names(self): """ Used to send all the names to the server. Usecase: Previously analyzed IDB """ for head in idautils.Names(): if not idaapi.has_dummy_name(idaapi.get_flags(head[0])): self.skel_conn.push_name(head[0], head[1])
def similar_names_list(nm): l = [] if nm: for ea, name in idautils.Names(): dn = idc.Demangle(name, 0) if idc.Demangle(name, 0) else name if re.search(r"\b" + nm + r"\b", dn): l.append((ea, name)) return l
def get_symbols(): """Get symbols from IDA database """ symbols = {} for addr, name in idautils.Names(): symbols[addr] = name return symbols
def filter_names(): names = idautils.Names() selected = [] for name in names: if name[1].startswith("_D"): # possible D name selected.append(name) return selected
def makeName(addr, name): names = list(map(lambda x: x[1], list(idautils.Names()))) i = 0 myname = name while myname in names: myname = name + "_%d" % i i += 1 idc.set_name(addr, myname, idc.SN_CHECK)
def send_names(self): """ Used to send all the names to the server. Usecase: Previously analyzed IDB """ for head in idautils.Names(): if not SkelUtils.func_name_blacklist(head[1]): mtype = idc.GetType(head[0]) if mtype and not mtype.lower().startswith("char["): self.skel_conn.push_name(head[0], head[1])
def tables_from_names(): ''' Yields addresses of VtableGroups if binary is not stripped ''' for n in idautils.Names(): seg = idaapi.getseg(n[0]) if seg is None or seg.type != idaapi.SEG_DATA: continue if is_vtable_name(n[1]) is True: yield n[0]
def get_ea(par): if isinstance(par, str): for ea, nm in idautils.Names(): if nm == par: return ea if re.match('off_[0-9a-fA-F]+', par): return int(par[4:], 16) return int(par, 16) if isinstance(par, int): return par
def __str__(self): names = dict(idautils.Names()) if type(self.fct) == value_t: name = names.get(self.fct.value, 'sub_%x' % self.fct.value) else: name = '(%s)' % str(self.fct) if self.params is None: p = '' else: p = str(self.params) return '%s(%s)' % (name, p)
def load_symbols_from_ida(self): for ea, name in idautils.Names(): flag = idc.GetFlags(ea) if not idc.hasUserName(flag): continue seg_ea = idc.SegStart(ea) seg_name = idc.SegName(ea) if seg_name not in self.sections: continue sym_type = 'function' if idc.isCode(flag) else 'object' self.symbols[name] = (seg_name, ea - seg_ea, sym_type)
def init_demangled_names(*args): """ Creates dictionary of demangled names => address, that will be used further at double click on methods got from symbols. """ demangled_names.clear() for address, name in idautils.Names(): short_name = idc.Demangle(name, idc.GetLongPrm(idc.INF_SHORT_DN)) if short_name: demangled_names[short_name.split('(') [0]] = address - idaapi.get_imagebase() print "[DEBUG] Demangled names have been initialized"
def m_smglobals(self): """ The SM_GLOBALS structure contains information about all stores being used by the system. It can be located via the nt!SmGlobals symbol. Locating this structure is the fastest way to begin the page retrieval process. This function searches for the symbol in IDA's namespace. It is available in the ntoskrnl's PDB. """ for va, name in idautils.Names(): if "?SmGlobals" in name: return va - idaapi.get_imagebase() self.logger.error("SmGlobals could not be resolved.") return None
def init_demangled_names(*args): """ Creates dictionary of demangled names => address, that will be used further at double click on methods got from symbols. """ demangled_names.clear() for address, name in idautils.Names(): short_name = idc.Demangle(name, idc.INF_SHORT_DN) if short_name: short_name = common.demangled_name_to_c_str(short_name) demangled_names[short_name].add(address - idaapi.get_imagebase()) print "[DEBUG] Demangled names have been initialized"
def _init_demangled_names(): """ Creates dictionary of demangled names => set of address, that will be used further when user makes double click on methods in Decompiler output. """ demangled_names.clear() for address, name in idautils.Names(): short_name = idc.demangle_name(name, idc.INF_SHORT_DN) if short_name: short_name = common.demangled_name_to_c_str(short_name) demangled_names[short_name].add(address - idaapi.get_imagebase()) print("[DEBUG] Demangled names have been initialized")
def find_ida_name(self, fn_name): """ This functions serves as a soft search for function names. It exists to allow some flexibility when searching for mangled function names. """ self.logger.debug("Searching for {0}...".format(fn_name)) for name_addr in idautils.Names(): if fn_name in name_addr[1]: self.logger.debug("found {0} @ {1}".format(name_addr[1], hex(name_addr[0]))) return name_addr #Tuple self.logger.debug("{0} not found".format(fn_name)) return None, None
def nlrepl(oldstr, newstr, log=True): """ Replaces string from all names in the global name list :param oldstr: occurrence to replace :param newstr: replaced string :param log: True by default, logging messages of what got replaced """ for ea, name in idautils.Names(): if oldstr in name: newName = name.replace(oldstr, newstr, 1) if log: print('%07X: Replacing %s -> %s' % (ea, name, newName)) idc.MakeName(ea, newName)
def get_names(): """ Get symbols from IDA database :return: Dict containing symbol information """ symbols = {} for addr, name in idautils.Names(): symbols[addr] = name return symbols