Exemplo n.º 1
0
def load_kmdf_types_into_idb():
    header_path = idautils.GetIdbDir()
    # change relative path to use more easily
    idaapi.idc_parse_types("".join([header_path, "../Tools/kmdf_re/code/WDFStructsV2.h"]), idc.PT_FILE)
    for idx in range(1, idc.GetMaxLocalType()):
        print(idx, idc.GetLocalTypeName(idx))
        idc.Til2Idb(idx, idc.GetLocalTypeName(idx))
Exemplo n.º 2
0
def export_tags(tags):
    out_dir = idautils.GetIdbDir() + idaapi.get_root_filename(
    ) + "_TagSource" + ".json"
    with open(out_dir, 'wb') as f:
        json.dump(tags, f)
    print("[TagSource] Tags created : " + str(len(tags)))
    print("[TagSource] Tags exported : " + out_dir)
Exemplo n.º 3
0
def find_input_file():
    """
    Description:
        Check whether or not IDA knows where the original file used to create the IDB is.
        If IDA doesn't know, check the IDA's directory for the file.

    Output:
        Returns True if the input file was located, False if it was not.
    """
    global INPUT_FILE_PATH
    ida_path = INPUT_FILE_PATH
    if not os.path.exists(ida_path):
        # If IDA does not know, check if the (correct) file is sitting next to the IDB.
        local_path = os.path.join(idautils.GetIdbDir(),
                                  idc.get_root_filename())
        if (os.path.exists(local_path) and hashlib.md5(
                open(local_path, "rb").read()).hexdigest().upper()
                == idc.retrieve_input_file_md5()):
            INPUT_FILE_PATH = local_path
            logger.debug("Guessed the input file path: " + INPUT_FILE_PATH)
            logger.debug("IDA thought it was:          " + ida_path)
            return True
        else:
            return False
    else:
        return True
Exemplo n.º 4
0
def load_kmdf_types_into_idb():
    header_path = idautils.GetIdbDir()
    idaapi.idc_parse_types("".join([header_path, "WDFStructs.h"]), idc.PT_FILE)
    for idx in range(1, idc.get_ordinal_qty()):
        #Fails to add some of the types
        print((idx, idc.get_numbered_type_name(idx)))
        idc.import_type(idx, idc.get_numbered_type_name(idx))
Exemplo n.º 5
0
def main():
    root_dir = idautils.GetIdbDir()

    local_module_name_list = get_local_module_name_list(root_dir)

    local_import_module_info_list = get_specify_import_modules_info(local_module_name_list)

    import_module_funcs = dict()
    for module_info in local_import_module_info_list:
        funcs = get_import_funcs(module_info["index"])
        import_module_funcs[module_info["name"]] = funcs


    dump_dict_to_file(os.path.join(root_dir, 'imports.json'), import_module_funcs)
Exemplo n.º 6
0
def initModules():
    global g_h2langDll
    global g_user32Dll
    global g_BaseAddress
    global g_TagGroupListAddress

    # Get the idb folder which will contains the h2alang.dll file.
    modulePath = idautils.GetIdbDir() + "h2alang.dll"

    # Check if the h2alang.dll module exists.
    if os.path.isfile(modulePath) is False:
        # The file does not exist, display a message to the user.
        idaapi.warning("Could not find \"%s\"!" % modulePath)
        return False

    try:
        # Load the h2alang.dll module.
        g_h2langDll = ctypes.cdll.LoadLibrary(modulePath)

        # Try to load the user32.dll module.
        g_user32Dll = ctypes.OleDLL("user32.dll")
    except Exception:
        # Failed to load the h2alang.dll file.
        idaapi.warning("Failed to load \"%s\"!" % modulePath)
        return False

    # Check the input file name to determine which hek tool we have loaded.
    moduleName = idc.GetInputFile()
    if moduleName == "H2Guerilla.exe":
        # Load values for h2 guerilla executable.
        g_BaseAddress = 0x400000
        g_TagGroupListAddress = 0x00901B90
    elif moduleName == "H2Sapien.exe":
        # Load values for h2 sapien executable.
        idaapi.warning("H2Sapien currently not supported!")
        return False
    elif moduleName == "H2Tool.exe":
        # Load values for h2 tool executable.
        idaapi.warning("H2Tool currently not supported!")
        return False
    else:
        # Unknown module.
        idaapi.warning("Unknown HEK module loaded!")
        return False

    # Initialized successfully.
    return True
Exemplo n.º 7
0
def wait_ready():
    global already_loaded
    if menu is None:
        if os.path.dirname(idautils.GetIdbDir()) == os.getcwd():
            create_menu()

    # Couldn't find a better way: IDA Hooks do not provide any event to
    # know when this happens. To be improved.
    prev_status = idc.SetStatus(IDA_STATUS_READY)
    idc.SetStatus(prev_status)

    if prev_status == IDA_STATUS_READY and (menu is not None):
        if not already_loaded:
            already_loaded = True
            menu.insert_hooks()
        return 0

    return 1000
def find_input_file():
    '''
    Description:
        Check whether or not IDA knows where the original file used to create the IDB is.
        If IDA doesn't know, check the IDA's directory for the file.

    Output:
        Returns True if the input file was located, False if it was not.
    '''
    global INPUT_FILE_PATH
    ida_path = INPUT_FILE_PATH
    if not os.path.exists(ida_path):
        # If IDA does not know, check if the (correct) file is sitting next to the IDB.
        local_path = os.path.join(idautils.GetIdbDir(), idc.GetInputFile())
        if os.path.exists(local_path) and \
                hashlib.md5(open(local_path, 'rb').read()).hexdigest().upper() == idc.GetInputMD5():
            INPUT_FILE_PATH = local_path
            append_debug('Guessed the input file path: ' + INPUT_FILE_PATH)
            append_debug('IDA thought it was:          ' + ida_path)
            return True
        else:
            return False
    else:
        return True
Exemplo n.º 9
0
    def _init(self):
        """
        Initialize plugin members.
        """

        # plugin color palette
        self.palette = LighthousePalette()

        # the coverage engine
        self.director = CoverageDirector(self.palette)

        # the coverage painter
        self.painter = CoveragePainter(self.director, self.palette)

        # the coverage overview widget
        self._ui_coverage_overview = None

        # menu entry icons
        self._icon_id_file = idaapi.BADADDR
        self._icon_id_batch = idaapi.BADADDR
        self._icon_id_overview = idaapi.BADADDR

        # the directory to start the coverage file dialog in
        self._last_directory = idautils.GetIdbDir()
Exemplo n.º 10
0
def hunt(symbols, dbname, merge=True, replace=False, bin_name="lina"):
    if bin_name == "lina":
        base_name = "lina_imagebase"
        addr_name = "addresses"
    elif bin_name == "lina_monitor":
        base_name = "lm_imagebase"
        addr_name = "lm_addresses"
    elif bin_name == "libc.so":
        base_name = "libc_imagebase"
        addr_name = "libc_addresses"
    else:
        logmsg("ERROR: bad elf name in hunt()")
        return None

    # parse version/fw from directory name
    idbdir = idautils.GetIdbDir()
    version = helper.build_version(idbdir)
    if not version:
        logmsg("Can't parse version in %s" % idbdir)
        sys.exit()
    fw = helper.build_bin_name(idbdir)
    if not fw:
        logmsg("Can't parse fw in %s" % idbdir)
        sys.exit()

    new_target = {}
    new_target["fw"] = fw
    new_target["arch"] = ida_helper.ARCHITECTURE
    # by default we don't know the imagebase so we will save
    # absolute addresses in new_target[addr_name]
    new_target[base_name] = 0
    # XXX - add fw md5 to db?

    prevtime = time.time()
    lock = filelock.FileLock("asadb.json")
    with lock.acquire():
        newtime = time.time()
        logmsg("Acquired lock after %d seconds" % int(newtime - prevtime))

        # load old targets
        targets = []
        if os.path.isfile(dbname):
            targets = helper.load_targets(dbname)
        else:
            logmsg("Creating new db: %s" % dbname)
        #logmsg("Existing targets:")
        #logmsg(targets)

        # Building new entry
        new_target["version"] = version
        addresses = {}
        for s, func in symbols.items():
            if not s:
                continue
            name = s
            if name.startswith("instruction_"):
                name = s[len("instruction_"):]
            # addr can actually be an address but also an offset we need
            # (e.g. tls->default_channel)...
            logmsg("Looking up %s" % s)
            addr = func(s)
            # we check both as we never want to add a -1 symbol and sometimes
            # the architecture detected is wrong and we ended up saving -1 :|
            if addr == 0xffffffffffffffff or addr == 0xffffffff or addr == None:
                logmsg("[x] Impossible to get '%s' symbol" % name)
                continue
            #logmsg("%s = 0x%x (%s)" % (name, addr, type(addr)))
            addresses[name] = addr
        #logmsg(addresses)
        new_target[addr_name] = addresses

        if helper.is_new(targets, new_target):
            logmsg("New target: %s (%s)" % (version, fw))
            logmsg(addresses)
            targets.append(new_target)
        elif merge == True:
            logmsg("Merging target: %s (%s)" % (version, fw))
            i = helper.merge_target(new_target, targets, bin_name=bin_name)
            if i != None:
                print(json.dumps(targets[i], indent=2))


#               print(targets[i])
            else:
                logmsg(
                    "Skipping target: %s (%s) as helper.merge_target() failed"
                    % (version, fw))
        elif replace == True:
            logmsg("Replacing target: %s (%s)" % (version, fw))
            helper.replace_target(new_target, targets)
            logmsg(new_target)
        else:
            logmsg("Skipping target: %s (%s)" % (version, fw))
        # sort targets by version. Drawback: index changes each time we add
        # a new firmware but it should not anymore once we have them all
        targets = sorted(targets,
                         key=lambda k: map(int, k["version"].split(".")))

        logmsg("Writing to %s" % dbname)
        open(dbname, "wb").write(json.dumps(targets, indent=4))
Exemplo n.º 11
0
def test():
    json_file = os.path.join(idautils.GetIdbDir().replace(
        'modules', 'log'), 'examples', 'ida_log_all_tpt480s.json')
    g = run(json_file)
    if g and DEBUG:
        print('[{}] graph created and displayed'.format(NAME))
Exemplo n.º 12
0
                    docstr_needed[entry] = s
                    break  # out of docstr iteration

    # update any results
    for called_in, lua_list in result.iteritems():
        for obj in lua_list:
            obj.docstr = docstr_needed[obj.name]

    # remove the defaultness to allow ez serialization
    return dict(result)


LOG.info("Noita IDAPython init")
idaapi.auto_wait()
LOG.info("analysis finished")
idb_path = idautils.GetIdbDir() + "noita_auto.idb"
LOG.info("saving IDB to {}".format(idb_path))
#idaapi.save_database(idb_path)

all_strings = idautils.Strings()

# do something useful?
lua_natives = get_all_registered_lua_natives()

# person who started IDA defined where the log file is, so they can parse this out of it.
# import ast; natives_fromlogs = ast.literal_eval(x.split("|lol|")[1])
# ...py3, need to re.sub(r"(\d+)L,", "\\1,", x)
natives_fordisk = []
for caller, natives in lua_natives.iteritems():
    natives_fordisk.extend([o.to_dict() for o in natives])
Exemplo n.º 13
0
 def init(self):
     self._last_directory = idautils.GetIdbDir()
     ui.init_menu(MenuHandler(self))
     self._welcome()
     return idaapi.PLUGIN_KEEP
Exemplo n.º 14
0
def get_dump_file():
    return os.path.join(idautils.GetIdbDir(), 'dump.json')
Exemplo n.º 15
0
 def get_database_directory(self):
     return idautils.GetIdbDir()
Exemplo n.º 16
0
 def __init__(self):
     super(tagstring_t, self).__init__()
     self.tags = []
     self.path = idautils.GetIdbDir() + "tags\\"
     self.base = idaapi.get_imagebase()
Exemplo n.º 17
0
addr_mask = 0xffff
default_name = ["sub_", "dword_", "qword_", "word_", "off_"]
restore_name = "off_%04X"


def in_default(name):
    res = False
    for defname in default_name:
        if name[:len(defname)] == defname:
            res = True
            break
    return res


filename = idc.AskStr("", "Input file name")
dirname = idautils.GetIdbDir()
if os.path.exists(filename):
    filepath = filename
elif os.path.exists(dirname + filename):
    filepath = dirname + filename
else:
    print("File Not Exist")
    exit()

items = []
with open(filename) as f:
    raw = f.read()
    lines = raw.split("\n")

    for i in lines:
        addr_raw = re_getaddr.search(i)
Exemplo n.º 18
0
 def getIdbDir(self):
     return idautils.GetIdbDir()
Exemplo n.º 19
0
def load_kmdf_types_into_idb():
    header_path = idautils.GetIdbDir()
    idaapi.idc_parse_types("".join([header_path, "WDFStructs.h"]), idc.PT_FILE)
    for idx in range(1, idc.GetMaxLocalType()):
        print(idx, idc.GetLocalTypeName(idx))
        idc.Til2Idb(idx, idc.GetLocalTypeName(idx))