Example #1
0
def get_virtual_func_address(name, tinfo=None, offset=None):
    """
    :param name: method name
    :param tinfo: class tinfo
    :param offset: virtual table offset
    :return: address of the method
    """
    # address = idaapi.BADADDR
    # if name in idautils.Functions():
    address = idc.LocByName(name) #f*****g idaapi. It's function work incorrectly. This returned 0xFF005BE7 instead BADADDR in some cases. get_name_ea problem.

    if address != idaapi.BADADDR:
        return address

    address = Cache.demangled_names.get(name, idaapi.BADADDR)
    if address != idaapi.BADADDR:
        return address + idaapi.get_imagebase()

    if tinfo is None or offset is None:
        return

    offset *= 8
    udt_member = idaapi.udt_member_t()
    while tinfo.is_struct():
        address = Cache.demangled_names.get(tinfo.dstr() + '::' + name, idaapi.BADADDR)
        if address != idaapi.BADADDR:
            return address + idaapi.get_imagebase()
        udt_member.offset = offset
        tinfo.find_udt_member(idaapi.STRMEM_OFFSET, udt_member)
        tinfo = udt_member.type
        offset = offset - udt_member.offset
Example #2
0
File: ui.py Project: r0mpage/idarop
    def load_internal_db(self, force=False):
        """ Load the rop gadgets list from the internal db """

        if self.blob_manager == None:
            return

        internal_repr = self.blob_manager["db"].split(";")
        if internal_repr == None:
            return

        for item in internal_repr:
            offset, ret_offset = item.split(':')

            # Reconstruct linear address based on binary base address and offset
            address = int(offset, 16) + idaapi.get_imagebase()
            ret_address = int(ret_offset, 16) + idaapi.get_imagebase()

            gadget = Gadget(address=address,
                            ret_address=ret_address,
                            instructions=list(),
                            opcodes="",
                            size=0)

            self.engine.rop.gadgets.append(gadget)

            if idaapi.wasBreak():
                print("[IdaRopLoad] Load csv file interrupted.")
                break
Example #3
0
def NameToRVA(s):
    addr = LocByName(s)
    if addr == ERROR_MINUS_1:
        print("[ida_helper] Error: NameToRVA: Failed to find '%s' symbol" % s)
        return None
    print("[ida_helper] image base 0x%x" % idaapi.get_imagebase())
    return addr - idaapi.get_imagebase()
Example #4
0
def MakeEnum(enumName, offsetArray):
    print("enum class %s\r\n{" % enumName)
    for offset in offsetArray:
        if len(offset[0]) == 0:
            print("")
            continue
        if type(offset[1]) is str:
            print("   %s = %s," % (offset[0], offset[1]))
            continue

        fncValue = offset[1] if offset[1] != -1 else 0x0

        locByName = idc.get_name_ea_simple(offset[0])
        isMismatch = locByName == 0x0

        if locByName == BADADDR:
            locByName = fncValue

        if locByName > idaapi.get_imagebase():
            set_name(locByName, offset[0])
            locByName = locByName - idaapi.get_imagebase()

        print("   %s = %s,%s" % (offset[0], hex(locByName),
                                 '// Possible mismatch' if isMismatch else ''))

    print("};\r\n")
Example #5
0
def get_virtual_func_address(name, tinfo=None, offset=None):
    """
    :param name: method name
    :param tinfo: class tinfo
    :param offset: virtual table offset
    :return: address of the method
    """

    address = idc.LocByName(name)
    if address != idaapi.BADADDR:
        return address

    address = demangled_names.get(name, idaapi.BADADDR)
    if address != idaapi.BADADDR:
        return address + idaapi.get_imagebase()

    if tinfo is None or offset is None:
        return

    offset *= 8
    udt_member = idaapi.udt_member_t()
    while tinfo.is_struct():
        address = demangled_names.get(tinfo.dstr() + '::' + name,
                                      idaapi.BADADDR)
        if address != idaapi.BADADDR:
            return address + idaapi.get_imagebase()
        udt_member.offset = offset
        tinfo.find_udt_member(idaapi.STRMEM_OFFSET, udt_member)
        tinfo = udt_member.type
        offset = offset - udt_member.offset
Example #6
0
File: ui.py Project: r0mpage/idarop
    def save_internal_db(self):
        """ store the found rop gadget in the default internal db """

        if len(self.engine.rop.gadgets) == 0 or self.blob_manager == None:
            return

        cancel_flag = False
        internal_repr = list()
        for item in self.engine.rop.gadgets:

            address, ret_addres = item.address, item.ret_address
            offset = "0x%x" % (address - idaapi.get_imagebase())
            ret_offset = "0x%x" % (ret_addres - idaapi.get_imagebase())

            internal_repr.append((offset, ret_offset))

            if idaapi.wasBreak():
                cancel_flag = True
                print("[IdaRop] save internal db interrupted.")
                break

        # save only on success
        if not cancel_flag:
            txt_repr = ";".join("%s:%s" % (g[0], g[1]) for g in internal_repr)
            self.blob_manager["db"] = txt_repr
Example #7
0
def name_to_rva(s):
    addr = get_name_ea_simple(s)
    if addr == ERROR_MINUS_1:
        logmsg("Error: name_to_rva: Failed to find '%s' symbol" % s)
        return None
    logmsg("image base 0x%x" % idaapi.get_imagebase())
    return addr - idaapi.get_imagebase()
Example #8
0
 def check_vals(self):
     visual_style.set_alarmed_if(self.addr_edit,
                                 self.addr < idaapi.get_imagebase())
     visual_style.set_alarmed_if(self.length_edit, self.length <= 0)
     visual_style.set_alarmed_if(self.filename_edit, not self.filename)
     is_ok = bool(self.addr >= idaapi.get_imagebase() and self.length > 0
                  and self.filename)
     self.ok_btn.setEnabled(is_ok)
     print "idaapi getimage base %s" % idaapi.get_imagebase()
     print "addr %s" % self.addr
     print "length %s" % self.length
     print "filename %s" % self.filename
Example #9
0
    def ida_hook_rebase(self, meta, post=False):
        """function hook for IDA "RebaseProgram" action

        called twice, once before action and once after action completes

        @param meta: dict of key/value pairs set when action first called (may be empty)
        @param post: False if action first call, True if action second call
        """
        if post:
            if idaapi.get_imagebase() != meta.get("prev_base", -1):
                capa.ida.helpers.inform_user_ida_ui("Running capa analysis again after program rebase")
                self.slot_analyze()
        else:
            meta["prev_base"] = idaapi.get_imagebase()
            self.model_data.reset()
Example #10
0
def _get_service_table_info():
    name = GetInputFile().lower()
    if name not in SERVICE_TABLE_NAME_SYMBOL_MAP:
        return None

    stride = 8
    table_name, limit_name = SERVICE_TABLE_NAME_SYMBOL_MAP[name]
    table_address = LocByName(table_name)
    if table_address == BADADDR:
        table_name = '_' + table_name
        limit_name = '_' + limit_name
        table_address = LocByName(table_name)
        stride = 4
        if table_address == BADADDR:
            print 'table address failure'
            return None

    limit_address = LocByName(limit_name)
    limit = Dword(limit_address)
    base_id = SERVICE_TABLE_NAME_BASE_MAP[name]
    offset_base = 0

    if stride == 8:
        for x in DataRefsFrom(table_address):
            # Ideally we would test out the reference here
            # There is a chance IDA made a mistake as it seems to treat the
            # contents of the table as code when it contains 4-byte offsets
            break

        else:
            stride  = 4
            offset_base = get_imagebase()

    return table_address, limit, stride, base_id, offset_base
Example #11
0
    def export(self):
        image_name = idc.GetInputFile()
        self.image_base = idaapi.get_imagebase()

        self.filename = "%s.db" % (image_name)

        datadir = os.path.join(RECOVERER_PATH, "data")
        if not os.path.exists(datadir):
            os.mkdir(datadir)

        self.filename = os.path.join(datadir, self.filename)

        if os.path.exists(self.filename):
            info("File %s exists, overwriting." % (self.filename))
        else:
            info("Creating database at %s." % (self.filename))

        self.fd = open(self.filename, "w")

        self.fd.write("IMAGE_BASE;0x%x\n" % (self.image_base))
        self.fd.write("IMAGE_NAME;%s\n" % (image_name))
        self.__export_functions__()
        self.__export_imports__()

        self.fd.close()
Example #12
0
 def __init__(self, parser):
     self.color = False
     self.prev_loc = None
     self.prev_node = None
     self.name = idaapi.get_root_filename()
     print "[sync] name %s" % self.name
     self.base = idaapi.get_imagebase()
     print "[sync] module base 0x%x" % self.base
     self.base_remote = None
     self.gm = GraphManager()
     self.parser = parser
     self.broker_sock = None
     self.is_active = False
     self.dbg_dialect = None
     self.req_handlers = {
         "broker": self.req_broker,
         "loc": self.req_loc,
         "cmd": self.req_cmd,
         "cmt": self.req_cmt,
         "rcmt": self.req_rcmt,
         "fcmt": self.req_fcmt,
         "raddr": self.req_raddr,
         "rln": self.req_rln,
         "lbl": self.req_lbl,
         "bc": self.req_bc,
         "bps_get": self.req_bps_get,
         "bps_set": self.req_bps_set,
         "modcheck": self.req_modcheck,
         "dialect": self.req_set_dbg_dialect,
     }
Example #13
0
 def __init__(self, parser, form):
     self.form = form
     self.color = False
     self.prev_loc = None
     self.prev_node = None
     self.name = idaapi.get_root_filename()
     print "[sync] name %s" % self.name
     self.base = idaapi.get_imagebase()
     print "[sync] module base 0x%x" % self.base
     self.base_remote = None
     self.gm = GraphManager()
     self.parser = parser
     self.broker_sock = None
     self.is_active = False
     self.dbg_dialect = None
     self.req_handlers = {
         'broker': self.req_broker,
         'loc': self.req_loc,
         'cmd': self.req_cmd,
         'cmt': self.req_cmt,
         'rcmt': self.req_rcmt,
         'fcmt': self.req_fcmt,
         'raddr': self.req_raddr,
         'rln': self.req_rln,
         'lbl': self.req_lbl,
         'bc': self.req_bc,
         'bps_get': self.req_bps_get,
         'bps_set': self.req_bps_set,
         'modcheck': self.req_modcheck,
         'dialect': self.req_set_dbg_dialect
     }
Example #14
0
def collect_metadata():
    md5 = idautils.GetInputFileMD5()
    if not isinstance(md5, six.string_types):
        md5 = capa.features.bytes_to_str(md5)

    sha256 = idaapi.retrieve_input_file_sha256()
    if not isinstance(sha256, six.string_types):
        sha256 = capa.features.bytes_to_str(sha256)

    return {
        "timestamp": datetime.datetime.now().isoformat(),
        # "argv" is not relevant here
        "sample": {
            "md5": md5,
            "sha1": "",  # not easily accessible
            "sha256": sha256,
            "path": idaapi.get_input_file_path(),
        },
        "analysis": {
            "format": idaapi.get_file_type_name(),
            "extractor": "ida",
            "base_address": idaapi.get_imagebase(),
        },
        "version": capa.version.__version__,
    }
Example #15
0
 def __init__(self, parser):
     self.color = False
     self.prev_loc = None
     self.prev_node = None
     self.name = idaapi.get_root_filename()
     self.base = idaapi.get_imagebase()
     rs_log("module base 0x%x" % self.base)
     self.base_remote = None
     self.gm = GraphManager()
     self.hexsync = Syncrays()
     self.parser = parser
     self.broker_sock = None
     self.is_active = False
     self.dbg_dialect = None
     self.req_handlers = {
         'broker': self.req_broker,
         'loc': self.req_loc,
         'cmd': self.req_cmd,
         'cmt': self.req_cmt,
         'rcmt': self.req_rcmt,
         'fcmt': self.req_fcmt,
         'raddr': self.req_raddr,
         'rbase': self.req_rbase,
         'cursor': self.req_cursor,
         'patch': self.req_patch,
         'rln': self.req_rln,
         'rrln': self.req_rrln,
         'lbl': self.req_lbl,
         'bc': self.req_bc,
         'bps_get': self.req_bps_get,
         'bps_set': self.req_bps_set,
         'modcheck': self.req_modcheck,
         'dialect': self.req_set_dbg_dialect
     }
     self.prev_req = ""  # used as a cache if json is not completely received
Example #16
0
def collect_metadata():
    """ """
    md5 = get_file_md5()
    sha256 = get_file_sha256()

    return {
        "timestamp": datetime.datetime.now().isoformat(),
        # "argv" is not relevant here
        "sample": {
            "md5": md5,
            "sha1": "",  # not easily accessible
            "sha256": sha256,
            "path": idaapi.get_input_file_path(),
        },
        "analysis": {
            "format": idaapi.get_file_type_name(),
            "extractor": "ida",
            "base_address": idaapi.get_imagebase(),
            "layout": {
                # this is updated after capabilities have been collected.
                # will look like:
                #
                # "functions": { 0x401000: { "matched_basic_blocks": [ 0x401000, 0x401005, ... ] }, ... }
            },
        },
        "version": capa.version.__version__,
    }
Example #17
0
def find_bbls(function_ea):
    '''
        yields all basic blocks that belong to the
        given function. The blocks are returned in
        a 2-tuple like:

            (start_address, end_address)

        Both start and end address are RELATIVE offsets
        from the image base.
    '''

    # get image base from IDA
    image_base = idaapi.get_imagebase()
    function_ea += image_base

    # get flow chart from IDA
    flow_chart = idaapi.FlowChart(idaapi.get_func(function_ea),
                                  flags=idaapi.FC_PREDS)

    # iterate through all basic blocks in
    # the current routine
    for block in flow_chart:
        start_addr = block.startEA - image_base
        end_addr = block.endEA - image_base
        if start_addr != end_addr:
            yield start_addr, end_addr
Example #18
0
 def __init__(self, dotnet_version):
     self.dotnet_version = dotnet_version
     self.imagebase = idaapi.get_imagebase()
     self.module_header_struct = idaapi.get_segm_by_name(".rdata").start_ea
     self.nb_custom_modules = idaapi.get_dword(self.module_header_struct + \
                              dotnet_versions_offsets[self.dotnet_version]\
                              ["nbCustomModules"])
Example #19
0
def main():
    idaapi.auto_wait()
    base = idaapi.get_imagebase()
    tif = idaapi.tinfo_t()

    f = open(os.environ.get("DESTPATH", "functype_"), 'w')

    for ea in Segments():
        # only code segment
        if idaapi.segtype(ea) != idaapi.SEG_CODE:
            continue

        for fva in Functions(get_segm_start(ea), get_segm_end(ea)):
            func_name = get_func_name(fva)
            has_type = idaapi.get_tinfo(tif, fva) or idaapi.guess_tinfo(
                tif, fva)

            if not has_type:
                continue

            info = serialize(tif)
            if info is None:
                continue

            print(
                hex(fva - base)[:-1], "|", func_name, "|", tif, "|",
                len(info['args']))
            f.write("0x%x|%s|%s\n" % (fva - base, func_name, json.dumps(info)))

    f.close()
    idaapi.qexit(0)
Example #20
0
def main():
        clist = build_color_list();
        
	filepath = idaapi.askfile_c(False, "*.*", "Pin log file");
	imagebase = idaapi.get_imagebase();
	try:
		f = open(filepath, "rb");
	except:
		print("Need log file to parse data...");
		return;
	buff = f.read();
	functions = set()
	for index in range(0, len(buff)):
		exec_count = ord(buff[index]);
		if exec_count == 0:
			continue;
		
		exec_count = exec_count / 10;
		if exec_count > 11: exec_count = 11;
		        
		ida_color = clist[exec_count];
		if (not (idc.GetFunctionName(imagebase+index) in functions)):
                        func = idc.GetFunctionName(imagebase+index)
                        print "hit @ 0x%08x function %s"%(imagebase+index, func)
                        functions.add(func)
                
		

		idc.SetColor(imagebase + index, CIC_ITEM, ida_color);
Example #21
0
    def m32_mmpagingfile(self):
        """
        The MmPagingFile pointer can be defined as PVOID *MMPAGING_FILE[16]. Support for locating this
        pointer is not mandatory, but essential to verify if an MMPAGING_FILE structure corresponds
        to a virtual store. Although this pointer was previously exported as nt!MmPagingFile in Windows
        7, the pointer has not been exported by any Windows 10 kernel to date. This function traverses
        MiVaIsPageFileHash and stops at the first instance of an memory dereference by index. The
        signature appears to be fragile but has worked from 1607-1809. Disassembly snippet from
        Windows 10 1809 x86 shown below.

        MiVaIsPageFileHash(x,x)      _MiVaIsPageFileHash@8 proc near         ;
        MiVaIsPageFileHash(x,x)                      mov     edi, edi
        MiVaIsPageFileHash(x,x)+2                    push    ebx
        MiVaIsPageFileHash(x,x)+3                    push    esi
        MiVaIsPageFileHash(x,x)+4                    push    edi
        MiVaIsPageFileHash(x,x)+5                    mov     edi, Count
        MiVaIsPageFileHash(x,x)+B                    xor     ecx, ecx
        MiVaIsPageFileHash(x,x)+D                    mov     ebx, edx
        MiVaIsPageFileHash(x,x)+F                    test    edi, edi
        MiVaIsPageFileHash(x,x)+11                   jnz     short loc_4DC5C7
        MiVaIsPageFileHash(x,x)+19   loc_4DC5C7:                             ;
        MiVaIsPageFileHash(x,x)+19                   mov     esi, dword_6A8614[ecx*4]
        """
        (addr, name) = self.find_ida_name("MiVaIsPageFileHash")

        for insn_addr, insn, op0, op1 in self.iter_fn(addr):
            if "*4]" in op1:
                return idc.get_operand_value(insn_addr,
                                             1) - idaapi.get_imagebase()

        self.logger.error("MmPagingFile could not be resolved.")
        return None
Example #22
0
def main():
    disas_path = idc.AskFile(1, '*.disas', 'Save basic blocks')
    do_exit = False

    if not disas_path:
        basename = idc.GetInputFile()
        disas_path = '%s.disas' % basename
        idc.GenerateFile(idc.OFILE_ASM, '%s.asm' % basename, 0, idc.BADADDR, 0)
        idc.GenerateFile(idc.OFILE_LST, '%s.lst' % basename, 0, idc.BADADDR, 0)
        do_exit = True

    # Get basic blocks
    bbs = _get_basic_blocks()

    # Get the module's base address
    base_addr = idaapi.get_imagebase()

    # Get the module's end address
    segs = sorted(idautils.Segments())
    end_addr = idc.SegEnd(segs[-1])

    disas_info = {
        'bbs': bbs,
        'base_addr': base_addr,
        'end_addr': end_addr,
    }

    with open(disas_path, 'w') as disas_file:
        json.dump(disas_info, disas_file)

    if do_exit:
        idc.Exit(0)
    def _rebase_datastore(self, undo: bool = False) -> None:
        """
        Rebase all the addresses in the datastore.
        :param undo: Revert a rebasing instead
        :return: None
        """
        current_image_base = idaapi.get_imagebase()
        if self.STANDARD_IMAGE_BASE == current_image_base:
            return

        rebase_offset = current_image_base - self.STANDARD_IMAGE_BASE
        if undo:
            rebase_offset *= -1

        self.__rebase_dict(self.DATASTORE.globals, rebase_offset)
        self.__rebase_dict(self.DATASTORE.functions, rebase_offset)

        class_data: GameClass
        for (class_name, class_data) in self.DATASTORE.classes.items():
            if not class_data:
                continue

            self.__rebase_dict(class_data.funcs, rebase_offset)

            for vtbl in class_data.vtbls:
                vtbl.ea += rebase_offset

            if class_data.g_pointer:
                class_data.g_pointer += rebase_offset

            if class_data.g_instance:
                class_data.g_instance += rebase_offset
Example #24
0
def MakeNamespace(name, offsetArray):
    # type: (object, object) -> object
    print("namespace %s \n{" % name)
    for offset in offsetArray:
        print("\tconst auto %-20s = 0x%X;\t//0x%X" %
              (offset[0], offset[1] - idaapi.get_imagebase(), offset[1]))
    print("};\r\n")
Example #25
0
def get_inverted(func_ea):
    # Returns set of relative virtual addresses which are tied to IF and swapped
    internal_name = _ARRAY_STORAGE_PREFIX + hex(
        int(func_ea - idaapi.get_imagebase()))
    internal_id = idc.get_array_id(internal_name)
    array = idc.get_array_element(idc.AR_STR, internal_id, 0)
    return set(map(int, array.split()))
Example #26
0
 def custom_base_changed(self, s):
     try:
         self.custom_base = int(self.le_custom_base.text(), 16)
         self.lbl_diff.setText('%x' %
                               (idaapi.get_imagebase() - self.custom_base))
     except:
         self.lbl_diff.setText('<invalid>')
Example #27
0
def main():
    wow_imagebase = idc.AskAddr(idc.BADADDR, "Enter WoW's base address.")
    if wow_imagebase and wow_imagebase is not idc.BADADDR:
        delta = wow_imagebase - idaapi.get_imagebase()
        status = rebase_program(delta, idc.MSF_NOFIX)
        if status is not idc.MOVE_SEGM_OK:
            print "rebase_program failed %d." % (status)
Example #28
0
 def __init__(self, parser):
     self.color = False
     self.prev_loc = None
     self.prev_node = None
     self.name = idaapi.get_root_filename()
     print "[sync] name %s" % self.name
     self.base = idaapi.get_imagebase()
     print "[sync] module base 0x%x" % self.base
     self.base_remote = None
     self.gm = GraphManager()
     self.parser = parser
     self.broker_sock = None
     self.is_active = False
     self.dbg_dialect = None
     self.req_handlers = {
         'broker': self.req_broker,
         'loc': self.req_loc,
         'cmd': self.req_cmd,
         'cmt': self.req_cmt,
         'rcmt': self.req_rcmt,
         'fcmt': self.req_fcmt,
         'raddr': self.req_raddr,
         'rln': self.req_rln,
         'lbl': self.req_lbl,
         'bc': self.req_bc,
         'bps_get': self.req_bps_get,
         'bps_set': self.req_bps_set,
         'modcheck': self.req_modcheck,
         'dialect': self.req_set_dbg_dialect
     }
Example #29
0
    def Sync(self, offset, added, removed):
        """ Sync(offset, added, removed) => None
        Synchronize debug info with gef. This is an internal function. It is
        not recommended using it from the command line.
        """
        global _breakpoints, _current_instruction, _current_instruction_color

        if _current_instruction > 0:
            idc.SetColor(_current_instruction, CIC_ITEM, _current_instruction_color)

        base_addr = idaapi.get_imagebase()
        pc = base_addr + int(offset, 16)
        _current_instruction = long(pc)
        _current_instruction_color = GetColor(_current_instruction, CIC_ITEM)
        idc.SetColor(_current_instruction, CIC_ITEM, 0x00ff00)
        print("PC @ " + hex(_current_instruction).strip('L'))
        # post it to the ida main thread to prevent race conditions
        idaapi.execute_sync(lambda: idc.Jump(_current_instruction), idaapi.MFF_WRITE)

        cur_bps = set([ idc.GetBptEA(n)-base_addr for n in range(idc.GetBptQty()) ])
        ida_added = cur_bps - _breakpoints
        ida_removed = _breakpoints - cur_bps
        _breakpoints = cur_bps

        # update bp from gdb
        for bp in added:
            idc.AddBpt(base_addr+bp)
            _breakpoints.add(bp)
        for bp in removed:
            if bp in _breakpoints:
                _breakpoints.remove(bp)
            idc.DelBpt(base_addr+bp)

        return [list(ida_added), list(ida_removed)]
def Label_Dynamically_Resolved_Iat_Addresses(iatList, labeledIatDumpFileName):
    with open(labeledIatDumpFileName, 'r') as fp:
        labeledIatList = fp.read().splitlines()

    imageBase = idaapi.get_imagebase()
    labeledIatDict = dict()
    for i in labeledIatList:
        curRva, curIatLabel = i.split('\t')
        labeledIatDict[imageBase + int(curRva, 16)] = curIatLabel

    labeledCount = 0
    unresolvedList = []
    for entry in iatList:
        ea = idaapi.get_name_ea(0, entry)
        curIatLabel = labeledIatDict.get(ea, None)
        if curIatLabel != None:
            idc.set_name(ea, curIatLabel, 0)
            labeledCount += 1
        else:
            unresolvedList.append(
                'could not resolve address 0x{:x}'.format(ea))

    print('labeled {:x} dynamically resolved IAT entries'.format(labeledCount))

    if len(unresolvedList) != 0:
        print('[*] ERROR, was not able to resolve {:x} entries'.format(
            len(unresolvedList)))
        print('\n'.join(unresolvedList))
Example #31
0
    def m64_mmpagingfile(self):
        """
       The MmPagingFile pointer can be defined as PVOID *MMPAGING_FILE[16]. Support for locating this
        pointer is not mandatory, but essential to verify if an MMPAGING_FILE structure corresponds
        to a virtual store. Although this pointer was previously exported as nt!MmPagingFile in Windows
        7, the pointer has not been exported by any Windows 10 kernel to date. This function traverses
        MmStorecheckPagefiles. The same signature as x86 could not be used due to compiler optimzations
        using the LEA instruction to get the address of the global variable. Disassembly snippet from
        Windows 10 1809 x64 shown below.

        MmStoreCheckPagefiles      MmStoreCheckPagefiles proc near         ;
        MmStoreCheckPagefiles                      mov     r9d, cs:Count
        MmStoreCheckPagefiles+7                    xor     r8d, r8d
        MmStoreCheckPagefiles+A                    test    r9d, r9d
        MmStoreCheckPagefiles+D                    jz      short loc_14072F307
        MmStoreCheckPagefiles+F                    lea     eax, [r8+1]
        MmStoreCheckPagefiles+13                   lea     r10, unk_14043E5E0
        """
        (addr, name) = self.find_ida_name("MmStoreCheckPagefiles")

        for insn_addr, insn, op0, op1 in self.iter_fn(addr):
            if insn == "lea":
                if idc.get_operand_type(insn_addr, 1) == idc.o_mem:
                    return idc.get_operand_value(insn_addr,
                                                 1) - idaapi.get_imagebase()

        self.logger.error("MmPagingFile could not be resolved.")
        return None
Example #32
0
    def prepCMDLine(self):
        cmd = [
            self.PIN_PATH, '-t', self.TA_PATH, '-sib',
            "0x{0:x}".format(idaapi.get_imagebase()), "-bt",
            "0x{0:x}".format(self.__taintStart), "-et",
            "0x{0:x}".format(self.__taintStop)
        ]

        if len(self.__tpargs) > 1:
            cmd.append("-tp")
            cmd.append(self.__tpargs)

        if len(self.__trargs) > 1:
            cmd.append("-tr")
            cmd.append(self.__trargs)

        if len(self.__taargs) > 1:
            cmd.append("-ta")
            cmd.append(self.__taargs)

        if len(self.__sffargs) > 1:
            cmd.append("-sff")
            cmd.append(self.__sffargs)

        if len(self.__sfrargs) > 1:
            cmd.append("-sfr")
            cmd.append(self.__sfrargs)

        cmd.append("--")
        cmd.append(self.TARGET_PATH + self.TARGET_FILE)

        return cmd + self.__programArguments
Example #33
0
def find_bbls(function_ea):
    '''
        yields all basic blocks that belong to the
        given function. The blocks are returned in
        a 2-tuple like:

            (start_address, end_address)

        Both start and end address are RELATIVE offsets
        from the image base.
    '''

    # get image base from IDA
    image_base = idaapi.get_imagebase()
    function_ea += image_base

    # get flow chart from IDA
    flow_chart = idaapi.FlowChart(
            idaapi.get_func(function_ea),
            flags=idaapi.FC_PREDS
            )

    # iterate through all basic blocks in
    # the current routine
    for block in flow_chart:
        start_addr = block.startEA - image_base
        end_addr = block.endEA - image_base
        if start_addr != end_addr:
            yield start_addr, end_addr
Example #34
0
def find_vftable_msvc(seg):
    seg_start = idc.SegStart(seg)
    seg_end = idc.SegEnd(seg)
    cur_addr = seg
    symbol = ""

    while cur_addr <= seg_end - 8:  #32 is 4
        data = idc.Qword(cur_addr)  #32 is Dword
        # 检测data是否在.text段
        # check if the data in .text
        if text_start <= data < text_end:
            xrefs = list(idautils.XrefsTo(cur_addr))
            rttiptr = idc.Qword(cur_addr - 8)
            nameptr = idaapi.get_imagebase() + idc.Dword(rttiptr + 0x10)

            if (len(xrefs) != 0) and (rdata_start <= rttiptr < rdata_end) and (
                    nameptr not in rtti_list):

                symbol = idc.GetOpnd(rttiptr + 0x10, 0)
                symbol = re.sub(r'^rva ', '', symbol)
                class_hierarchy_addr = nameptr

                class_list[symbol] = dict()
                class_list[symbol]["addr"] = class_hierarchy_addr
                class_list[symbol]["base"] = list()
                class_list[symbol]["function_list"] = [hex(data).strip("L")]

                rtti_list.append(nameptr)

            elif symbol != "":
                class_list[symbol]["function_list"].append(
                    hex(data).strip("L"))

        cur_addr += 8  #32 is 4
Example #35
0
    def run(self, arg):
        # Get form and widget
        form = idaapi.create_empty_widget(self.comment)
        widget = sip.wrapinstance(int(form), QtWidgets.QWidget)

        runtime = IDARuntime(form)

        # Try to find the IDA input file
        filename = idaapi.get_input_file_path()

        if not filename:
            return

        if not os.path.isfile(filename):
            filename = os.path.basename(filename)

            if not os.path.isfile(filename):
                filename = runtime.ask_file(os.path.basename(filename),
                                            "Where is the input file?")

        if not filename:
            return

        # Map input file
        self.pe_tree_form = pe_tree.form.PETreeForm(widget, None, runtime)
        self.pe_tree_form.map_pe(image_base=idaapi.get_imagebase(),
                                 filename=filename)
        self.pe_tree_form.show()
Example #36
0
def CopyEA():
  myModuleName = idc.GetInputFile()
  MyModuleShortName = re.sub(r'\.[^.]*$','',myModuleName)
  myModuleBase = idaapi.get_imagebase()
  myOffset = idc.ScreenEA() - myModuleBase
  pasteStr = "bp !%s + 0x%x" % (MyModuleShortName, myOffset)
  print pasteStr
  Paste(pasteStr)
 def __init__(self):
     self.image_base = idaapi.get_imagebase();
     self.code_coverage_total = 0.0
     self.loc_executed_total = 0
     self.bbls_executed_total = 0
     self.functions_executed_total = 0
     self.calls_executed_total = 0
     self.functions = dict()
Example #38
0
def CopyEA():
  myModuleName = idc.GetInputFile()
  MyModuleShortName = re.sub(r'\.[^.]*$','',myModuleName)
  myModuleBase = idaapi.get_imagebase()
  myOffset = idc.ScreenEA() - myModuleBase
  clippy = QtGui.QClipboard()
  pasteStr = "bp !%s + 0x%x" % (MyModuleShortName, myOffset)
  print pasteStr
  clippy.setText(pasteStr)
Example #39
0
def rebaseProgramToDynamicBase(processBaseAddress):
    delta = processBaseAddress - ida.get_imagebase()
    rebaseStatus = idc.rebase_program(delta, MSF_FIXONCE)
    if rebaseStatus < 0:
        errstr = ( "Error: Problem rebasing program, error code {0}.  Check "
            "MOVE_SEGM_ error codes.  ida_taint.py is now exiting...\n" )
        fatalError(errstr.format(rebaseStatus))
        return -1
    return 0
Example #40
0
def find_functions():
    '''
        yields all functions in the form a 2-tuple:

            (function_address, function_name)

        function_address is a RELATIVE offset from the
        image base.
    '''
    # get image base from IDA
    image_base = idaapi.get_imagebase()

    # iterate through all functions in the executable.
    for func_ea in Functions(MinEA(), MaxEA()):
        # craft the routine record
        func_name = GetFunctionName(func_ea)
        funcaddr = func_ea - image_base
        yield funcaddr, func_name
def main():
	filepath = idaapi.askfile_c(False, "*.*", "Pin log file");
	imagebase = idaapi.get_imagebase();
	try:
		f = open(filepath, "rb");
	except:
		print("Need log file to parse data...");
		return;
	buff = f.read();
	ida_color = 0xFFFFFFFF;
	for index in range(0, len(buff)):
		exec_count = ord(buff[index]);
		if exec_count == 0:
			continue;
		
		exec_count = exec_count / 10;
		if exec_count > 11: exec_count = 11;

		idc.SetColor(imagebase + index, CIC_ITEM, ida_color);
Example #42
0
def get_list_of_function_instr(addr, mode):
    #TODO follow subcalls MODE_INSTRUMENT_SUBCALLS
    f_start = addr
    f_end = idc.FindFuncEnd(addr)
    chunks = enumerate_function_chunks(f_start)
    list_of_addr = list()
    image_base = idaapi.get_imagebase(addr)
    for chunk in chunks:
        for head in idautils.Heads(chunk[0], chunk[1]):
            # If the element is an instruction
            if head == hex(0xffffffffL):
                raise Exception("Invalid head for parsing")
            if isCode(idc.GetFlags(head)):
                head = head - image_base
                head = str(hex(head))
                head = head.replace("L", "")
                head = head.replace("0x", "")
                list_of_addr.append(head)
    return list_of_addr
Example #43
0
    def prepCMDLine(self):
        cmd = [
            self.PIN_PATH,
            '-t',
            self.TA_PATH,
            '-sib',
            "0x{0:x}".format(idaapi.get_imagebase()),
            "-bt",
            "0x{0:x}".format(self.__taintStart),
            "-et",
            "0x{0:x}".format(self.__taintStop)]

        if len(self.__tpargs) > 1:
            cmd.append("-tp")
            cmd.append(self.__tpargs)

        if len(self.__trargs) > 1:
            cmd.append("-tr")
            cmd.append(self.__trargs)

        if len(self.__taargs) > 1:
            cmd.append("-ta")
            cmd.append(self.__taargs)

        if len(self.__sffargs) > 1:
            cmd.append("-sff")
            cmd.append(self.__sffargs)

        if len(self.__sfrargs) > 1:
            cmd.append("-sfr")
            cmd.append(self.__sfrargs)

        cmd.append("--")
        cmd.append(self.TARGET_PATH + self.TARGET_FILE)

        return cmd + self.__programArguments
Example #44
0
def get_rva():
    rva = here() - idaapi.get_imagebase()
    return rva
Example #45
0
def queryFile(comFile, tMan, iMan, coClassCLSID=None, coClassName=None):

    success = False
    imgBase = idaapi.get_imagebase()

    class tmpCoClass(object):
        def __init__(self, name, iid):
            self.iid = iid
            self.name = self.entryName = coClassName

    if not os.access(comFile, os.R_OK|os.X_OK):
        print "Bad file permissions on %s, can't RX" % (comFile)
        return False

    try:
        tlb = pyTypeLibs.typeLib(comFile)
        tMan.addLib(tlb)
        classes = tlb.getClasses()
    except OSError:
        if not coClassCLSID:
            print "%s has no typelib, but we need a CLSID to create an instance" % comFile
            print "Try passing the -C argument with a clsid to instantiate"
            return False
        else:
            tmpClass = tmpCoClass("obj", coClassCLSID)
            print "Using CLSID %s to instantiate" % (coClassCLSID)
            classes = [tmpClass]
    
    #
    if coClassCLSID:
        tmpClass = tmpCoClass("obj", coClassCLSID)
        print "Using CLSID %s to instantiate" % (coClassCLSID)
        classes = [tmpClass]

    #
    for coclass in classes:
        
        #try and instantiate each coclass we find
        try:
            iuk = iquery.iQuery()
            if iuk.coCreateUnknown(comFile, coclass.iid):
                success = True
                print "Class %s (%s)" % (coclass.entryName, coclass.iid)
                del iuk
            else:
                print "Failed to CoCreate class %s %s" % (coclass.entryName, coClass.iid)
                continue

            #
            for iFace in iMan.getInterfaceList():

                #any exception caught by the outside try{}
                iuk = iquery.iQuery()
                if not iuk.coCreateUnknown(comFile, coclass.iid):
                    break
                
                #
                try:
                    if iuk.isInterfaceSupported(iFace.iid):
                        iMan.resolveBase(iFace)
                        print "  Interface %s %s" % (iFace.entryName, iFace.iid)
                        print "    Inheritance hierarchy: %s" % (iFace.hierStr())
                        vtOffset = imgBase + iuk.getIFaceVTOffset(iFace.iid)
                        iName = coclass.entryName + "::" + iFace.entryName
                        if not idaapi.set_name(int(vtOffset), str(iName)):
                            print "ERROR:Failed to set interface name, (%#x, %s)" % (vtOffset, iName)
                        print "    %s - VT addr %#x" % (iFace.entryName, vtOffset)
                        offset = 0
                        for func in iFace.getVtable():
                            fName = iName + "::" + func.name
                            fAddr = idc.Dword(vtOffset + offset)
                            if not idaapi.set_name(int(fAddr), str(fName)):
                                print "ERROR:Failed to set function name, (%#x, %s)" % (fAddr, fName)
                                break
                            #print "      (%#x) %s" % (vtOffset + offset, str(func))
                            offset += 4
                    else:
                        #print "%s (%s) not supported" % (iFace.iid, iFace.entryName)
                        pass
                except RuntimeError, exc:
                    #print "EXC %s" % (exc)
                    #print "%s (%s) not supported (EXC)" % (iFace.iid, iFace.entryName)
                    pass

                del iuk

        except RuntimeError, exc:
            if not isinstance(coclass, pyTypeLibs.tCoClass) or coclass.canCreate():
                print "INFO:Failed to CoCreate class %s %s, %s" % (coclass.entryName, coclass.iid, str(exc))
                print("If LoadLibrary() failed, it may be because the DLL tried load a resource\n"
                        "DLL that is based on the current module name. msxml3.dll tries to do this\n"
                        "when it tries to load msxml3r.dll\n")
Example #46
0
def get_image():
    name = idc.GetInputFile()
    base = idaapi.get_imagebase()
    return base, name
Example #47
0
def baseaddress():
    return ida.get_imagebase()
from sets import Set
import json
import idaapi
import idc

print('My Script is now running...')
print('Waiting for idapro...')
idaapi.autoWait()
print('start persisting...')

idaapi.rebase_program(-1*idaapi.get_imagebase(), 0)

ss = idaapi.get_input_file_path()
pn = os.path.splitext(ss)[0]
callees = dict()
funcmap = dict()
data = dict()
data['name'] = pn

for seg_ea in Segments():
    for function_ea in Functions(SegStart(seg_ea), SegEnd(seg_ea)):
        #fill call graph
        # For each of the incoming references
        for ref_ea in CodeRefsTo(function_ea, 0):
             # Get the name of the referring function
             caller_name = GetFunctionName(ref_ea)
             # Add the current function to the list of functions called by the referring function
             callees[caller_name] = callees.get(caller_name, Set())
             callees[caller_name].add(function_ea)

data['functions'] = list()
import idaapi
import idautils

# Global variables
IMG_BASE = idaapi.get_imagebase()
list_seg = []
for seg in idautils.Segments():
    list_seg.append(seg)
IMG_END = idc.SegEnd(list_seg[len(list_seg)-1])

def decrypt(ea, key):
    
    # Virtual address to IMAGE_IMPORT_DESCRIPTOR->FirstThunk
    va_iat = 0
    # Virtual address to IMAGE_IMPORT_DESCRIPTOR->OriginalFirstThunk
    va_int = 0
    tmp_ea = ea
    
    # Back-tracing to locate the IMAGE_IMPORT_DESCRIPTOR from import address table passed from the callback
    for xref in idautils.XrefsTo(ea, 0):
        if XrefTypeName(xref.type) == 'Data_Offset':
            va_iat = xref.frm - 0x10

    if va_iat != 0:
        print "Import Name Table->%08x" % (idaapi.get_long(va_iat) + IMG_BASE)
        va_int = idaapi.get_long(va_iat) + IMG_BASE
    else:
        return
        
    if va_int != 0:
        va_itd = idaapi.get_long(va_int)
Example #50
0
    binary_path = GetInputFilePath()
    #Create the object from its GUID/ClassID
    newobj = comtypes.client.CreateObject(get_guid(binary_path))
    #Gross way to parse out the actual interface name
    interface_name = newobj.__class__.__name__.split('(')[1].strip(')')
    
    #Lets cast it to a real ctypes pointer so we can get the pointer to interface vtbl
    #This feels like a dirty hack, but seems to be easiest way to get the actual pointer
    #http://blogs.msdn.com/b/oldnewthing/archive/2004/02/05/68017.aspx
    vtbl_ptr = ctypes.cast(newobj, ctypes.POINTER(ctypes.c_void_p)).contents.value
	
    #Lets get our module base address using ctypes/win32 api
    mod_base = kernel32.GetModuleHandleA(binary_path)
    
    #Get the base address of the binary loaded in IDA
    base = idaapi.get_imagebase()
	
    #Get the delta of the actual module load address vs what the binary is currently loaded at in IDA
    delta = mod_base - base
    
    #Now rebase, we do this so our vtable ptr is accurate in the IDA display
    rebase_program(delta,  0x0008)
	
    #Bring focus to the vtable
    idaapi.jumpto(vtbl_ptr)
    
    #Name it after the interface name
    MakeName(vtbl_ptr, interface_name + '_vtable')
    
    #Now skip down the vtable past the stuff inherited from IDispatch etc.
    #Not 100% sure this will always be the same....
	c_addr = str_addr
	MakeUnknown(str_addr, str_sz, DOUNK_DELNAMES) 
	while c_addr < str_sz+str_addr:
		string = get_data_string(c_addr, str_sz+str_addr)
		if len(string) == 0:
			#MakeAlign(c_addr, 4, 0)
			c_addr += 1
			continue
		MakeStr(c_addr, c_addr+len(string)+1)
		#a = get_align(len(string)+1, 4)
		#MakeAlign(c_addr+len(string)+1, a, 0)
		#c_addr += a+len(string)+1
		c_addr += len(string)+1

#elf_file = AskString("C:\\code\\elf.h", "Enter path to the ELF header file.")
start = AskAddr(idaapi.get_imagebase(), "Enter start address of the file.")
if start == 0xFFFFFFFF:
	print "Error, bad address."
	exit(-1)

# elf header structure
file_start = start
print "Processing Ehdr", hex(file_start)
ehdr_id = process_ehdr(file_start)

# phdr structure
phdr_off = Dword(file_start+GetMemberOffset(ehdr_id, "e_phoff"))
phdr_num = Word(file_start+GetMemberOffset(ehdr_id, "e_phnum"))
process_phdrs(file_start+phdr_off, phdr_num)

Example #52
0
def main():
    
    global tm_start
    
    for mod in ('metapc', 'ppc', 'arm'):
        arch_mod = __import__('arch.%s' % mod, globals(), locals(), ['*'])
        arch = arch_mod.Arch()
        if arch:
            if arch.check_arch():
                # This is a valid module for the current architecure
                # so the search has finished
                log_message('Using architecture module [%s]' % mod)
                break
    else:
        log_message('No module found to process the current architecure [%s]. Exiting.' % (arch.processor_name))
        return
        
    global instrumentation
    
    log_message('Initialization sucessful.')
    
    db_engine, db_host, db_name, db_user, db_password = (None,)*5
    batch_mode = False
    module_comment = ''
    process_sections = False
    
    
    # If the configuration filename has been fetched from the
    # environment variables, then use that.
    #
    if CONFIG_FILE_NAME:
        config_file_path = CONFIG_FILE_NAME
        
    # Otherwise fallback into the one expected in the IDA directory
    #
    else:
        config_file_path = os.path.join(idaapi.idadir(''), 'ida2sql.cfg')
     
    
    if os.path.exists(config_file_path):
        cfg = ConfigParser.ConfigParser()
        cfg.read(config_file_path)
        
        if cfg.has_section('database'):
            if cfg.has_option('database', 'engine'):
                db_engine = getattr(DB_ENGINE, cfg.get('database', 'engine'))
            
            if cfg.has_option('database', 'host'):
                db_host = cfg.get('database', 'host')
            
            if cfg.has_option('database', 'schema'):
                db_name = cfg.get('database', 'schema')
            
            if cfg.has_option('database', 'user'):
                db_user = cfg.get('database', 'user')
            
            if cfg.has_option('database', 'password'):
                db_password = cfg.get('database', 'password')
            
            if cfg.has_option('importing', 'mode'):
                batch_mode = cfg.get('importing', 'mode')
                
                if batch_mode.lower() in ('batch', 'auto'):
                    batch_mode = True
            
            if cfg.has_option('importing', 'comment'):
                module_comment = cfg.get('importing', 'comment')
            
            if cfg.has_option('importing', 'process_sections'):
                process_sections = cfg.get('importing', 'process_sections')
                
                if process_sections.lower() in ('no', 'false'):
                    process_sections = False
                else:
                    process_sections = True
                
    
    if None in (db_engine, db_host, db_name, db_user, db_password):
    
        (db_engine, db_host, 
        db_name, db_user, 
        db_password) = query_configuration()    
        
        if None in (db_engine, db_host, db_name, db_user, db_password):
            log_message('User cancelled the exporting.')
            return
            
    failed = False
    try:
        sqlexporter = SQLExporter(arch, db_engine, db=db_name,
                user=db_user, passwd=db_password, host=db_host, use_new_schema=USE_NEW_SCHEMA)
    except ImportError:
        print "Error connecting to the database, error importing required module: %s" % sys.exc_info()[0]
        failed = True
    except Exception:
        print "Error connecting to the database, Reason: %s" % sys.exc_info()[0]
        failed = True

    if failed:
        # Can't connect to the database, indicate that to BinNavi
        if batch_mode is True:
            idc.Exit(FATAL_CANNOT_CONNECT_TO_DATABASE)
        else:
            return
    
    if not sqlexporter.is_database_ready():
        
        if batch_mode is False:
            result = idc.AskYN(1, 'Database has not been initialized yet. Do you want to create now the basic tables? (This step is performed only once)')
        else:
            result = 1
            
        if result == 1:
            sqlexporter.init_database()
        else:
            log_message('User requested abort.')
            return
    
    iteration = os.environ.get('EXPORT_ITERATION', None)
    module_id = os.environ.get('MODULE_ID', None)
        
    if iteration is None and module_id == None:
        # Export manually
        print "Exporting manually ..."
        iteration = -1
        sqlexporter.set_callgraph_only(False)
        sqlexporter.set_exporting_manually(True)
        status = sqlexporter.new_module(
            idc.GetInputFilePath(), arch.get_architecture_name(), idaapi.get_imagebase(), module_comment, batch_mode)
            
    elif iteration is not None and module_id is not None:
        
        # Export the next k functions or the call graph
        sqlexporter.set_exporting_manually(False)
        sqlexporter.set_callgraph_only(int(iteration) == -1)
        sqlexporter.set_module_id(int(module_id))
        status = True
        
    else:
        
        sqlexporter.set_exporting_manually(False)
        status = sqlexporter.new_module(
            idc.GetInputFilePath(), arch.get_architecture_name(), idaapi.get_imagebase(), module_comment, batch_mode)
        sqlexporter.set_callgraph_only(False)
        
    if status is False:
        log_message('Export aborted')
        return
    elif status is None:
        log_message('The database appears to contain data exported with different schemas, exporting not allowed.')
        if batch_mode:
            idc.Exit(FATAL_INVALID_SCHEMA_VERSION)
    
    instrumentation = Instrumentation()
    
    instrumentation.new_function_callable(sqlexporter.process_function)
    instrumentation.new_packet_callable(sqlexporter.process_packet)
    instrumentation.new_section_callable(sqlexporter.process_section)
    
    
    tm_start = time.time()
    
    already_imported = sqlexporter.db.get_already_imported()

    incomplete = process_binary(arch, process_sections, int(iteration), already_imported)
    
    sqlexporter.finish()
    
    log_message('Results: %d functions, %d instructions, %d basic blocks, %d address references' % (
        len(sqlexporter.exported_functions), len(sqlexporter.exported_instructions),
        sqlexporter.basic_blocks_next_id-1, sqlexporter.address_references_values_count ))
        
    log_message('Results: %d expression substitutions, %d operand expressions, %d operand tuples' % (
        sqlexporter.expression_substitutions_values_count, sqlexporter.operand_expressions_values_count,
        sqlexporter.operand_tuples___operands_values_count ) )
        
        
    log_message('Exporting completed in %s' % get_time_delta_string())
    
    # If running in batch mode, exit when done
    if batch_mode:
        if incomplete:
            shiftedModule = (sqlexporter.db.module_id << 0x10) | 0xFF
        
            idc.Exit(shiftedModule)
        elif not sqlexporter.callgraph_only:
            shiftedModule = (sqlexporter.db.module_id << 0x10) | 0xFE
    
            idc.Exit(shiftedModule)
        else:
            idc.Exit(0)
def MakeRva(name):
    return construct.Embed(construct.Struct('EmbeddedRva',
        construct.ULInt32(name),
        construct.Value('VA', lambda ctx: idaapi.get_imagebase() + ctx[name])
    ))
Example #54
0
def baseaddress():
    '''returns the baseaddress of the database'''
    return idaapi.get_imagebase()