def enumerate_function_names():
func_name = dict()
for seg_ea in idautils.Segments():
# For each of the functions
function_ea = seg_ea
while function_ea != 0xffffffffL:
function_name = idc.GetFunctionName(function_ea)
# if already analyzed
if func_name.get(function_name, None) != None:
function_ea = idc.NextFunction(function_ea)
continue
image_base = idaapi.get_imagebase(function_ea)
addr = function_ea - image_base
addr = str(hex(addr))
addr = addr.replace("L", "")
addr = addr.replace("0x", "")
func_name[function_name] = get_list_of_function_instr(function_ea)
function_ea = idc.NextFunction(function_ea)
return func_name
python类Segments()的实例源码
def enumerate_function_names():
'''
The function enumerates all functions in a dll.
@return - dictionary {function_name : list of corresponded instructions}
'''
func_name = dict()
for seg_ea in idautils.Segments():
# For each of the functions
function_ea = seg_ea
while function_ea != 0xffffffffL:
function_name = idc.GetFunctionName(function_ea)
# if already analyzed
if func_name.get(function_name, None) != None:
function_ea = idc.NextFunction(function_ea)
continue
image_base = idaapi.get_imagebase(function_ea)
addr = function_ea - image_base
addr = str(hex(addr))
addr = addr.replace("L", "")
addr = addr.replace("0x", "")
func_name[function_name] = get_list_of_function_instr(function_ea)
function_ea = idc.NextFunction(function_ea)
return func_name
def getAllMemoryFromIda(self):
result = {}
seg_start = [ea for ea in idautils.Segments()][0]
current_start = seg_start
seg_end = idc.SegEnd(current_start)
current_buffer = ""
for index, current_start in enumerate(idautils.Segments()):
# get current buffer content
current_buffer = ""
for ea in lrange(current_start, idc.SegEnd(current_start)):
current_buffer += chr(idc.Byte(ea))
# first buffer is only saved
if index == 0:
result[seg_start] = current_buffer
continue
# otherwise decide if the buffers are consecutive and either save or update contents
if current_start != seg_end:
seg_start = current_start
result[seg_start] = current_buffer
else:
result[seg_start] += current_buffer
seg_end = idc.SegEnd(current_start)
return result
def enum_segm(self):
i = 0
for ea in idautils.Segments():
seg = idaapi.getseg(ea)
SigmName = idc.SegName(ea)
startA = idc.SegStart(ea)
endA = idc.SegEnd(ea)
className = idaapi.get_segm_class(seg)
seg_radio = SegmRadio(SigmName, startA, endA, className)
self.segm.append((SigmName, startA, endA, className))
self.segm_vbox.addWidget(seg_radio)
self.segm_vbox.addStretch(1)
if i == 0:
i = 1
seg_radio.toggle()
return self.segm_vbox
def Main():
codeSegments = GetExecutableSegments()
#Iterate Segments
for segment in codeSegments:
functions = GetFunctions(segment)
#Iterate Functions and search XOR
for function in functions:
flag = GetFunctionFlags(function)
if flag == -1 or flag & FUNC_LIB:
continue
#print hex(function), GetFunctionName(function)
xorList = FindXor(function)
if 0 < len(xorList):
print "[+]Found Possible Crypto at 0x%08X in function %s" % (function, GetFunctionName(function))
# Itrate over tuples (function, xorAddr, xorMnemonic, operand1, operand2)
for xor in xorList:
print "[+]Crypto Inst: 0x%08X: %s %s %s" % (xor[1], xor[2], xor[3], xor[4])
#Script Entry
def create_call_map(self, ftype):
assert_ida_available()
import idc
import idautils
seg_mapping = {idc.SegName(x): (idc.SegStart(x), idc.SegEnd(x)) for x in idautils.Segments()}
imports = seg_mapping[".idata"] if ftype == PE else seg_mapping['.plt']
start, stop = seg_mapping[".text"]
current = start
while current <= stop:
inst = current
if idc.GetMnem(inst) in ["call", "jmp"]:
value = idc.GetOperandValue(inst, 0)
name = idc.GetOpnd(inst, 0)
if imports[0] <= value <= imports[1]:
entry = self.config.call_map.add()
entry.address = inst
entry.name = name
current = idc.NextHead(current, stop)
def tables_from_heuristics(require_rtti=False):
''' Yields addresses of VTableGroups found via heuristic methods
'''
for s in idautils.Segments():
seg = idaapi.getseg(s)
if seg is None:
continue
if seg.type != idaapi.SEG_DATA:
continue
ea = seg.startEA
while ea < seg.endEA:
try:
table = VTableGroup(ea)
if require_rtti is True and ea.typeinfo is not None:
yield ea
elif require_rtti is False:
yield ea
ea += table.size
except ValueError:
# Assume vtables are aligned
ea += TARGET_ADDRESS_SIZE
def addresses():
"""Generate all mapped addresses."""
for s in idautils.Segments():
ea = idc.SegStart(s)
while ea < idc.SegEnd(s):
yield ea
ea = idaapi.nextaddr(ea)
def output_segments(out):
"""Dump binary segmentation."""
info = idaapi.get_inf_structure()
size = "r32" if info.is_32bit else "r64"
out.writelines(('(', info.get_proc_name()[1], ' ', size, ' ('))
for seg in idautils.Segments():
out.write("\n({} {} {:d} ({:#x} {:d}))".format(
idaapi.get_segm_name(seg),
"code" if idaapi.segtype(seg) == idaapi.SEG_CODE else "data",
idaapi.get_fileregion_offset(seg),
seg, idaapi.getseg(seg).size()))
out.write("))\n")
def output_symbols(out):
"""Dump symbols."""
try:
from idaapi import get_func_name2 as get_func_name
# Since get_func_name is deprecated (at least from IDA 6.9)
except ImportError:
from idaapi import get_func_name
# Older versions of IDA don't have get_func_name2
# so we just use the older name get_func_name
def func_name_propagate_thunk(ea):
current_name = get_func_name(ea)
if current_name[0].isalpha():
return current_name
func = idaapi.get_func(ea)
temp_ptr = idaapi.ea_pointer()
ea_new = idaapi.BADADDR
if func.flags & idaapi.FUNC_THUNK == idaapi.FUNC_THUNK:
ea_new = idaapi.calc_thunk_func_target(func, temp_ptr.cast())
if ea_new != idaapi.BADADDR:
ea = ea_new
propagated_name = get_func_name(ea) or '' # Ensure it is not `None`
if len(current_name) > len(propagated_name) > 0:
return propagated_name
else:
return current_name
# Fallback to non-propagated name for weird times that IDA gives
# a 0 length name, or finds a longer import name
for ea in idautils.Segments():
fs = idautils.Functions(idc.SegStart(ea), idc.SegEnd(ea))
for f in fs:
out.write('("%s" 0x%x 0x%x)\n' % (
func_name_propagate_thunk(f),
idc.GetFunctionAttr(f, idc.FUNCATTR_START),
idc.GetFunctionAttr(f, idc.FUNCATTR_END)))
def get_segments():
'''
fetch the segments in the current executable.
'''
for segstart in idautils.Segments():
segend = idaapi.getseg(segstart).endEA
segsize = segend - segstart
segname = str(idc.SegName(segstart)).rstrip('\x00')
segbuf = get_segment_buffer(segstart)
yield Segment(segstart, segend, segname, segbuf)
def enum_segments():
for segstart in idautils.Segments():
segend = idc.SegEnd(segstart)
segname = idc.SegName(segstart)
yield Segment(segstart, segend, segname)
def get_seg_range(seg):
for s in idautils.Segments():
if idc.SegName(s) == seg:
start_ea = idc.SegStart(s)
end_ea = idc.SegEnd(s)
return start_ea, end_ea
def __init__(self, title, api_results, flags=0):
Choose2.__init__(self,
title,
[["#", 6], ["Offset", 14], ["API Address", 14], ["DLL", 20], ["API", 35]],
embedded=True, width=140, height=20, flags=flags)
self.row_count = 0
self.base_address = [ea for ea in idautils.Segments()][0]
self.scout = ApiScout()
self.scout.setBaseAddress(self.base_address)
self.api_results = api_results
self.all_items = self.populate(api_results)
self.items = self.populate(api_results)
self.icon = 4
self.selcount = 0
def getBaseAddress(self):
return [ea for ea in idautils.Segments()][0]
def getLastAddress(self):
return idc.SegEnd([ea for ea in idautils.Segments()][-1]) - 1
def GetExecutableSegments():
segments = []
for segment in idautils.Segments():
#print SegName(segment), hex(segment)
#Get Segment Attribute
segPermission = GetSegmentAttr(segment, SEGATTR_PERM)
if segPermission & SEGPERM_EXEC:
print "[+]Code Segment %s 0x%08X" % (SegName(segment), segment)
segments.append(segment)
return segments
#Get Function List
def GetExecutableSegments():
segments = []
for segment in idautils.Segments():
#print SegName(segment), hex(segment)
#Get Segment Attribute
segPermission = GetSegmentAttr(segment, SEGATTR_PERM)
if segPermission & SEGPERM_EXEC:
print "[+]Code Segment %s 0x%08X" % (SegName(segment), segment)
segments.append(segment)
return segments
#Get Function List
def Main():
codeSegments = GetExecutableSegments()
#Iterate Segments
for segment in codeSegments:
functions = GetFunctions(segment)
#Iterate Functions and search XOR
for function in functions:
flag = GetFunctionFlags(function)
if flag == -1 or flag & FUNC_LIB:
continue
#print hex(function), GetFunctionName(function)
xorList = FindXor(function)
if 0 < len(xorList):
print "[+]Found Possible Crypto at 0x%08X in function %s" % (function, GetFunctionName(function))
# Itrate over tuples (function, xorAddr, xorMnemonic, operand1, operand2)
for xor in xorList:
print "[+]Crypto Inst: 0x%08X: %s %s %s" % (xor[1], xor[2], xor[3], xor[4])
#hardcoded addresses are not good
if function == 0x00402C72:
DecryptString0(function)
else:
pass
#Script Entry
def GetSection(sectionName):
for seg in idautils.Segments():
if idc.SegName(seg) == sectionName:
return seg
return 0
def Main():
InitEmulator()
codeSegments = GetExecutableSegments()
#Iterate Segments
for segment in codeSegments:
functions = GetFunctions(segment)
#Iterate Functions and search XOR
for function in functions:
flag = GetFunctionFlags(function)
if flag == -1 or flag & FUNC_LIB:
continue
#print hex(function), GetFunctionName(function)
xorList = FindXor(function)
if 0 < len(xorList):
print "[+]Found Possible Crypto at 0x%08X in function %s" % (function, GetFunctionName(function))
# Itrate over tuples (function, xorAddr, xorMnemonic, operand1, operand2)
for xor in xorList:
print "[+]Crypto Inst: 0x%08X: %s %s %s" % (xor[1], xor[2], xor[3], xor[4])
print
#hardcoded addresses are not good
if function == 0x00402CB8:
DecryptStackStrings(function)
else:
pass
#Script Entry
def iter_lines():
"""
Iterate through all line addresses in the IDB
Yields addresses of all lines.
"""
for ea in idautils.Segments():
seg_start = idc.SegStart(ea)
seg_end = idc.SegEnd(ea)
cur_addr = seg_start
while (cur_addr < seg_end) and (cur_addr != idaapi.BADADDR):
yield cur_addr
cur_addr = idc.NextHead(cur_addr)
def update_mapping(self):
pass
self.fun_mapping = {idc.GetFunctionName(x): (idaapi.get_func(x).startEA, idaapi.get_func(x).endEA-1) for x in
idautils.Functions()}
self.seg_mapping = {idc.SegName(x): (idc.SegStart(x), idc.SegEnd(x)) for x in idautils.Segments()}
def ret_addr(ea):
#we can't assume Thumb only, so we also keep ARM cases, just adjust addr in Thumb cases
if (ea % 2) != 0:
ea -= 1
'''
#calculating code segment ranges every time is wasteful
code_segs = []
for s in idautils.Segments():
if idaapi.segtype(s) == idaapi.SEG_CODE:
s_end = idc.GetSegmentAttr(s, SEGATTR_END)
code_segs.append({"start" : s, "end" : s_end})
if not reduce(lambda x, y: x or y, map(lambda x: (x["start"] <= ea) and (x["end"] > ea), code_segs)):
return False
'''
#this is-in-function check is enough (segment check redundant) if we trust function ID'ing anyway.
f_ea = idaapi.get_func(ea)
if not f_ea:
return False
#Preceding or Previous?
# Not necessarily all preceding will be a call to a ret instruction,
# but "the" prev should be always the one.
i = idautils.DecodePreviousInstruction(ea)
if i and "BL" in idc.GetMnem(i.ea):
return True
return False
def main():
print("[*] loading crypto constants")
for const in non_sparse_consts:
const["byte_array"] = convert_to_byte_array(const)
for start in idautils.Segments():
print("[*] searching for crypto constants in %s" % idc.get_segm_name(start))
ea = start
while ea < idc.get_segm_end(start):
bbbb = list(struct.unpack("BBBB", idc.get_bytes(ea, 4)))
for const in non_sparse_consts:
if bbbb != const["byte_array"][:4]:
continue
if map(lambda x:ord(x), get_bytes(ea, len(const["byte_array"]))) == const["byte_array"]:
print(("0x%0" + str(digits) + "X: found const array %s (used in %s)") % (ea, const["name"], const["algorithm"]))
idc.set_name(ea, const["name"])
if const["size"] == "B":
idc.create_byte(ea)
elif const["size"] == "L":
idc.create_dword(ea)
elif const["size"] == "Q":
idc.create_qword(ea)
make_array(ea, len(const["array"]))
ea += len(const["byte_array"]) - 4
break
ea += 4
ea = start
if get_segm_attr(ea, SEGATTR_TYPE) == 2:
while ea < get_segm_end(start):
d = ida_bytes.get_dword(ea)
for const in sparse_consts:
if d != const["array"][0]:
continue
tmp = ea + 4
for val in const["array"][1:]:
for i in range(8):
if ida_bytes.get_dword(tmp + i) == val:
tmp = tmp + i + 4
break
else:
break
else:
print(("0x%0" + str(digits) + "X: found sparse constants for %s") % (ea, const["algorithm"]))
cmt = idc.get_cmt(idc.prev_head(ea), 0)
if cmt:
idc.set_cmt(idc.prev_head(ea), cmt + ' ' + const["name"], 0)
else:
idc.set_cmt(idc.prev_head(ea), const["name"], 0)
ea = tmp
break
ea += 1
print("[*] finished")