Python idaapi.get_imagebase() Examples

The following are 12 code examples of idaapi.get_imagebase(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module idaapi , or try the search function .
Example #1
Source File: lib_parser.py    From IDAmetrics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #2
Source File: x64dbgida.py    From x64dbgida with MIT License 5 votes vote down vote up
def do_export():
    db = {}
    module = idaapi.get_root_filename().lower()
    base = idaapi.get_imagebase()

    file = ida_kernwin.ask_file(1, "x64dbg database|{}".format(get_file_mask()),
                                "Export database")
    if not file:
        return
    print("Exporting database {}".format(file))

    db["labels"] = [{
        "text": name,
        "manual": False,
        "module": module,
        "address": "{:#x}".format(ea - base)
    } for (ea, name) in idautils.Names()]
    print("{:d} label(s) exported".format(len(db["labels"])))

    db["comments"] = [{
        "text": comment.replace("{", "{{").replace("}", "}}"),
        "manual": False,
        "module": module,
        "address": "{:#x}".format((ea - base))
    } for (ea, comment) in Comments()]
    print("{:d} comment(s) exported".format(len(db["comments"])))

    db["breakpoints"] = [{
        "address": "{:#x}".format(ea - base),
        "enabled": True,
        "type": bptype,
        "titantype": "{:#x}".format(titantype),
        "oldbytes": "{:#x}".format(oldbytes),
        "module": module,
    } for (ea, bptype, titantype, oldbytes) in Breakpoints()]
    print("{:d} breakpoint(s) exported".format(len(db["breakpoints"])))

    with open(file, "w") as outfile:
        json.dump(db, outfile, indent=1)
    print("Done!") 
Example #3
Source File: ida_debugger.py    From IDAngr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def image_base(self):
        return idaapi.get_imagebase()
    
    #------------------------------------- 
Example #4
Source File: diaphora_ida.py    From maltindex with GNU General Public License v2.0 5 votes vote down vote up
def get_base_address(self):
    return idaapi.get_imagebase() 
Example #5
Source File: ida_api.py    From lighthouse with MIT License 5 votes vote down vote up
def get_imagebase(self):
        return idaapi.get_imagebase() 
Example #6
Source File: main.py    From ida_pdb_loader with MIT License 5 votes vote down vote up
def run(self):
        '''Public function.'''

        self.symbol_path = idc.AskFile(0, '*.pdb', 'Choose PDB file...')
        self.image_base = idaapi.get_imagebase()

        print "IPL: Loading PDB data, might take a while..."
        self.PDBLookup = pdbparse.symlookup.Lookup([(self.symbol_path, self.image_base)])

        if not self.PDBLookup:
            print "IPL: PDBLookup failed to initialize, exiting."
            return

        self._rename_functions()
        return 
Example #7
Source File: IDAMetrics_dynamic.py    From IDAmetrics with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 #8
Source File: drop.py    From DROP-IDA-plugin with GNU General Public License v3.0 5 votes vote down vote up
def database_inited(self, is_new_db, idc_script):
        # A file was loaded, reset vars
        self.plugin.filename = idaapi.get_input_file_path()
        self.plugin.cfg = None
        self.plugin.angr_proj = None
        self.plugin.global_vars = None
        self.plugin.opaque_predicates = dict()
        self.plugin.extra_constraints = dict()
        self.plugin.symbolic_vars = dict()

        # Check if it (still) exists
        if not isfile(self.plugin.filename):
            print("### Drop error: original input file no longer exists, unable to load it into angr. ###")
            return

        # Load the file into angr
        try:
            # This is a bit inefficient, but figure out if it's PIC by loading twice
            p = angr.Project(self.plugin.filename, load_options={'auto_load_libs': False})
            if p.loader.main_bin.pic:
                # Load with IDA's imagebase as base_addr
                base_addr = idaapi.get_imagebase()
            else:
                # Load with 0 as base_addr
                base_addr = 0
            del p
            self.plugin.angr_proj = angr.Project(self.plugin.filename,
                load_options={'auto_load_libs': False, 'main_opts': {
                    'custom_base_addr': base_addr}})

            # get and store the file bitness
            # Don't use idaapi.get_inf_structure().is_32bit(), it will give True for MIPS64...
            self.plugin.bitness = self.plugin.angr_proj.arch.bits

            # Save the list of all recognized variables in .bss, .data and .rodata (TODO: why these? any others?)
            # TODO: Other segments as well?
            self.plugin.global_vars = [var for s in sark.segments() for var in get_segment_names(s) if s.name in [".bss", ".data", ".rodata"]]
            print("### Loaded file into angr succesfully! ###")
        except:
            import traceback
            print("ERROR: Failed to load file into angr: {}".format(traceback.format_exc())) 
Example #9
Source File: ida_api.py    From lighthouse with MIT License 4 votes vote down vote up
def _get_ida_bg_color_from_file(self):
        """
        Get the background color of the IDA disassembly views via HTML export.
        """
        logger.debug("Attempting to get IDA disassembly background color from HTML...")

        #
        # TODO/IDA: we need better early detection for if IDA is fully ready,
        # this isn't effective and this func theme func can crash IDA if
        # called too early (eg, during db load...).
        #
        # this isn't a problem now... but I don't want us to be at risk of
        # hard crashing people's IDA in the future should we change something.
        #

        imagebase = idaapi.get_imagebase()
        #if imagebase == idaapi.BADADDR:
        #    logger.debug(" - No imagebase...")
        #    return None

        # create a temp file that we can write to
        handle, path = tempfile.mkstemp()
        os.close(handle)

        # attempt to generate an 'html' dump of the first 0x20 bytes (instructions)
        ida_fd = idaapi.fopenWT(path)
        idaapi.gen_file(idaapi.OFILE_LST, ida_fd, imagebase, imagebase+0x20, idaapi.GENFLG_GENHTML)
        idaapi.eclose(ida_fd)

        # read the dumped text
        with open(path, "r") as fd:
            html = fd.read()

        # delete the temp file from disk
        try:
            os.remove(path)
        except OSError:
            pass

        # attempt to parse the user's disassembly background color from the html
        bg_color_text = get_string_between(html, '<body bgcolor="', '">')
        if bg_color_text:
            logger.debug(" - Extracted bgcolor '%s' from regex!" % bg_color_text)
            return QtGui.QColor(bg_color_text)

        # sometimes the above one isn't present... so try this one
        bg_color_text = get_string_between(html, '.c1 \{ background-color: ', ';')
        if bg_color_text:
            logger.debug(" - Extracted background-color '%s' from regex!" % bg_color_text)
            return QtGui.QColor(bg_color_text)

        logger.debug(" - HTML color regex failed...")
        logger.debug(html)
        return None 
Example #10
Source File: analyser.py    From UEFI_RETool with MIT License 4 votes vote down vote up
def __init__(self):
        header = get_header_idb()
        if not len(header):
            header = get_header_file()
        self.arch = get_machine_type(header)
        self.subsystem = check_subsystem(header)
        self.valid = True
        if not self.subsystem:
            print('[ERROR] Wrong subsystem')
            self.valid = False
        if not (self.arch == 'x86' or self.arch == 'x64'):
            print('[ERROR] Wrong architecture')
            self.valid = False
        if self.arch == 'x86':
            self.BOOT_SERVICES_OFFSET = BOOT_SERVICES_OFFSET_x86
        if self.arch == 'x64':
            self.BOOT_SERVICES_OFFSET = BOOT_SERVICES_OFFSET_x64
        self.base = idaapi.get_imagebase()
        idc.import_type(-1, 'EFI_GUID')
        idc.import_type(-1, 'EFI_SYSTEM_TABLE')
        idc.import_type(-1, 'EFI_RUNTIME_SERVICES')
        idc.import_type(-1, 'EFI_BOOT_SERVICES')

        self.gBServices = {}
        self.gBServices['InstallProtocolInterface'] = []
        self.gBServices['ReinstallProtocolInterface'] = []
        self.gBServices['UninstallProtocolInterface'] = []
        self.gBServices['HandleProtocol'] = []
        self.gBServices['RegisterProtocolNotify'] = []
        self.gBServices['OpenProtocol'] = []
        self.gBServices['CloseProtocol'] = []
        self.gBServices['OpenProtocolInformation'] = []
        self.gBServices['ProtocolsPerHandle'] = []
        self.gBServices['LocateHandleBuffer'] = []
        self.gBServices['LocateProtocol'] = []
        self.gBServices['InstallMultipleProtocolInterfaces'] = []
        self.gBServices['UninstallMultipleProtocolInterfaces'] = []

        self.Protocols = {}
        self.Protocols['ami_guids'] = ami_guids.ami_guids
        self.Protocols['asrock_guids'] = asrock_guids.asrock_guids
        self.Protocols['dell_guids'] = dell_guids.dell_guids
        self.Protocols['edk_guids'] = edk_guids.edk_guids
        self.Protocols['edk2_guids'] = edk2_guids.edk2_guids
        self.Protocols['lenovo_guids'] = lenovo_guids.lenovo_guids
        self.Protocols['all'] = []
        self.Protocols['prop_guids'] = []
        self.Protocols['data'] = [] 
Example #11
Source File: vxhunter_ida.py    From vxhunter with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def fix_vxworks_idb(load_address, vx_version, symbol_table_start, symbol_table_end):
        current_image_base = idaapi.get_imagebase()
        symbol_interval = 16
        if vx_version == 6:
            symbol_interval = 20
        symbol_table_start += load_address
        symbol_table_end += load_address
        ea = symbol_table_start
        shift_address = load_address - current_image_base
        while shift_address >= 0x70000000:
            idaapi.rebase_program(0x70000000, 0x0008)
            shift_address -= 0x70000000
        idaapi.rebase_program(shift_address, 0x0008)
        while ea < symbol_table_end:
            # for VxWorks 6 unknown symbol format
            if idc.Byte(ea + symbol_table_end - 2) == 3:
                ea += symbol_interval
                continue
            offset = 4
            if idaapi.IDA_SDK_VERSION >= 700:
                idc.create_strlit(idc.Dword(ea + offset), idc.BADADDR)
            else:
                idc.MakeStr(idc.Dword(ea + offset), idc.BADADDR)
            sName = idc.GetString(idc.Dword(ea + offset), -1, idc.ASCSTR_C)
            print("Found %s in symbol table" % sName)
            if sName:
                sName_dst = idc.Dword(ea + offset + 4)
                if vx_version == 6:
                    sName_type = idc.Dword(ea + offset + 12)
                else:
                    sName_type = idc.Dword(ea + offset + 8)
                idc.MakeName(sName_dst, sName)
                if sName_type in need_create_function:
                    # flags = idc.GetFlags(ea)
                    print("Start fix Function %s at %s" % (sName, hex(sName_dst)))
                    idc.MakeCode(sName_dst)  # might not need
                    idc.MakeFunction(sName_dst, idc.BADADDR)
            ea += symbol_interval
        print("Fix function by symbol table finish.")
        print("Start IDA auto analysis, depending on the size of the firmware this might take a few minutes.")
        idaapi.autoWait() 
Example #12
Source File: vxhunter_ida.py    From vxhunter with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def load_symbols(self, file_data, is_big_endian=True):
        symbol_list = []
        if is_big_endian:
            unpack_format = '>I'
        else:
            unpack_format = '<I'

        symbol_count = struct.unpack(unpack_format, file_data[4:8])[0]
        print("symbol_count: %s" % symbol_count)
        symbol_offset = 8
        string_table_offset = 8 + 8 * symbol_count
        print("string_table_offset: %s" % string_table_offset)
        # get symbols
        for i in range(symbol_count):
            offset = i * 8
            symbol_data = file_data[symbol_offset + offset:symbol_offset + offset + 8]
            flag = ord(symbol_data[0])
            string_offset = struct.unpack(unpack_format, '\x00' + symbol_data[1:4])[0]
            string_offset += string_table_offset
            print("string_offset: %s" % string_offset)
            symbol_name = ""
            while True:
                if file_data[string_offset] != '\x00':
                    symbol_name += file_data[string_offset]
                    string_offset += 1

                else:
                    break
            print("symbol_name: %s" % symbol_name)
            symbol_address = struct.unpack(unpack_format, symbol_data[-4:])[0]
            symbol_list.append([flag, symbol_name, symbol_address])
            # Find TP-Link device loading address with symbols
            if "wrs_kernel_text_start" in symbol_name:
                load_address = symbol_address
                current_image_base = idaapi.get_imagebase()
                shift_address = load_address - current_image_base
                while shift_address >= 0x70000000:
                    idaapi.rebase_program(0x70000000, 0x0008)
                    shift_address -= 0x70000000
                idaapi.rebase_program(shift_address, 0x0008)

        # load symbols
        for symbol_data in symbol_list:
            flag, symbol_name, symbol_address = symbol_data
            idc.MakeName(symbol_address, symbol_name)
            if flag == 0x54:
                if symbol_name:
                    print("Start fix Function %s at %s" % (symbol_name, hex(symbol_address)))
                    idc.MakeCode(symbol_address)  # might not need
                    idc.MakeFunction(symbol_address, idc.BADADDR)