def __init__(self, name): """initialize form elements""" super(CapaExplorerForm, self).__init__() self.form_title = name self.rule_path = os.path.join(ida_diskio.idadir("plugins"), "idacapa", "capa-rules") self.process_total = 0 self.process_count = 0 self.parent = None self.ida_hooks = None self.doc = None # models self.model_data = None self.range_model_proxy = None self.search_model_proxy = None # UI controls self.view_limit_results_by_function = None self.view_search_bar = None self.view_tree = None self.view_attack = None self.view_tabs = None self.view_menu_bar = None self.view_status_label = None self.view_buttons = None self.view_analyze_button = None self.view_reset_button = None self.Show()
def get_library(): dllname = "ida64" if ida_idaapi.__EA64__ else "ida" if sys.platform == "win32": dllname, dlltype = dllname + ".dll", ctypes.windll elif sys.platform == "linux2": dllname, dlltype = "lib" + dllname + ".so", ctypes.cdll elif sys.platform == "darwin": dllname, dlltype = "lib" + dllname + ".dylib", ctypes.cdll return dlltype[os.path.join(ida_diskio.idadir(None), dllname)]
def build_items(self): subdir = "" if is_ida_version("7.4"): subdir, _, _, _, _ = sys.version_info pydir = ida_diskio.idadir(os.path.join("python", str(subdir))) for mod_name in os.listdir(pydir): if mod_name.endswith(".py"): mod_name, _ = os.path.splitext(mod_name) if mod_name not in ["init", "idaapi"]: mod = __import__(mod_name) file_name = mod.__file__ for sym_name, obj in inspect.getmembers(mod): if inspect.isfunction(obj): data = ChooserData(mod_name, sym_name, file_name) data.sym_type = "function" data.line_no = "%d" % obj.func_code.co_firstlineno data.doc_str = inspect.getdoc(obj) self.items.append(data) elif inspect.isclass(obj): data = ChooserData(mod_name, sym_name, file_name) data.sym_type = "class" data.doc_str = inspect.getdoc(obj) self.items.append(data) elif inspect.ismethod(obj): data = ChooserData(mod_name, sym_name, file_name) data.sym_type = "method" data.line_no = "%d" % obj.im_func.func_code.co_firstlineno data.doc_str = inspect.getdoc(obj) self.items.append(data) elif type(obj) == int: data = ChooserData(mod_name, sym_name, file_name) data.sym_type = "int" data.sym_value = "0x%x" % (obj) self.items.append(data) elif type(obj) == long: data = ChooserData(mod_name, sym_name, file_name) data.sym_type = "long" data.sym_value = "0x%x" % (obj) self.items.append(data) elif type(obj) == str: data = ChooserData(mod_name, sym_name, file_name) data.sym_type = "str" data.sym_value = str(obj) self.items.append(data) else: if DBG: print "%s: %s" % (type(obj), sym_name)
def _load_filters(self, pw): filterdir = os.path.join(ida_diskio.idadir('plugins'), 'cyber') sys.path.append(filterdir) filters = [] for entry in os.listdir(filterdir): if entry.lower().endswith('.py') and entry.lower() != '__init__.py': mod = os.path.splitext(entry)[0] fmod = __import__(mod, globals(), locals(), [], 0) if fmod is not None: flt = fmod.FILTER_INIT(pw) if flt is not None: filters.append((fmod, flt)) return filters
def get_ida_dll(app_name=None): if app_name is None: app_path = QCoreApplication.applicationFilePath() app_name = QFileInfo(app_path).fileName() idaname = "ida64" if "64" in app_name else "ida" if sys.platform == "win32": dllname, dlltype = idaname + ".dll", ctypes.windll elif sys.platform in ["linux", "linux2"]: dllname, dlltype = "lib" + idaname + ".so", ctypes.cdll elif sys.platform == "darwin": dllname, dlltype = "lib" + idaname + ".dylib", ctypes.cdll dllpath = ida_diskio.idadir(None) if not os.path.exists(os.path.join(dllpath, dllname)): dllpath = dllpath.replace("ida64", "ida") return dlltype[os.path.join(dllpath, dllname)]
def get_items(): keywords = set() subdir = "" if is_ida_version("7.5"): subdir, _, _, _, _ = sys.version_info pydir = ida_diskio.idadir(os.path.join("python", str(subdir))) for mod_name in os.listdir(pydir): if mod_name.endswith(".py"): mod_name, _ = os.path.splitext(mod_name) if mod_name not in ["init", "idaapi"]: mod = __import__(mod_name) keywords.add(mod_name) for sym_name, obj in inspect.getmembers(mod): keywords.add(mod_name + "." + sym_name) return list(keywords)
def __init__(self): global hex_pytools_config self.section = "HexRaysPyTools features" self.file_path = os.path.join(ida_diskio.idadir(""), "cfg", "HexRaysPyTools.cfg") self.reader = ConfigParser.SafeConfigParser() self.reader.optionxform = str self.actions, self.action_names = self.GetDefActions() self.actions_refs = self.GetActionsRefs() hex_pytools_config = self try: f = open(self.file_path, "ab") f.close() except: print("Cannot open config file.") self.file_path = os.path.join(os.environ["APPDATA"], "IDA Pro", "cfg", "HexRaysPyTools.cfg") if not os.path.exists( os.path.join(os.environ["APPDATA"], "IDA Pro", "cfg")): os.makedirs( os.path.join(os.environ["APPDATA"], "IDA Pro", "cfg")) f = open(self.file_path, "ab") f.close() try: f = open(self.file_path, "rb") self.reader.readfp(f) f.close() fRewrite = False for ac in self.actions: if self.reader.has_option(self.section, ac): self.actions[ac] = self.reader.getboolean(self.section, ac) else: fRewrite = True if fRewrite: self.write_config() except ConfigParser.NoSectionError: self.actions, self.action_names = self.GetDefActions() del self.reader self.reader = ConfigParser.SafeConfigParser() self.reader.optionxform = str self.reader.add_section(self.section) for ac in self.actions: self.reader.set(self.section, ac, "true" if self.actions[ac] else "false") f = open(self.file_path, "wb") self.reader.write(f) f.close()
def build_items(self): pydir = ida_diskio.idadir("python") for name in os.listdir(pydir): if name.endswith(".py"): name, _ = os.path.splitext(name) if name not in ["init", "idaapi"]: mod = __import__(name) for symbol in dir(mod): try: attr = getattr(mod, symbol) docstr = attr.__doc__ module = attr.__module__ except AttributeError: docstr = "" module = "" except NameError: docstr = "" module = "" if not module.startswith("_"): self.items.append( (module, symbol, docstr.strip() if docstr else ""))
def _file_downloaded(self, database, progress, reply): """Called when the file has been downloaded.""" progress.close() # Get the absolute path of the file app_path = QCoreApplication.applicationFilePath() app_name = QFileInfo(app_path).fileName() file_ext = "i64" if "64" in app_name else "idb" file_name = "%s_%s.%s" % (database.project, database.name, file_ext) file_path = self._plugin.user_resource("files", file_name) # Write the file to disk with open(file_path, "wb") as output_file: output_file.write(reply.content) self._plugin.logger.info("Saved file %s" % file_name) # Save the old database database = ida_loader.get_path(ida_loader.PATH_TYPE_IDB) if database: ida_loader.save_database(database, ida_loader.DBFL_TEMP) # This is a very ugly hack used to open a database into IDA. We don't # have any function for this in the SDK, so I sorta hijacked the # snapshot functionality in this effect. # Get the library to call functions not present in the bindings idaname = "ida64" if "64" in app_name else "ida" if sys.platform == "win32": dllname, dlltype = idaname + ".dll", ctypes.windll elif sys.platform == "linux2": dllname, dlltype = "lib" + idaname + ".so", ctypes.cdll elif sys.platform == "darwin": dllname, dlltype = "lib" + idaname + ".dylib", ctypes.cdll dllpath = ida_diskio.idadir(None) if not os.path.exists(os.path.join(dllpath, dllname)): dllpath = dllpath.replace("ida64", "ida") dll = dlltype[os.path.join(dllpath, dllname)] # Close the old database using the term_database library function old_path = ida_loader.get_path(ida_loader.PATH_TYPE_IDB) if old_path: dll.term_database() # Open the new database using the init_database library function # This call only won't be enough because the user interface won't # be initialized, this is why the snapshot functionality is used for args = [app_name, file_path] argc = len(args) argv = (ctypes.POINTER(ctypes.c_char) * (argc + 1))() for i, arg in enumerate(args): arg = arg.encode("utf-8") argv[i] = ctypes.create_string_buffer(arg) v = ctypes.c_int(0) av = ctypes.addressof(v) pv = ctypes.cast(av, ctypes.POINTER(ctypes.c_int)) dll.init_database(argc, argv, pv) # Create a temporary copy of the new database because we cannot use # the snapshot functionality to restore the currently opened database file_ext = ".i64" if "64" in app_name else ".idb" tmp_file, tmp_path = tempfile.mkstemp(suffix=file_ext) shutil.copyfile(file_path, tmp_path) # This hook is used to delete the temporary database when all done class UIHooks(ida_kernwin.UI_Hooks): def database_inited(self, is_new_database, idc_script): self.unhook() os.close(tmp_file) if os.path.exists(tmp_path): os.remove(tmp_path) hooks = UIHooks() hooks.hook() # Call the restore_database_snapshot library function # This will initialize the user interface, completing the process s = ida_loader.snapshot_t() s.filename = tmp_path # Use the temporary database ida_kernwin.restore_database_snapshot(s, None, None)
def _database_downloaded(self, branch, progress, reply): """ Called when the file has been downloaded. :param branch: the branch :param progress: the progress dialog :param reply: the reply from the server """ # Close the progress dialog progress.close() # Get the absolute path of the file appPath = QCoreApplication.applicationFilePath() appName = QFileInfo(appPath).fileName() fileExt = 'i64' if '64' in appName else 'idb' fileName = '%s_%s.%s' % (branch.repo, branch.name, fileExt) filePath = local_resource('files', fileName) # Write the packet content to disk with open(filePath, 'wb') as outputFile: outputFile.write(reply.content) logger.info("Saved file %s" % fileName) # Save the old database database = ida_loader.get_path(ida_loader.PATH_TYPE_IDB) if database: ida_loader.save_database(database, ida_loader.DBFL_TEMP) # Get the dynamic library idaname = 'ida64' if '64' in appName else 'ida' if sys.platform == 'win32': dllname, dlltype = idaname + '.dll', ctypes.windll elif sys.platform == 'linux2': dllname, dlltype = 'lib' + idaname + '.so', ctypes.cdll elif sys.platform == 'darwin': dllname, dlltype = 'lib' + idaname + '.dylib', ctypes.cdll dllpath = ida_diskio.idadir(None) if not os.path.exists(os.path.join(dllpath, dllname)): dllpath = dllpath.replace('ida64', 'ida') dll = dlltype[os.path.join(dllpath, dllname)] # Close the old database oldPath = ida_loader.get_path(ida_loader.PATH_TYPE_IDB) if oldPath: dll.term_database() # Open the new database LP_c_char = ctypes.POINTER(ctypes.c_char) args = [appName, filePath] argc = len(args) argv = (LP_c_char * (argc + 1))() for i, arg in enumerate(args): arg = arg.encode('utf-8') argv[i] = ctypes.create_string_buffer(arg) LP_c_int = ctypes.POINTER(ctypes.c_int) v = ctypes.c_int(0) av = ctypes.addressof(v) pv = ctypes.cast(av, LP_c_int) dll.init_database(argc, argv, pv) # Create a copy of the new database fileExt = '.i64' if '64' in appName else '.idb' tmpFile, tmpPath = tempfile.mkstemp(suffix=fileExt) shutil.copyfile(filePath, tmpPath) class UIHooks(ida_kernwin.UI_Hooks): def database_inited(self, is_new_database, idc_script): self.unhook() # Remove the tmp database os.close(tmpFile) if os.path.exists(tmpPath): os.remove(tmpPath) hooks = UIHooks() hooks.hook() # Open the tmp database s = ida_loader.snapshot_t() s.filename = tmpPath ida_kernwin.restore_database_snapshot(s, None, None)
if __EA64__: CAPSTONE_MODE = capstone.CS_MODE_64 SIG_EXT = ".sig64" idenLibCache = local_appdata + os.sep + PLUGIN_NAME + os.sep + "idenLibCache64" idenLibCacheMain = local_appdata + os.sep + PLUGIN_NAME + os.sep + "idenLibCacheMain64" else: CAPSTONE_MODE = capstone.CS_MODE_32 SIG_EXT = ".sig" idenLibCache = local_appdata + os.sep + PLUGIN_NAME + os.sep + "idenLibCache" idenLibCacheMain = local_appdata + os.sep + PLUGIN_NAME + os.sep + "idenLibCacheMain" idenLib_appdata = local_appdata + os.sep + PLUGIN_NAME func_sigs = {} mainSigs = {} ida_dir = ida_diskio.idadir("") symEx_dir = ida_dir + os.sep + "SymEx" def getNames(): for ea, name in idautils.Names(): yield name def getFiles(path): for file in os.listdir(path): if os.path.isfile(os.path.join(path, file)): yield path + "\\" + file # return (start_ea, size)
sys.stdout = sys.stderr = IDAPythonStdOut() # ----------------------------------------------------------------------- # Initialize the help, with our own stdin wrapper, that'll query the user # ----------------------------------------------------------------------- import pydoc class IDAPythonHelpPrompter: def readline(self): return ida_kernwin.ask_str('', 0, 'Help topic?') help = pydoc.Helper(input = IDAPythonHelpPrompter(), output = sys.stdout) # Assign a default sys.argv sys.argv = [""] # Have to make sure Python finds our modules sys.path.append(ida_diskio.idadir("python")) # Remove current directory from the top of the patch search if '' in sys.path: # On non Windows, the empty path is added sys.path.remove('') if os.getcwd() in sys.path: sys.path.remove(os.getcwd()) # ...and add it to the end if needed if not IDAPYTHON_REMOVE_CWD_SYS_PATH: sys.path.append(os.getcwd()) if IDAPYTHON_COMPAT_AUTOIMPORT_MODULES: # Import all the required modules from idaapi import get_user_idadir, cvar, Appcall, Form
# ----------------------------------------------------------------------- import pydoc class IDAPythonHelpPrompter: def readline(self): return ida_kernwin.ask_str('', 0, 'Help topic?') help = pydoc.Helper(input=IDAPythonHelpPrompter(), output=sys.stdout) # Assign a default sys.argv sys.argv = [""] # Have to make sure Python finds our modules sys.path.append(ida_diskio.idadir("python")) # Remove current directory from the top of the patch search if '' in sys.path: # On non Windows, the empty path is added sys.path.remove('') if os.getcwd() in sys.path: sys.path.remove(os.getcwd()) # ...and add it to the end if needed if not IDAPYTHON_REMOVE_CWD_SYS_PATH: sys.path.append(os.getcwd()) if IDAPYTHON_COMPAT_AUTOIMPORT_MODULES: # Import all the required modules from idaapi import get_user_idadir, cvar, Appcall, Form
# Allow the user to override the download URL if 'URL' not in locals(): URL = 'https://github.com/IDArlingTeam/IDArling/archive/master.zip' print('[*] Installing IDArling...') if os.name == 'nt': # Install into the user directory on Windows userDir = ida_diskio.get_user_idadir() if not os.path.exists(userDir): os.makedirs(userDir, 0755) destDir = os.path.join(userDir, 'idarling') if not os.path.exists(destDir): os.makedirs(destDir, 0755) else: # Install into the plugins directory on Linux destDir = os.path.join(ida_diskio.idadir(None), 'plugins') print('[*] Downloading master.zip archive...') archivePath = os.path.join(destDir, 'master.zip') if os.path.exists(archivePath): os.remove(archivePath) with open(archivePath, 'wb') as f: f.write(urllib2.urlopen(URL).read()) print('[*] Unzipping master.zip archive...') archiveDir = os.path.join(destDir, 'IDArling-master') if os.path.exists(archiveDir): shutil.rmtree(archiveDir) with zipfile.ZipFile(archivePath, 'r') as zip: for zipfile in zip.namelist(): if zipfile.startswith(os.path.basename(archiveDir)):
# Allow the user to override the download URL if "URL" not in locals(): URL = "https://github.com/IDArlingTeam/IDArling/archive/master.zip" print("[*] Installing IDArling...") if os.name == "nt": # Install into the user directory on Windows user_dir = ida_diskio.get_user_idadir() if not os.path.exists(user_dir): os.makedirs(user_dir, 493) # 0755 dest_dir = os.path.join(user_dir, "idarling") if not os.path.exists(dest_dir): os.makedirs(dest_dir, 493) # 0755 else: # Install into the plugins directory on Linux/macOS dest_dir = os.path.join(ida_diskio.idadir(None), "plugins") print("[*] Downloading master.zip archive...") archive_path = os.path.join(dest_dir, "master.zip") if os.path.exists(archive_path): os.remove(archive_path) with open(archive_path, "wb") as f: f.write(urllib2.urlopen(URL).read()) print("[*] Unzipping master.zip archive...") archive_dir = os.path.join(dest_dir, "IDArling-master") if os.path.exists(archive_dir): shutil.rmtree(archive_dir) with zipfile.ZipFile(archive_path, "r") as zip: for zip_file in zip.namelist(): if zip_file.startswith(os.path.basename(archive_dir)):