def OnSelectLine(self, n): segname = self.items[n][0] seg = ida_segment.get_segm_by_name(segname + ":__text") filename = segname.replace(".", "_") + "_massbp" fp = open(filename + ".h", "w") guard = filename.upper() + "_H" fp.write("#ifndef %s\n" % guard) fp.write("#define %s\n" % guard) # Put the ID of the function inside the immediate of the BRK brk = 0xd4200000 fxnid = 0 fxns = list(idautils.Functions(seg.start_ea, seg.end_ea)) # orig instrs for sleh hook, indexed by function ID # one shot breakpoints fp.write("static uint32_t %s_orig_instrs[] = {\n" % filename) for fxnaddr in fxns: instr = int.from_bytes(idaapi.get_bytes(fxnaddr, 4, False), "little") fp.write(hex(instr) + ",\n") fp.write("};\n") fxnid = 0 fp.write("static const char *%s_fxn_names[] = {\n" % filename) for fxnaddr in fxns: fxnname = ida_funcs.get_func_name(fxnaddr) fxnname_dm = idc.demangle_name(fxnname, get_inf_attr(idc.INF_LONG_DN)) if fxnname_dm != None: fxnname = fxnname_dm fp.write("\"%s\",\n" % fxnname) fp.write("};\n") fxnid = 0 fp.write("static void %s(void){\n" % filename) for fxnaddr in fxns: brk &= 0xffe0001f brk |= (fxnid << 5) fxnaddrh = hex(fxnaddr) # print("Current function {} with ID {}, brk {}".format(fxnaddrh, fxnid, hex(brk))) fp.write("kwrite_instr({}+kernel_slide, {}); /* FUNCTION {} */\n". format(fxnaddrh, hex(brk), hex(fxnid))) fxnid += 1 fp.write("}\n") fxnid = 0 fp.write("static void %s(void){\n" % filename.replace("massbp", "undobp")) for fxnaddr in fxns: brk &= 0xffe0001f brk |= (fxnid << 5) fxnaddrh = hex(fxnaddr) # print("Current function {} with ID {}, brk {}".format(fxnaddrh, fxnid, hex(brk))) fp.write( "kwrite_instr({}+kernel_slide, {}_orig_instrs[{}]);\n".format( fxnaddrh, filename, hex(fxnid))) fxnid += 1 fp.write("}\n") fp.write("#endif\n") print("Wrote header file to %s" % os.getcwd() + "/" + fp.name) fp.close() return n
def GetExportedFunctionByName(name): for funcAddr in idautils.Functions(): funcName = GetFunctionName(funcAddr) if funcName == name: print(name + ":" + hex(funcAddr)) return funcAddr
def get_items_for_type(self): x = self.target.operands['x'] m = self.target.operands['m'] xtype = x.type xtype.remove_ptr_or_array() typename = idaapi.print_tinfo('', 0, 0, idaapi.PRTYPE_1LINE, xtype, '', '') addresses = [] for ea in idautils.Functions(): try: cfunc = idaapi.decompile(ea) except: print 'Decompilation of %x failed' % (ea, ) continue str(cfunc) for citem in cfunc.treeitems: citem = citem.to_specific_type if not (type(citem) == idaapi.cexpr_t and citem.opname in ('memptr', 'memref')): continue _x = citem.operands['x'] _m = citem.operands['m'] _xtype = _x.type _xtype.remove_ptr_or_array() _typename = idaapi.print_tinfo('', 0, 0, idaapi.PRTYPE_1LINE, _xtype, '', '') #~ print 'in', hex(cfunc.entry_ea), _typename, _m if not (_typename == typename and _m == m): continue parent = citem while parent: if type(parent.to_specific_type) == idaapi.cinsn_t: break parent = cfunc.body.find_parent_of(parent) if not parent: print 'cannot find parent statement (?!)' continue if parent.ea in addresses: continue if parent.ea == idaapi.BADADDR: print 'parent.ea is BADADDR' continue addresses.append(parent.ea) self.functions.append(cfunc.entry_ea) self.items.append( (parent.ea, idc.GetFunctionName(cfunc.entry_ea), self.get_decompiled_line(cfunc, parent.ea))) return []
def main(): eh = flare_emu.EmuHelper() # dictionary that stores data used across emulation runs, function emulation specific data is set below userData = { # found stackstrings in stack memory "stackstrings": [], # found stackstrings in global memory (globalstrings) "globalstrings": [] } cnt_functions = 0 cnt_analyzed = 0 cnt_found_ss = 0 cnt_commented_ss = 0 errors = [] start = time.time() print("Started ironstrings stackstring deobfuscation") print_header() if ANALYZE_SINGLE_FUNC: fvas = [idc.get_func_attr(idc.here(), idc.FUNCATTR_START)] else: fvas = idautils.Functions() for fva in fvas: logging.debug("running on 0x%X", fva) if JUMP_TO_FUNC: idc.jumpto(fva) if fva == idaapi.BADADDR: logging.debug("skipping invalid function address") continue if idc.get_func_flags(fva) & (idc.FUNC_LIB | idc.FUNC_THUNK): logging.debug("skipping library or thunk function 0x%X", fva) continue # function start address userData["funcStart"] = fva # list of addresses of last instruction for all basic blocks in function userData["bb_ends"] = get_bb_ends(fva) # memory writes in current function userData["mem_writes"] = {} # start and end addresses of all memory writes in function userData["writelog"] = set() # memory write count in current basic block userData["mem_write_count"] = 0 # cache previous address to count instructions that are executed multiple times, e.g. rep prefixed userData["prevAddress"] = 0 # number same instruction has been executed in a row userData["repCount"] = 0 cnt_functions += 1 try: # emulate various paths through function via flare-emu, use hooks to reconstruct strings eh.iterateAllPaths(fva, noop, hookData=userData, callHook=call_hook, instructionHook=instr_hook, memAccessHook=hook_mem_write, hookApis=False, maxPaths=MAX_CODE_PATHS) except unicorn.UcError as e: errors.append("Error analyzing function 0x{:X}: {}".format( fva, str(e))) else: cnt_analyzed += 1 # print stackstrings found in this function f_ss = filter(lambda s: s.fva == fva, userData["stackstrings"]) cnt_found_ss += len(f_ss) for ss in sorted(f_ss, key=lambda s: s.written_at): print_string(ss.fva, ss.written_at, ss.offset, ss.s) # IMPROVEMENT adjust stack frame member size in IDA view # print globalstrings found in this function f_gs = filter(lambda g: g.fva == fva, userData["globalstrings"]) cnt_found_ss += len(f_gs) for gs in sorted(f_gs, key=lambda g: g.written_at): print_string(gs.fva, gs.written_at, gs.offset, gs.s) if COMMENT_STACKSTRINGS: for ss in f_ss: if not ss.written_at: errors.append( "Can't get location where '{}' was written in 0x{:X}." .format(ss.s, ss.fva)) continue ss_cmt = format_comment(ss.s) if append_comment(ss.written_at, ss_cmt): cnt_commented_ss += 1 else: errors.append( "Failed to set comment at 0x{:X}: {}".format( ss.written_at, ss_cmt)) for gs in f_gs: if COMMENT_STACKSTRING_GLOBAL_REPEATABLE: repeatable = True cmt_va = gs.offset else: repeatable = False cmt_va = gs.written_at if not cmt_va: errors.append( "Can't get location where '{}' was written in 0x{:X}." .format(gs.s, gs.fva)) continue gs_cmt = format_comment(gs.s) if append_comment(cmt_va, gs_cmt, repeatable): cnt_commented_ss += 1 else: errors.append( "Failed to set comment at 0x{:X}: {}".format( cmt_va, gs_cmt)) # update IDA view idc.refresh_idaview_anyway() # clean up memory after each function eh.resetEmulatorHeapAndStack() print_summary(cnt_functions, cnt_analyzed, cnt_found_ss, cnt_commented_ss, errors) if PRINT_PLAIN_SUMMARY: print_plain_summary(userData["stackstrings"] + userData["globalstrings"]) print( "\nFinished ironstrings stackstring deobfuscation after {:.2f} seconds" .format(time.time() - start))
def Functions(self, start=None, end=None): """Returns list of Functions entry's in the program being analyzed""" return idautils.Functions(start, end)
#encoding: utf-8 import idautils import idaapi min = MinEA() max = MaxEA() for func in idautils.Functions(): flags = idc.GetFunctionFlags(func) if flags & FUNC_LIB & flags & FUNC_THUNK: continue dism_addr = list(idautils.FuncItems(func)) for curr_addr in dism_addr: # o_imm = 5 if idc.GetOpType(curr_addr, 0) == 5 and \ (min < idc.GetOperandValue(curr_addr, 0) < max): idc.OpOff(curr_addr, 0, 0) if idc.GetOpType(curr_addr, 0) == 5 and \ (min < idc.GetOperandValue(curr_addr, 1) < max): idc.OpOff(curr_addr, 1, 0)
def get_all_functions(): for func in idautils.Functions(): print(hex(func), idc.GetFunctionName(func))
def activate(self, ctx): if self.action in ACTION_CONVERT: # convert t0, t1, view = idaapi.twinpos_t(), idaapi.twinpos_t( ), idaapi.get_current_viewer() if idaapi.read_selection(view, t0, t1): start, end = t0.place(view).toea(), t1.place(view).toea() size = end - start elif idc.get_item_size(idc.get_screen_ea()) > 1: start = idc.get_screen_ea() size = idc.get_item_size(start) end = start + size else: return False data = idc.get_bytes(start, size) if isinstance(data, str): # python2 compatibility data = bytearray(data) name = idc.get_name(start, idc.GN_VISIBLE) if not name: name = "data" if data: print("\n[+] Dump 0x%X - 0x%X (%u bytes) :" % (start, end, size)) if self.action == ACTION_CONVERT[0]: # escaped string print('"%s"' % "".join("\\x%02X" % b for b in data)) elif self.action == ACTION_CONVERT[1]: # hex string print("".join("%02X" % b for b in data)) elif self.action == ACTION_CONVERT[2]: # C array output = "unsigned char %s[%d] = {" % (name, size) for i in range(size): if i % 16 == 0: output += "\n " output += "0x%02X, " % data[i] output = output[:-2] + "\n};" print(output) elif self.action == ACTION_CONVERT[3]: # C array word data += b"\x00" array_size = (size + 1) // 2 output = "unsigned short %s[%d] = {" % (name, array_size) for i in range(0, size, 2): if i % 16 == 0: output += "\n " output += "0x%04X, " % u16(data[i:i + 2]) output = output[:-2] + "\n};" print(output) elif self.action == ACTION_CONVERT[4]: # C array dword data += b"\x00" * 3 array_size = (size + 3) // 4 output = "unsigned int %s[%d] = {" % (name, array_size) for i in range(0, size, 4): if i % 32 == 0: output += "\n " output += "0x%08X, " % u32(data[i:i + 4]) output = output[:-2] + "\n};" print(output) elif self.action == ACTION_CONVERT[5]: # C array qword data += b"\x00" * 7 array_size = (size + 7) // 8 output = "unsigned long %s[%d] = {" % (name, array_size) for i in range(0, size, 8): if i % 32 == 0: output += "\n " output += "%#018X, " % u64(data[i:i + 8]) output = output[:-2] + "\n};" print(output.replace("0X", "0x")) elif self.action == ACTION_CONVERT[6]: # python list print("[%s]" % ", ".join("0x%02X" % b for b in data)) elif self.action == ACTION_CONVERT[7]: # python list word data += b"\x00" print("[%s]" % ", ".join("0x%04X" % u16(data[i:i + 2]) for i in range(0, size, 2))) elif self.action == ACTION_CONVERT[8]: # python list dword data += b"\x00" * 3 print("[%s]" % ", ".join("0x%08X" % u32(data[i:i + 4]) for i in range(0, size, 4))) elif self.action == ACTION_CONVERT[9]: # python list qword data += b"\x00" * 7 print("[%s]" % ", ".join( "%#018X" % u64(data[i:i + 8]) for i in range(0, size, 8)).replace("0X", "0x")) elif self.action == ACTION_XORDATA: t0, t1, view = idaapi.twinpos_t(), idaapi.twinpos_t( ), idaapi.get_current_viewer() if idaapi.read_selection(view, t0, t1): start, end = t0.place(view).toea(), t1.place(view).toea() else: if idc.get_item_size(idc.get_screen_ea()) > 1: start = idc.get_screen_ea() end = start + idc.get_item_size(start) else: return False data = idc.get_bytes(start, end - start) if isinstance(data, str): # python2 compatibility data = bytearray(data) x = idaapi.ask_long(0, "Xor with...") if x: x &= 0xFF print("\n[+] Xor 0x%X - 0x%X (%u bytes) with 0x%02X:" % (start, end, end - start, x)) print(repr("".join(chr(b ^ x) for b in data))) elif self.action == ACTION_FILLNOP: t0, t1, view = idaapi.twinpos_t(), idaapi.twinpos_t( ), idaapi.get_current_viewer() if idaapi.read_selection(view, t0, t1): start, end = t0.place(view).toea(), t1.place(view).toea() idaapi.patch_bytes(start, b"\x90" * (end - start)) print("\n[+] Fill 0x%X - 0x%X (%u bytes) with NOPs" % (start, end, end - start)) elif self.action == ACTION_SCANVUL: print("\n[+] Finding Format String Vulnerability...") found = [] for addr in idautils.Functions(): name = idc.get_func_name(addr) if "printf" in name and "v" not in name and idc.get_segm_name( addr) in (".text", ".plt", ".idata"): xrefs = idautils.CodeRefsTo(addr, False) for xref in xrefs: vul = self.check_fmt_function(name, xref) if vul: found.append(vul) if found: print("[!] Done! %d possible vulnerabilities found." % len(found)) ch = VulnChoose("Vulnerability", found, None, False) ch.Show() else: print("[-] No format string vulnerabilities found.") elif self.action == ACTION_PASTE: print("paste data.") paste_data_window(idc.get_screen_ea()) elif self.action == ACTION_DUMPER: print("dump data.") dumper_windows() else: return 0 return 1
def get_all_funcs(): """ Enumerate all function names defined in the IDB. """ return set(idaapi.get_func_name(ea) for ea in idautils.Functions())
def get_fns(self): import idautils return list(idautils.Functions())
def _Functions(): """ Thread safe IDA iteration over all functions. """ logger.debug('_Functions') return list(idautils.Functions())
def compare(self): res = defaultdictRecurse() if self.f_fol_cmp: self.mcur.execute( "SELECT sha256,path FROM sample WHERE path LIKE ?", (self.ana_fol + '%', )) else: self.mcur.execute("SELECT sha256,path FROM sample") frows = self.mcur.fetchall() num_of_samples = len(frows) for sha256, path in frows: res[sha256]['path'] = path res[sha256]['mcnt'].default_factory = lambda: 0 #sql = "SELECT sha256,fname,fhd,fhm,f_ana,ptype FROM function WHERE f_ana == 1 AND bsize BETWEEN ? AND ?" if self.f_ana_cmp else "SELECT sha256,fname,fhd,fhm,f_ana,ptype FROM function WHERE bsize BETWEEN ? AND ?" sql = "SELECT function.sha256,fname,fhd,fhm,f_ana,ptype FROM function INNER JOIN sample on function.sha256 == sample.sha256 WHERE path LIKE ? AND " if self.f_fol_cmp else "SELECT sha256,fname,fhd,fhm,f_ana,ptype FROM function WHERE " sql += "f_ana == 1 AND bsize BETWEEN ? AND ?" if self.f_ana_cmp else "bsize BETWEEN ? AND ?" for fva in idautils.Functions(): fname = get_func_name(fva) if self.exclude_libthunk(fva, fname) or not num_of_samples: continue pfhd, pbsize = self.calc_fn_ssdeep(fva, fname) pfhm, pcfgnum = self.calc_fn_machoc(fva, fname) if pfhd and pfhm: pbuf = ctypes.create_string_buffer(pfhd) self.debug( 'COMPARE {}: ssdeep={} (size={}), machoc={} (num of bb={})' .format(fname, pfhd, pbsize, pfhm, pcfgnum)) min_ = pbsize * (1 - (self.ratio / 100)) max_ = pbsize * (1 + (self.ratio / 100)) self.debug('min={}, max={}'.format(min_, max_)) if self.f_fol_cmp: self.mcur.execute(sql, (self.ana_fol + '%', min_, max_)) else: self.mcur.execute(sql, (min_, max_)) frows = self.mcur.fetchall() self.debug('targeted {} records'.format(len(frows))) for sha256, sfname, sfhd, sfhm, sf_ana, sptype in frows: if sha256 == self.sha256: # skip the self continue res[sha256]['mfn'][fva].default_factory = lambda: 0 sbuf = ctypes.create_string_buffer(sfhd) score = fuzzy_lib.fuzzy_compare(pbuf, sbuf) if g_dbg_flag and fva == g_dbg_fva and sfname == g_dbg_fname and sha256 == g_dbg_sha256: self.debug( '{:#x}: compared with {} in {} score = {} machoc match = {}' .format(fva, sfname, sha256, score, bool(pfhm == sfhm))) if (score >= self.threshold) or ( score >= self.threshold_cfg and pfhm == sfhm) or (pbsize > self.max_bytes_for_score and pfhm == sfhm): res[sha256]['mcnt']['total'] += 1 if sf_ana: res[sha256]['mcnt']['analyzed'] += 1 if score > res[sha256]['mfn'][fva]['score'] or ( res[sha256]['mfn'][fva]['score'] == 0 and pbsize > self.max_bytes_for_score): res[sha256]['mfn'][fva]['score'] = score res[sha256]['mfn'][fva]['cfg_match'] = bool( pfhm == sfhm) res[sha256]['mfn'][fva]['sfname'] = sfname res[sha256]['mfn'][fva]['sptype'] = sptype res[sha256]['mfn'][fva]['pbsize'] = pbsize c = SummaryCh("fn_fuzzy summary", res) c.Show() success('totally {} samples compared'.format(num_of_samples))
#encoding: utf-8 import idautils for func in idautils.Functions(): flags = idc.GetFunctionFlags(func) if flags & FUNC_LIB or flags & FUNC_THUNK: continue dism_addr = list(idautils.Functions(func)) for line in dism_addr: m = idc.GetMnem(line) if m == 'call' or m == 'jmp': op = idc.GetOpType(line, 0) if op == o_reg: print "0x%x %s" % (line, idc.GetDisasm(line))
def run(self, arg): for function in idautils.Functions(): values = {} #function = ida_kernwin.get_screen_ea() function_start = idc.get_func_attr(function, idc.FUNCATTR_START) function_end = idc.get_func_attr(function, idc.FUNCATTR_END) function_name = idc.get_func_name(function) if re.search("func\d+", function_name): try: decompiled_code = str(ida_hexrays.decompile(function)) lenght = re.search(r"i < (\w+); \+\+i", decompiled_code) if lenght != None: # Getting hex values displayed in the decompiled code values[function_name] = [] for z in re.findall("= (0[xX][0-9a-fA-F]+)", decompiled_code): values[function_name].append( binascii.hexlify( struct.pack( '<Q', int(int(z.replace("0x", ""), base=16)))).decode( "windows-1252").replace( "00", "")) # Getting values from xmmwords xmmwords = re.findall(r"xmmword_(\w+)", decompiled_code) for xmmword in xmmwords: #print(f"\nxmmword_{xmmword} -> {int(xmmword, 16)}") ida_bytes.create_data( int(xmmword, 16), ida_bytes.byte_flag(), 1, ida_netnode.BADNODE ) # create byte at the specified address data = binascii.hexlify( idaapi.get_bytes( int(xmmword, 16), int(lenght.group(1), 16))).decode("windows-1252") values[function_name].append(data) #print(binascii.hexlify(idaapi.get_bytes(int(xmmword, 16), int(lenght, 16)))) # get bytes except idaapi.DecompilationFailure: pass try: lenght = int(len(values[function_name]) / 2) string = self.to_decimal(values[function_name][0:lenght]) key = self.to_decimal(values[function_name][lenght::]) str_decrypted = "" for i in range(0, len(string)): str_decrypted += chr(string[i] ^ key[i % len(key)]) #idaapi.msg(f"{string[i]} ^ {key[i % len(key)]}\n") if str_decrypted != "": #idaapi.msg(str_decrypted+"\n") idc.set_func_cmt(function_start, str_decrypted, 0) rowPosition = self.plg.table.rowCount() self.plg.table.insertRow(rowPosition) self.plg.table.setItem( rowPosition, 0, QtWidgets.QTableWidgetItem( function_name.replace(".", "_"))) self.plg.table.setItem( rowPosition, 1, QtWidgets.QTableWidgetItem(str_decrypted)) except: pass
# list functions in IDA # by laqieer # 2018-11-14 import idautils if __name__ == "__main__": file = idc.AskFile(1, "*.md", "Save functions to list") if file is not None: list = os.open(file, os.O_WRONLY | os.O_CREAT) if list is not None: os.write(list, "# Functions in %s\n\n" % idaapi.get_root_filename()) os.write(list, "| Address | Name | Comment |\n") os.write(list, "| ------ | ------ | ------ |\n") for func in idautils.Functions(0x3000000, BADADDR): os.write( list, "| 0x%X | %s | %s |\n" % (func, idaapi.get_func_name(func), idaapi.get_func_cmt(idaapi.get_func(func), 1))) os.close(list) print "Functions have been written to ", file
def generate(self): signatures = RizzoSignatures() # Generate unique string-based function signatures for (ea, string) in self.strings.items(): # Only generate signatures on reasonably long strings with one xref if len(string.value) >= 8 and len(string.xrefs) == 1: func = idaapi.get_func(string.xrefs[0]) if func: strhash = self.sighash(string.value) # Check for and remove string duplicate signatures (the same # string can appear more than once in an IDB). # If no duplicates, add this to the string signature dict. if strhash in signatures.strings: del signatures.strings[strhash] signatures.stringdups.add(strhash) elif strhash not in signatures.stringdups: signatures.strings[strhash] = func.startEA # Generate formal, fuzzy, and immediate-based function signatures for ea in idautils.Functions(): func = idaapi.get_func(ea) if func: # Generate a signature for each block in this function blocks = self.function(func) # Build function-wide formal and fuzzy signatures by simply # concatenating the individual function block signatures. formal = self.sighash(''.join([str(e) for (e, f, i, c) in blocks])) fuzzy = self.sighash(''.join([str(f) for (e, f, i, c) in blocks])) # Add this signature to the function dictionary. signatures.functions[func.startEA] = (idc.Name(func.startEA), blocks) # Check for and remove formal duplicate signatures. # If no duplicates, add this to the formal signature dict. if formal in signatures.formal: del signatures.formal[formal] signatures.formaldups.add(formal) elif formal not in signatures.formaldups: signatures.formal[formal] = func.startEA # Check for and remove fuzzy duplicate signatures. # If no duplicates, add this to the fuzzy signature dict. if fuzzy in signatures.fuzzy: del signatures.fuzzy[fuzzy] signatures.fuzzydups.add(fuzzy) elif fuzzy not in signatures.fuzzydups: signatures.fuzzy[fuzzy] = func.startEA # Check for and remove immediate duplicate signatures. # If no duplicates, add this to the immediate signature dict. for (e, f, immediates, c) in blocks: for immediate in immediates: if immediate in signatures.immediates: del signatures.immediates[immediate] signatures.immediatedups.add(immediate) elif immediate not in signatures.immediatedups: signatures.immediates[immediate] = func.startEA # These need not be maintained across function calls, # and only add to the size of the saved signature file. signatures.fuzzydups = set() signatures.formaldups = set() signatures.stringdups = set() signatures.immediatedups = set() # DEBUG signatures.show() return signatures
def activate(self, ctx): if self.action in ACTION_CONVERT: # convert selection, start, end = idaapi.read_selection() if selection: size = end - start elif ItemSize(ScreenEA()) > 1: start = ScreenEA() size = ItemSize(start) end = start + size else: return False data = idaapi.get_many_bytes(start, size) name = Name(start) if not name: name = "data" if data: print "\n[+] Dump 0x%X - 0x%X (%u bytes) :" % (start, end, size) if self.action == ACTION_CONVERT[0]: # escaped string print '"%s"' % "".join("\\x%02X" % ord(b) for b in data) elif self.action == ACTION_CONVERT[1]: # hex string print "".join("%02X" % ord(b) for b in data) elif self.action == ACTION_CONVERT[2]: # C array output = "unsigned char %s[%d] = {" % (name, size) for i in range(size): if i % 16 == 0: output += "\n " output += "0x%02X, " % ord(data[i]) output = output[:-2] + "\n};" print output elif self.action == ACTION_CONVERT[3]: # C array word data += "\x00" array_size = (size + 1) / 2 output = "unsigned short %s[%d] = {" % (name, array_size) for i in range(0, size, 2): if i % 16 == 0: output += "\n " output += "0x%04X, " % u16(data[i:i + 2]) output = output[:-2] + "\n};" print output elif self.action == ACTION_CONVERT[4]: # C array dword data += "\x00" * 3 array_size = (size + 3) / 4 output = "unsigned int %s[%d] = {" % (name, array_size) for i in range(0, size, 4): if i % 32 == 0: output += "\n " output += "0x%08X, " % u32(data[i:i + 4]) output = output[:-2] + "\n};" print output elif self.action == ACTION_CONVERT[5]: # C array qword data += "\x00" * 7 array_size = (size + 7) / 8 output = "unsigned long %s[%d] = {" % (name, array_size) for i in range(0, size, 8): if i % 32 == 0: output += "\n " output += "%#018X, " % u64(data[i:i + 8]) output = output[:-2] + "\n};" print output.replace("0X", "0x") elif self.action == ACTION_CONVERT[6]: # python list print "[%s]" % ", ".join("0x%02X" % ord(b) for b in data) elif self.action == ACTION_CONVERT[7]: # python list word data += "\x00" print "[%s]" % ", ".join("0x%04X" % u16(data[i:i + 2]) for i in range(0, size, 2)) elif self.action == ACTION_CONVERT[8]: # python list dword data += "\x00" * 3 print "[%s]" % ", ".join("0x%08X" % u32(data[i:i + 4]) for i in range(0, size, 4)) elif self.action == ACTION_CONVERT[9]: # python list qword data += "\x00" * 7 print "[%s]" % ", ".join( "%#018X" % u64(data[i:i + 8]) for i in range(0, size, 8)).replace("0X", "0x") elif self.action == ACTION_XORDATA: selection, start, end = idaapi.read_selection() if not selection: if ItemSize(ScreenEA()) > 1: start = ScreenEA() end = start + ItemSize(start) else: return False data = idaapi.get_many_bytes(start, end - start) x = AskLong(0, "Xor with...") if x: x &= 0xFF print "\n[+] Xor 0x%X - 0x%X (%u bytes) with 0x%02X:" % ( start, end, end - start, x) print repr("".join(chr(ord(b) ^ x) for b in data)) elif self.action == ACTION_FILLNOP: selection, start, end = idaapi.read_selection() if selection: idaapi.patch_many_bytes(start, "\x90" * (end - start)) print "\n[+] Fill 0x%X - 0x%X (%u bytes) with NOPs" % ( start, end, end - start) elif self.action == ACTION_SCANVUL: print "\n[+] Finding Format String Vulnerability..." found = [] for addr in idautils.Functions(): name = GetFunctionName(addr) if "printf" in name and "v" not in name and SegName(addr) in ( ".text", ".plt", ".idata"): xrefs = idautils.CodeRefsTo(addr, False) for xref in xrefs: vul = self.check_fmt_function(name, xref) if vul: found.append(vul) if found: print "[!] Done! %d possible vulnerabilities found." % len( found) ch = VulnChoose("Vulnerability", found, None, False) ch.Show() else: print "[-] No format string vulnerabilities found." else: return 0 return 1
def match_all_callback(self, ctx): self.operations.match_funcs(list(idautils.Functions()))
def OnInit(self): self.items = [[hex(x), get_func_name(x), x] for x in idautils.Functions()] return True
def upload_all_callback(self, ctx): self.operations.upload_funcs(list(idautils.Functions()))
import idaapi import idautils lines = [] for ea in idautils.Functions(0x0, 0xFFFFFFFFFFFFFFFF): lines.append("function: %s" % hex(ea)) f = idaapi.get_func(ea) for bb in idaapi.FlowChart(f, flags=idaapi.FC_PREDS): lines.append("basic block: %s" % hex(bb.start_ea)) for head in idautils.Heads(bb.start_ea, bb.end_ea): insn = idautils.DecodeInstruction(head) if not insn: continue lines.append("instruction: %s" % hex(head)) print("\n".join(lines)) import ida_pro ida_pro.qexit(0)
import idaapi import idc import idautils import json ##SCRIPT TO REBUILD ANATOVA FUNCTIONS functions = [] bucket = [] for f in idautils.Functions(): name = idc.get_func_name(f) if name[:2] == "j_": continue addr = f func = idaapi.get_func(f) size = func.endEA - func.startEA print "{} {} - {}".format(addr, name, size) tmp = {"addr": addr, "name": name, "size": size} if size == 11: if len(bucket) > 0: functions.append(bucket) bucket = [] bucket.append(tmp) functions.append(bucket) for bucket in functions: init = bucket[0]['addr'] tmp = bucket[-1] end = init
def GetFunctions(): return idautils.Functions()
def get_functions(): return (IdaLocation(f) for f in idautils.Functions())
def isAssignedToAFunction(self, ea): funcs = idautils.Functions(ea, ea + 1) funcs_list = list(funcs) if len(funcs_list) != 0: return True return False
# by laqieer # 2018/11/18 import idautils import ida_hexrays import os if __name__ == "__main__": file = idc.AskFile(1, "*.md", "Export functions infomation to table") if file is not None: table = os.open(file, os.O_WRONLY | os.O_CREAT) if table is not None: os.write(table, "# Function infomation in " + idaapi.get_root_filename() + "\n") os.write(table, "\n|Address|Name|Declaration|Comment|\n") os.write(table, "|----|----|----|----|\n") for func_ea in idautils.Functions(): name = idaapi.get_func_name(func_ea) if idaapi.is_uname(name): func = idaapi.get_func(func_ea) comment = idaapi.get_func_cmt(func, 1) if comment is None: comment = "" # new line in comment comment = comment.replace("\n", "<br>") # pf = ida_hexrays._decompile(func, None) try: pf = ida_hexrays.decompile(func_ea, ida_hexrays.hexrays_failure_t(0, func_ea, name)) except ida_hexrays.DecompilationFailure, e: print e, name decl = "" else:
def get_function_addresses(self): return list(idautils.Functions())
# (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import idautils import logging logger = logging.getLogger("YaCo") def init(tests): pass def exit(tests): pass _functions = sorted([k for k in idautils.Functions()]) def get_all_functions(): for ea in _functions: yield ea
import idaapi import idautils import idc functions_list = [] for f_ep in idautils.Functions(): # get list of functions' entrypoint function = idaapi.get_func(f_ep) # get pointer to a function flowchart = idaapi.FlowChart(function) # retrieve flowchart of a function # append function to the list functions_list.append( [flowchart.size, str(idc.get_func_name(function.start_ea))]) functions_list.sort() # sort the list for function in functions_list: print("{} -\t{}".format(function[0], function[1])) # print("Function %s starting at 0x%x consists of %d basic blocks\n" % (GetFunctionName(function.startEA), function.startEA, flowchart.size))
def main(): with open(os.path.join(__LOG_ROOT_PATH, __LOG_FILE_NAME), 'w') as f: if __DEBUG: f.write("successfully opened {}\n".format( os.path.join(__LOG_ROOT_PATH, __LOG_FILE_NAME))) f.write("{} \t=========zyc_test begins!=========\n\n".format( str(datetime.datetime.now()))) names = idautils.Names() name_addresses = [] name_literals = [] functions_found = [] for item in names: name_addresses.append(item[0]) name_literals.append(item[1]) if __DEBUG: f.write("\nNAME Address Pairs:\n") for i in range(len(name_addresses)): f.write( "Name and Address Pair -- Name: {}, Address: {}\n".format( str(name_literals[i]), str(hex(name_addresses[i])))) f.write('\n') func_gen = idautils.Functions() if __DEBUG: f.write("succesfully called idautils.Functions()\n") if __DEBUG: f.write("\nFunction Names:\n") for item in func_gen: func_literal = get_func_literal(item, name_addresses, name_literals) if func_literal is None: f.write("function at {} cannot be found in idautils.Names()\n". format(str(hex(item)))) else: if __DEBUG: f.write("function at {} is named: {}\n".format( str(hex(item)), func_literal)) functions_found.append((item, func_literal)) atomic_functions = [] entry_functions = [] for function_address_name_pairs in functions_found: if is_the_function_calling_nothing(function_address_name_pairs, f): atomic_functions.append(function_address_name_pairs) if is_the_function_called_by_others(function_address_name_pairs, f): entry_functions.append(function_address_name_pairs) for pairs in atomic_functions: f.write("I call nothing: {}, at {}\n".format(pairs[1], pairs[0])) for pairs in entry_functions: f.write("nothings called me: {}, at {}\n".format( pairs[1], pairs[0])) f.write("\n{} \t========zyc_test terminates!========\n".format( str(datetime.datetime.now()))) #uncomment this line when starting batch analysis idc.Exit(0) return 0