Пример #1
0
def get_data(start, size):
    '''
    read the given amount of data from the given start address.
    better than `idc.GetManyBytes` as it fills in missing bytes with NULLs.

    Args:
      start (int): start address.
      size (int): number of bytes to read.

    Returns:
      bytes: `size` bytes, filled with NULL when byte not available from database.
    '''
    # best case, works pretty often.
    buf = idc.GetManyBytes(start, size)
    if buf:
        return buf

    # but may fail, when there's no byte defined.
    buf = []
    for ea in range(start, start + size):
        b = idc.GetManyBytes(ea, 1)
        if b:
            buf.append(b)
        else:
            buf.append(b'\x00')
    return b''.join(buf)
def find_unrefd_encoded_strings(encoded_string, delimiter=None):
    '''
    Description:
        Given a known EncodedString, find unreferenced encoded strings before the next ref.
        By default, the delimiter is the null terminator.
        The original EncodedString is not modified.

    Input:
        encoded_string - The EncodedString to start from
        delimiter - The character(s) to split on (default is null terminator)

    Output:
        A list of new EncodedStrings (not including the original)
    '''
    if delimiter is None:
        delimiter = '\x00\x00' if isinstance(encoded_string.decoded_string,
                                             unicode) else '\x00'

    results = []
    index = encoded_string.string_location + encoded_string.size

    while not list(idautils.XrefsTo(index, idaapi.XREF_ALL)):
        # Consume bytes while we continue to find the delimiter
        if idc.GetManyBytes(index, len(delimiter)) == delimiter:
            if len(delimiter) > 1:
                # if the delimiter is multiple bytes, we could have stepped over a ref
                # in the middle of the delimiter
                if any(
                        bool(list(idautils.XrefsTo(index +
                                                   i, idaapi.XREF_ALL)))
                        for i in xrange(len(delimiter))):
                    break
                else:
                    index += len(delimiter)
            else:
                index += len(delimiter)
        else:
            # For cases where the delimiter has repeated values (like unicode null),
            # step until the delimiter is right aligned
            while not list(idautils.XrefsTo(index, idaapi.XREF_ALL)) and \
                    idc.GetManyBytes(index + 1, len(delimiter)) == delimiter:
                index += 1
            # Technically we need to check this again to be super safe
            if list(idautils.XrefsTo(index, idaapi.XREF_ALL)):
                break
            start = index

            # Consume non-delimiter bytes until we encounter another delimiter or a ref
            index += 1
            while not list(idautils.XrefsTo(index, idaapi.XREF_ALL)) and \
                    idc.GetManyBytes(index, len(delimiter)) != delimiter:
                index += 1

            new_string = copy.copy(encoded_string)
            new_string.offset = start - encoded_string.string_location
            new_string.size = index - start
            new_string.get_bytes()
            results.append(new_string)

    return results
Пример #3
0
def get_rets(bb, end_address):

    for func in idautils.Functions():
        # Retrieve func
        curr_func = idaapi.get_func(func)

        # Get start address making sure to strip the trailing L
        if curr_func.startEA == bb.startEA:

            # This fails if the function is implemented outside (e.g. ntdll), so we need to catch the exception
            try:
                flowchart = idaapi.FlowChart(curr_func)
            except:
                #f.write("Implemented somewhere else\n")
                #f.write(name+"\n")
                return end_address

            for bb in flowchart:

                # Examine BBs with no successors
                if not list(bb.succs()):
                    #f.write("empty internal:"+hex(bb.startEA)+"\n")

                    bb_len = int(bb.endEA - bb.startEA)
                    if bb_len != 0:
                        # Fetch BB rawbytes
                        bb_bytes = idc.GetManyBytes(bb.startEA,
                                                    bb.endEA - bb.startEA)
                    else:
                        bb_bytes = idc.GetManyBytes(bb.startEA,
                                                    ItemSize(bb.startEA))

                    # Init Capstone
                    if get_number_of_bits() == 32:
                        md = Cs(CS_ARCH_X86, CS_MODE_32)
                        md.detail = True
                    else:
                        md = Cs(CS_ARCH_X86, CS_MODE_64)
                        md.detail = True

                    # Get last instruction of BB
                    ins = list(md.disasm(bb_bytes, bb.startEA))[-1]

                    # Dump ret address
                    if ins.mnemonic == "ret":
                        #f.write("INT -- 0x%x:\t%s\t%s\n" %(ins.address, ins.mnemonic, ins.op_str))
                        end_address["rets"].append(ins.address)

    return end_address
Пример #4
0
def _get_blocks_codes_per_func_iter():
    """
    Iterative function to generate all blocks and opcodes
    :return: N/A
    """
    all_blocks = {}
    all_codes = {}
    all_opcodes = []
    for func in idautils.Functions():
        # blocks_in_func contains
        #   <idaapi.BasicBlock object at 0x0545F3F0>, ...
        blocks_in_func = idaapi.FlowChart(idaapi.get_func(func))
        blocks = []
        for block in blocks_in_func:

            # IDA BUG! block.startEA == block.endEA??
            # Should be in the range "block.startEA <= block < block.endEA"
            if block.startEA != block.endEA:
                blocks.append((block.startEA, block.endEA))
            for head in idautils.Heads(block.startEA, block.endEA):
                ibytes = idc.GetManyBytes(head, idc.ItemEnd(head) - head)
                spd = idc.GetSpd(head)
                all_codes[head] = insn.Instruction(head, ibytes, spd)

                # IDA BUG! all_codes[head].bytes == 0??
                # The size of the code should be positive
                if all_codes[head].bytes != 0:
                    all_opcodes.append(
                        (all_codes[head].addr,
                         all_codes[head].addr + len(all_codes[head].bytes)))
        all_blocks[func] = blocks
    yield (all_blocks, all_opcodes)
Пример #5
0
def main():
    address = AskAddr(BADADDR, "Enter address: ")
    if address is None:
        # cancel
        return

    if address == BADADDR:
        print "Invalid address."
        return

    size = AskLong(0, "Enter size: ")
    if size is None:
        # cancel
        return

    if size == 0:
        print "Invalid size."
        return

    print "Range: ", hex(address), hex(size)

    buffer = idc.GetManyBytes(address, size, True)
    if buffer is not None:
        output_file = os.path.join(os.path.dirname(GetIdbPath()),
                                   "dump_%08x_%08x.dat" % (address, size))

        with open(output_file, "wb") as f:
            f.write(buffer)
            print "Saved data success", output_file
    def process(self, callback):
        if not self.nid_table:
            assert (not self.entry_table)
            return

        if not self.libname:
            self.libname = "{}_Syslib".format(self.module.name)

        nids = idc.GetManyBytes(self.nid_table, 4 * self.num_funcs)
        funcs = idc.GetManyBytes(self.entry_table, 4 * self.num_funcs)

        pairs = list(
            zip([u32(x) for x in chunk(nids, 4)],
                [u32(x) for x in chunk(funcs, 4)]))
        for nid, func in pairs:
            callback(self, func, nid)
Пример #7
0
	def MakeBundledAssemblyStruct(self, FileItemStructOffset):


		if self.Is64Bit == True:
			addv = 8
			mf = MakeQword
			vf = Qword
		else:
			mf = MakeDword
			addv = 4
			vf = Dword
	
		offset = FileItemStructOffset


	
		mf(offset)
		FileNameOffset = vf(offset)
		FileName = idc.GetString(FileNameOffset)
		offset+=addv
	
		mf(offset)
		FileDataOffset = vf(offset)
		offset+=addv
	
		mf(offset)
		FileSize = vf(offset)
		FileSizeOffset = offset
		offset+=addv
	
	
	
		mf(offset)
		FileCompressedSize = vf(offset)
		FileCompressedSizeOffset = offset
		offset+=addv
	
		IsGZip = ""
	
		FileDataCompressed = idc.GetManyBytes(FileDataOffset,3)
	
		b1,b2,b3 = struct.unpack('ccc', FileDataCompressed[0:3])
		if b1 == '\x1f' and b2 == '\x8b' and b3 == '\x08':
			IsGZip = "Y"
		else:
			IsGZip = "N"
	
		ba = BundledAssembly()
		ba.FileItemStructOffset = FileItemStructOffset
		ba.FileNameOffset = FileNameOffset
		ba.FileName = FileName
		ba.FileDataOffset = FileDataOffset
		ba.FileSize = FileSize
		ba.FileSizeOffset = FileSizeOffset
		ba.FileCompressedSizeOffset = FileCompressedSizeOffset
		ba.FileCompressedSize = FileCompressedSize
		ba.IsGZip = IsGZip
		#ba.FileDataCompressed = FileDataCompressed

		return ba
Пример #8
0
    def trace(self, ip):
        self.setup()
        while True:
            if len(self.instructions) > 1000:
                break
            op = idc.GetManyBytes(ip, idc.ItemSize(ip))

            prev_esp = self.tx.buildSymbolicRegister(
                self.tx.registers.esp).evaluate()

            ins = Instruction()
            ins.setOpcode(op)
            ins.setAddress(ip)
            self.tx.processing(ins)

            ins_id = self.add_instruction(ins, prev_esp)

            if self.debug:
                reads = " ".join(
                    map(lambda x: x.getName(), self.get_side_reads(ins)))
                writes = " ".join(
                    map(lambda x: x.getName(), self.get_side_writes(ins)))

                mem_writes = " ".join(
                    map(lambda x: "%08x" % x.getAddress(),
                        self.get_side_mem_writes(ins)))

                #print "%08x    [%03d]    %-30s %-20s %-20s %s" % (ip,ins_id,ins.getDisassembly(),reads,writes,self.instructions[-1]['state'])
                print "%08x    [%03d]    %-40s %-30s %-30s (mem writes: %s)" % (
                    ip, ins_id, ins.getDisassembly(), reads, writes,
                    mem_writes)

            next_ip = self.follow_flow()
            if not next_ip:
                break
            ip = next_ip

        good = self.extract_good()
        print "Good instructions: %s" % sorted(good)

        svar_lookup = dict()
        num = 0
        for i in sorted(good):
            esp = ""
            for op in self.instructions[i]['ins'].getOperands():
                if op.getType() == OPERAND.MEM and op.getBaseRegister(
                ).getName() == "esp":
                    esp = "%08x" % op.getAddress()

            line = "[%03d]    %s" % (
                i, self.instructions[i]['ins'].getDisassembly())
            if esp:
                line = re.sub(r"\[esp.*\]", "[%s]" % esp, line)
                if int(esp, 16) not in svar_lookup:
                    svar_lookup[int(esp, 16)] = "svar%d" % num
                    num += 1
                line = line.replace("[%s]" % esp,
                                    "[%s]" % svar_lookup[int(esp, 16)])

            print line
    def insert_module_chunks(self):
        ptr = self.last_module_ptr
        while ptr:
            mod = Module(idc.GetManyBytes(ptr, 0x400))
            self.modules.append(mod)

            ptr = mod.prev
Пример #10
0
def handle_mov(ea, state):
    """Updates the stack based on a mov instruction. Used by create_stack

        :param ea: instruction location
        :param state: the current TraceState

        :return: None - updates stack or regs
    """
    op1 = get_opnd_replacement(ea, POS_FIRST)
    if idc.GetOpType(ea, POS_FIRST) != idc.o_reg:
        offset = get_operand_value_replacement(ea, POS_FIRST, state)
        set_stack(offset, ea, POS_SECOND, state)
    else:
        type_ = idc.GetOpType(ea, POS_SECOND)
        val = None
        if type_ == idc.o_reg:
            val = state.get_reg_value(get_opnd_replacement(ea, POS_SECOND))
        elif type_ == idc.o_mem:
            bytes = idc.GetManyBytes(idc.GetOperandValue(ea, POS_SECOND),
                                     get_byte_size_of_operand(ea, POS_SECOND))
            if bytes:
                val = 0
                for x in range(len(bytes)):
                    val += ord(bytes[x]) << (8 * x)
        elif type_ == idc.o_imm:
            val = idc.GetOperandValue(ea, POS_SECOND)
        else:
            offset = get_operand_value_replacement(ea, POS_SECOND, state)
            val, ea = state.stack.get(offset, (None, ea))
        state.set_reg_value(op1, val, ea)
Пример #11
0
def main(ea):
  # Get Function Bytes
  start = idc.GetFunctionAttr(ea, FUNCATTR_START)
  end = idc.GetFunctionAttr(ea, FUNCATTR_END)
  length = end - start
  code = ""
  for byte in idc.GetManyBytes(start, length):
  	 code += byte

  # Determine Architecture
  info = idaapi.get_inf_structure()
  proc = info.procName

  if info.is_64bit():
    if proc == "metapc":
      md = Cs(CS_ARCH_X86, CS_MODE_64)
    elif proc == "ARM":
      md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
  elif info.is_32bit():
    if proc == "metapc":
      md = Cs(CS_ARCH_X86, CS_MODE_32)
    elif proc == "ARM":
      md = Cs(CS_ARCH_ARM, CS_MODE_ARM) # If need change: CS_MODE_THUMB

  # Disassemble with Capstone and print
  for i in md.disasm(code, start):
    try:
      db = ""
      for ba in i.bytes:
        db += str("%X " %(ba)).rjust(3, "0")
      print("%x:\t%s\t%s\t%s" %(i.address, str(db).ljust(24, " "), i.mnemonic, i.op_str))
    except Exception as e:
      print "Exception: {}".format(e)
Пример #12
0
def ExecuteSymbolicSingleStep(addr, state=INIT_REG):
    size = idc.ItemSize(addr)
    code = idc.GetManyBytes(addr, size)
    loc_db = LocationDB()

    base = addr
    try:
        ins = mn_x86.dis(bin_stream_str(code, base_address=base), 64, base)
    except:
        return state.copy()

    ira = machine.ira(loc_db)
    ircfg = ira.new_ircfg()
    try:
        ira.add_instr_to_ircfg(ins, ircfg)
        sb = SymbolicExecutionEngine(ira, state)
        symbolic_pc = sb.run_at(ircfg, base)
    except:
        return state.copy()
    ret = state.copy()
    for key, value in sb.modified():
        if isinstance(value, ExprOp) and value.op == "call_func_ret":
            value = ExprInt(0, 64)
        ret[key] = value
    return ret
Пример #13
0
def copy_bytes():
    """
    Copy selected bytes to clipboard
    """
    if using_ida7api:
        start = idc.read_selection_start()
        end = idc.read_selection_end()
        if idaapi.BADADDR in (start, end):
            ea = idc.here()
            start = idaapi.get_item_head(ea)
            end = idaapi.get_item_end(ea)
        # # reference https://stackoverflow.com/questions/6624453/whats-the-correct-way-to-convert-bytes-to-a-hex-string-in-python-3
        data = idc.get_bytes(start, end - start).hex()
        print("Bytes copied: %s" % data)
        copy_to_clip(data)
    else:
        start = idc.SelStart()
        end = idc.SelEnd()
        if idaapi.BADADDR in (start, end):
            ea = idc.here()
            start = idaapi.get_item_head(ea)
            end = idaapi.get_item_end(ea)
        # reference https://stackoverflow.com/questions/6624453/whats-the-correct-way-to-convert-bytes-to-a-hex-string-in-python-3
        # not work in ida7.5 python3.7.7
        # data = idc.GetManyBytes(start, end-start).encode('hex')
        data = idc.GetManyBytes(start, end - start).hex()
        print("Bytes copied: %s" % data)
        copy_to_clip(data)
    return
Пример #14
0
    def parse_handler(ea, capstone_instance):
        """
            Search in handler instruction ID
            :param ea: Address of call handler
            :param capstone_instance: Instance of capstone disassembler
            :return: Instruction ID or None

        """
        i = ea
        jmp_id = None
        while True:

            bytes_mi = idc.GetManyBytes(i, Instruction.max_instruction_size)
            mi = list(capstone_instance.disasm(bytes_mi, 0))[0]
            if mi.mnemonic in Instruction.branching_mnemonics:
                break
            elif mi.mnemonic.lower() == "push":
                m = re.search("0x([ABCDEFabcdef0-9]+)", str(mi.op_str))
                if m:
                    if int(m.group(1), 16) > 0xffffff:
                        jmp_id = int(m.group(1), 16)
                        break
            i += mi.size

        return jmp_id
Пример #15
0
def find_WdfDeviceCreateDeviceInterface():
    function_offset = OFFSET_WdfDeviceCreateDeviceInterface

    calls_to_pfn_list = []
    try:
        for xref in idautils.XrefsTo(g_vars["_WDFFUNCTIONS"]+function_offset):
            call_pfnWdfDeviceCreateDeviceInterface = xref.frm
            calls_to_pfn_list.append(call_pfnWdfDeviceCreateDeviceInterface)
    except StopIteration:
        # this is case 2 or 3
        pass
    if len(calls_to_pfn_list) == 0:
        call_pfnWdfDeviceCreateDeviceInterface = find_wdf_callback_through_immediate("call", 0, function_offset)
        if call_pfnWdfDeviceCreateDeviceInterface:
            calls_to_pfn_list.append(call_pfnWdfDeviceCreateDeviceInterface)
            idc.OpStroffEx(call_pfnWdfDeviceCreateDeviceInterface,0,(idaapi.get_struc_id("_WDFFUNCTIONS")),0)

    if len(calls_to_pfn_list) == 0:
        call_pfnWdfDeviceCreateDeviceInterface = find_wdf_callback_through_immediate("mov", 1,function_offset)
        if call_pfnWdfDeviceCreateDeviceInterface:
            calls_to_pfn_list.append(call_pfnWdfDeviceCreateDeviceInterface)
            idc.OpStroffEx(call_pfnWdfDeviceCreateDeviceInterface,1,(idaapi.get_struc_id("_WDFFUNCTIONS")),0)

    for k, pfn_call in enumerate(calls_to_pfn_list):
        lea_guid = find_function_arg(pfn_call, "lea", "r8", 0)
        interface_guid = idc.GetOperandValue(lea_guid, 1)
        idc.MakeName(interface_guid, '_InterfaceGUID' + str(k))
        assign_struct_to_address(interface_guid, "GUID")
        g_vars["_InterfaceGUID" + str(k)] = interface_guid
        print("_InterfaceGUID: ", hex(interface_guid))
        guid_bytes = idc.GetManyBytes(interface_guid, 0x10)
        print_guid(guid_bytes)
def ida_functionprefix(fun):
    """Returns the first eighteen bytes of a function as ASCII."""
    B = bytearray(idc.GetManyBytes(adr, Symgrate2.SEARCHLEN))
    bstr = ""
    for b in B:
        bstr += "%02x" % (0x00FF & b)
    return bstr
Пример #17
0
 def run(self,arg):
     identified_func={}
     for func_ea in idautils.Functions():
         #get the function name
         function_name=idc.GetFunctionName(func_ea)
         print function_name
         if not function_name.startswith("sub_"):
             continue
         func_byteStr32=""
         func_str=idc.GetManyBytes(func_ea, 32)
         for fb in func_str:
             byte_str=binascii.b2a_hex(fb)
             func_byteStr32+=byte_str
         print func_byteStr32
         match_result=nampa.match_function(sig,func_byteStr32)
         print match_result
         if match_result[0]:
             function_names=''
             for function_name in match_result[1]:
                 if len(function_names)==0:
                     function_names=function_name
                     continue
                 function_names=function_names+"_"+function_name
                 #set the function name
             num=0
             print identified_func
             if identified_func.has_key(function_names):
                 num=identified_func[function_names]
                 num+=1
                 identified_func[function_names]=num
             else:
                 identified_func[function_names]=num
             function_names=function_names+str(num)
             idc.MakeName(func_ea,function_names)
     warning("Ida plugin run(%d) called.\n"%arg)
Пример #18
0
 def decode_here_clicked(self):
     inst = idc.here()
     if not idc.isCode(idc.GetFlags(inst)):
         print "Not code instruction"
     else:
         raw = idc.GetManyBytes(inst, idc.NextHead(inst) - inst)
         s = to_hex(raw)
         self.decode_ir(s)
Пример #19
0
 def getData(self):
     #获取起始地址和结束地址之间的数据,并将它们存入object.buffer中
     self.ogLen = self.end - self.start
     self.buffer = ''
     try:
         for byte in idc.GetManyBytes(self.start, self.ogLen):
             self.buffer = self.buffer + byte
     except:
         self.start = False
     return
Пример #20
0
    def refreshitems(self):

        # Pb : rop engine has not been init
        if self.idarop.rop == None:
            return

        # No new data present
        if self.rop_list_cache == self.idarop.rop.gadgets:
            return

        self.items = []

        # No data present
        if len(self.idarop.rop.gadgets) == 0:
            return

        if len(self.idarop.rop.gadgets) > 10000:
            idaapi.show_wait_box("Ida rop : loading rop list ...")

        for i, g in enumerate(self.idarop.rop.gadgets):

            # reconstruct disas
            if g.opcodes == "":

                bad_gadget = False
                opcodes = idc.GetManyBytes(g.address,
                                           g.ret_address - g.address + 1)
                instructions = list()
                ea = g.address
                while ea <= g.ret_address:
                    instructions.append(
                        idc.GetDisasmEx(ea, idaapi.GENDSM_FORCE_CODE))
                    ea += idaapi.decode_insn(ea)

                    # Badly decoded gadget
                    if idaapi.decode_insn(ea) == 0:
                        bad_gadget = True
                        break

                if not bad_gadget:
                    h = Gadget(address=g.address,
                               ret_address=g.ret_address,
                               instructions=instructions,
                               opcodes=opcodes,
                               size=len(opcodes))
                    self.idarop.rop.gadgets[i] = h

                    self.items.append(
                        h.get_display_list(self.idarop.addr_format))
            else:
                self.items.append(g.get_display_list(self.idarop.addr_format))

        self.rop_list_cache = self.idarop.rop.gadgets
        if len(self.idarop.rop.gadgets) > 10000:
            idaapi.hide_wait_box()
 def _parse_arr(self, start, end, cls):
     out = []
     x = start
     while x < end:
         sz = idc.Byte(x)
         data = idc.GetManyBytes(x, sz)
         c = cls(data)
         c.module = self
         out.append(c)
         x += sz
     return out
Пример #22
0
def is_jmp_next(ea):
    (short, off) = is_short_jmp(ea)
    if short:
        b = idc.Byte(ea + off)
        return b == 0x00
    else:
        s = idc.GetManyBytes(
            ea + off, 4
        )  #Byte() returns int, but GetManyBytes a string. consistency FTW ;p
        return s == "\0\0\0\0"
    assert (False)
Пример #23
0
	def DecompressFileTo(self, FileItem,OutputDir):
		
		newpath = '{}\\{}'.format(OutputDir, FileItem.FileName)

		FileDataCompressed = idc.GetManyBytes(FileItem.FileDataOffset,FileItem.FileCompressedSize)


		if FileItem.IsGZip == "Y":
			self.DecompressGzipTo(FileDataCompressed,newpath)
		else:
			self.DecompressZLib(FileDataCompressed,newpath)
Пример #24
0
    def get_padded_bytes(self, size):
        result = "\x00" * size
        ranges_left = [MemoryRange(self.address, self.address + size)]

        segment_count = idaapi.get_segm_qty()
        valid_memory_ranges = []
        for i in range(segment_count):
            segment = idaapi.getnseg(i)
            # Skip segments with unstable data
            if segment.type == idaapi.SEG_XTRN:
                continue
            valid_memory_ranges.append(
                MemoryRange(segment.startEA, segment.endEA))

        while len(ranges_left) > 0:
            # Get a requested memory range and remove it from the list
            current_range = ranges_left.pop()

            intersection = None
            for memory_range in valid_memory_ranges:
                start = max(current_range.start, memory_range.start)
                end = min(current_range.end, memory_range.end)
                if end > start:
                    intersection = MemoryRange(start, end)
                    break

            # No segment can satisfy any part of requested range
            if intersection is None:
                continue

            chunk = idc.GetManyBytes(intersection.start,
                                     intersection.end - intersection.start)
            if chunk is None:
                print(
                    '[librgb] Some bytes are unreadable in %s..%s' %
                    (idc.atoa(intersection.start), idc.atoa(intersection.end)))
                continue

            result = \
                result[0:intersection.start - self.address] \
                + chunk \
                + result[intersection.end - self.address:]
            assert len(result) == size

            # If necessary, enqueue ranges unsatisfied by chosen mem segment
            range1 = MemoryRange(current_range.start, intersection.start)
            range2 = MemoryRange(intersection.end, current_range.end)
            if range1.length > 0:
                ranges_left.append(range1)
            if range2.length > 0:
                ranges_left.append(range2)

        assert len(result) == size
        return result
Пример #25
0
def DumpProtoBin(root_dir, file_name, data, length):
    data = idc.GetManyBytes(data, length)

    full_file_name = os.path.join(root_dir, file_name + "bin")
    directory = os.path.dirname(full_file_name)

    if not os.path.exists(directory):
        os.makedirs(directory)

    file = open(full_file_name, "wb")
    file.write(data)
    file.close()
Пример #26
0
	def DecompressFileTo(self, FileItem,OutputDir):
		
		if FileItem.IsME == "Y":
			extname = ".ME"
		else:
			extname = ""

		newpath = '{}\\{}{}'.format(OutputDir, FileItem.FileName, extname)

		if FileItem.IsCompressed == "Y":
			FileDataCompressed = idc.GetManyBytes(FileItem.FileDataOffset,FileItem.FileCompressedSize)
			if FileItem.IsGZip == "Y":
				self.DecompressGzipTo(FileDataCompressed,newpath)
			else:
				self.DecompressZLib(FileDataCompressed,newpath)
		else:
			FileData = idc.GetManyBytes(FileItem.FileDataOffset,FileItem.FileSize)
			f = open(newpath, 'wb')
			f.write(FileData)
			f.close()
			pass
Пример #27
0
def get_segment_buffer(segstart):
    '''
    fetch the bytes of the section that starts at the given address.
    if the entire section cannot be accessed, try smaller regions until it works.
    '''
    segend = idaapi.getseg(segstart).endEA
    buf = None
    segsize = segend - segstart
    while buf is None:
        buf = idc.GetManyBytes(segstart, segsize - 1)
        if buf is None:
            segsize -= 0x1000
    return buf
Пример #28
0
def get_code_and_blocks(ea):
    """Extracts the control flow graph for the function at the given address.
  Returns a dictionary with the instructions (ea->insn.Instruction) and a list
  of the basic blocs (bbl.BasicBlock)."""

    code = {}
    blocks = {}
    ida_blocks = set(idaapi.FlowChart(idaapi.get_func(ea)))

    for bb in ida_blocks:

        # XXX: it seems that it's not a bug but inter-function jumps!
        if bb.startEA == bb.endEA:  # skip that .. it's IDA's bug
            #print "skipping block %x : %x in func %x"%(bb.startEA, bb.endEA, ea)
            continue

        blocks[bb.startEA] = bbl.BasicBlock(bb.startEA, bb.endEA, {})

        for head in idautils.Heads(bb.startEA, bb.endEA):
            ibytes = idc.GetManyBytes(head, idc.ItemEnd(head) - head)
            spd = idc.GetSpd(head)
            code[head] = insn.Instruction(head, ibytes, spd)
            blocks[bb.startEA].instrs.append(code[head])
            next_head = idc.NextHead(head, bb.endEA)

            if idaapi.isFlow(idc.GetFlags(next_head)):
                code[head].succ.add(next_head)

        for suc_bb in (s for s in bb.succs() if s.startEA != s.endEA):
            #assume head is the last instruction of the block
            code[head].succ.add(suc_bb.startEA)

    for bb in (b for b in ida_blocks if b.startEA != b.endEA):
        for suc_bb in (s for s in bb.succs() if s.startEA != s.endEA):
            # a jump with zero offset (like, jz 0) gives two succs to the same bb
            if blocks[suc_bb.startEA] not in blocks[bb.startEA].successors:
                blocks[bb.startEA].successors.append(blocks[suc_bb.startEA])
        blocks[bb.startEA].successors.sort(key=lambda x: x.begin, reverse=True)

    #FIXME: find a better way ..
    for block in blocks.itervalues():
        if block.instrs[0].addr == ea:
            #print "found the entry!:", block.instrs
            block.instrs[0].f_entry = True
            block.type |= bbl.BasicBlock.ENTRY
            break
    else:
        print "BUG: could not find function entry in instrs!!"
    #print "blocks:", blocks

    return code, blocks.values()
Пример #29
0
def _get_func_data(func_addr):
    """
    Get function's data
    """
    logger.debug('_get_func_data: {}'.format(func_addr))
    func_length = _get_func_length(func_addr)
    if func_length is None:
        return None
    func_data = idc.GetManyBytes(func_addr, func_length)
    if func_data is None:
        return None
        # raise FCatalogClientError('Failed reading function {:X} data'.\
        #        format(func_addr))

    return str(func_data)
Пример #30
0
 def get_segments(self):
     if len(self.segments) == 0:
         for seg in idautils.Segments():
             name = idc.SegName(seg)
             start = idc.SegStart(seg)
             end = idc.SegEnd(seg)
             d = idc.GetManyBytes(start, end - start)
             d = [ord(item) for item in list(d)]
             seg_data = {
                 "name": name,
                 "start": start,
                 "end": end,
                 "data": d
             }
             self.segments.append(seg_data)
     return self.segments