Exemple #1
0
    def Dark(self):
        g = globals()
        idahome = idaapi.idadir("plugins\\scylla")
        if __EA64__:
            subprocess.Popen(idahome + '\\Scylla_x64.exe')
    
        else:
            g = globals()
            idahome = idaapi.idadir("plugins\\scylla")

            subprocess.Popen(idahome + '\\Scylla_x86.exe')
Exemple #2
0
    def Dark(self):
        g = globals()
        idahome = idaapi.idadir("plugins\\scylla")
        if __EA64__:
            subprocess.Popen(idahome + '\\Scylla_x64.exe')

        else:
            g = globals()
            idahome = idaapi.idadir("plugins\\scylla")

            subprocess.Popen(idahome + '\\Scylla_x86.exe')
Exemple #3
0
def start_communication_manager():
    si = subprocess.STARTUPINFO()
    si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    print " ".join([
        "python",
        "{0}\communication_manager.py".format(idaapi.idadir("plugins")),
        str(INTEGRATOR_WINDOW_ID),
        str(COMMUNICATION_MANAGER_WINDOW_ID)
    ])
    subprocess.Popen([
        "python",
        "{0}\communication_manager.py".format(idaapi.idadir("plugins")),
        str(INTEGRATOR_WINDOW_ID),
        str(COMMUNICATION_MANAGER_WINDOW_ID)
    ])
Exemple #4
0
def load_plugins():
    import idaapi

    plugins_dir = idaapi.idadir("plugins")
    files = [f for f in os.listdir(plugins_dir) if re.match(r".*\.py", f)]
    for path in files:
        idaapi.load_plugin(path)
Exemple #5
0
    def __get_old_psy_version(self, start_addr: int, end_addr: int) -> str:
        psyq_dir = idaapi.idadir(os.path.join('loaders', 'psyq'))

        dirs = list()
        for ver, _, _ in os.walk(psyq_dir):
            vv = os.path.basename(ver)
            if vv in DetectPsyQ.OLD_VERSIONS:
                dirs.append(ver)

        for ver_dir in dirs:
            lib_json_file = os.path.join(ver_dir, '%s.json' % DetectPsyQ.OLD_UNIQUE_LIB)
            sig = SigApplier(self._game_id, lib_json_file, None, self._only_first, self._min_entropy)

            signatures = sig.get_signatures()

            for item in signatures:
                if item.get_name() != DetectPsyQ.OLD_UNIQUE_OBJ:
                    continue

                bytes_data = item.get_sig()

                offset, _ = masked_search(start_addr, end_addr, bytes_data.get_bytes(), bytes_data.get_masks())

                if offset != idaapi.BADADDR:
                    return os.path.basename(ver_dir)

        return ''
Exemple #6
0
 def load_proto(self):
     fns_file = idaapi.idadir("loaders") + os.sep + "vita_functions.h"
     try:        
         with open(fns_file, "r") as fin:
             self.proto = fin.read().split("\n")
     except IOError:
         raise Exception("Could not open " + fns_file)
Exemple #7
0
    def __init__(self):

        self.addmenu_item_ctxs = list()
        self.path = idaapi.idadir( os.path.join("plugins","idapomidor","images") )

        self.pomidors = list()

        # Initialize the timer
        # NOTE: QTimer is a lot more stable compared to idaapi.register_timer()
        #       unfortunately this requires PySide installation.
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.timer_callback)

        self.qapp = QtCore.QCoreApplication.instance()

        self.pomidorForm = None
        self.pomidorView = PomidorView(self, embedded=True)

        self.interval = 1000

        self.duration = 0
        self.duration_stop = 0
        self.duration_settings = {"Pomidor": 25*60, "Short break": 5*60, "Long break": 15*60}

        self.update = 0

        self.t = None
Exemple #8
0
def plugin_resource(resource_name):
    """
    Return the full path for a given plugin resource file.
    """
    return os.path.join(
        idaapi.idadir(idaapi.PLG_SUBDIR),
        prefix_t.wanted_name,
        "resources",
        resource_name
    )
Exemple #9
0
def plugin_resource(resource_name):
    """
    Return the full path for a given plugin resource file.
    """
    return os.path.join(
        idaapi.idadir(idaapi.PLG_SUBDIR),
        prefix_t.wanted_name,
        "resources",
        resource_name
    )
Exemple #10
0
    def run(self):
        print("IDA Code Editor | Dev Bym24v")
        #myIP = socket.gethostbyname(socket.gethostname())
        # bind address
        self.address = "%s:%s" % (HOST, self.sockets[0].getsockname()[1])

        application = tornado.web.Application([
            (r'/', MainHandler, dict(address=self.address, title=self.title)),
            (r'/css/(.*)', tornado.web.StaticFileHandler, {
                "path": idaapi.idadir("plugins\\IDACodeEditor\\public\\css")
            }),
            (r'/js/(.*)', tornado.web.StaticFileHandler, {
                "path": idaapi.idadir("plugins\\IDACodeEditor\\public\\js")
            }), (r'/ws', WSHandler)
        ])
        asyncio.set_event_loop(asyncio.new_event_loop())
        server = tornado.httpserver.HTTPServer(application)
        server.add_sockets(self.sockets)
        tornado.ioloop.IOLoop.instance().start()
Exemple #11
0
def plugin_resource(resource_name):
    """
    Return the full path for a given plugin resource file.
    """
    return os.path.join(
        idaapi.idadir(idaapi.PLG_SUBDIR),
        "lighthouse",
        "ui",
        "resources",
        resource_name
    )
Exemple #12
0
def _ida_lib():
    ea_name = 'ida64' if idc.__EA64__ else 'ida'
    if sys.platform == 'win32':
        functype = ctypes.WINFUNCTYPE
        lib = ctypes.WinDLL(ea_name)
    elif sys.platform == 'darwin':
        functype = ctypes.CFUNCTYPE
        lib = ctypes.CDLL(idaapi.idadir("lib" + ea_name + ".dylib"))
    else:
        functype = ctypes.CFUNCTYPE
        lib = ctypes.CDLL('lib' + ea_name + '.so')
    return functype, lib
Exemple #13
0
def _ida_lib():
    ea_name = 'ida64' if idc.__EA64__ else 'ida'
    if sys.platform == 'win32':
        functype = ctypes.WINFUNCTYPE
        lib = ctypes.WinDLL(ea_name)
    elif sys.platform == 'darwin':
        functype = ctypes.CFUNCTYPE
        lib = ctypes.CDLL(idaapi.idadir("lib" + ea_name + ".dylib"))
    else:
        functype = ctypes.CFUNCTYPE
        lib = ctypes.CDLL('lib' + ea_name + '.so')
    return functype, lib
Exemple #14
0
def ExecuteFileScript():

    g = globals()

    try:

        # ida dir
        path_ida = idaapi.idadir("plugins\\IDACodeEditor")

        # Execute
        IDAPython_ExecScript(path_ida + "\\code.py", g)

    except:
        print("[ERROR] Error Execute Script")
Exemple #15
0
    def load_nids(self):    
        db_file = idaapi.idadir("loaders") + os.sep + "db.yml"
        try:        
            with open(db_file, "r") as fin:
                data = fin.read().split("\n")
        except IOError:
            raise Exception("Could not open " + db_file)

        for line in data:
            if "0x" in line and "nid: " not in line:
                name, nid = line.strip().split(":")
                name = name.strip()
                nid = int(nid.strip(), 16)
                self.nid_to_name[nid] = name
Exemple #16
0
def WriteFileScript(code):

    try:
        # ida dir
        path_ida = idaapi.idadir("plugins\\IDACodeEditor")

        # Write file folder
        file = open(path_ida + "\\code.py", "w")
        file.write(code)  # write
        file.close()  # close

        # Execute Script
        execute_in_main_thread(ExecuteFileScript)
    except:
        print("[ERROR] Error Write File")
Exemple #17
0
    def init(self):
        if constants.create_general_config_file(
        ):  # if the Config file didnt exist, we want to ask for a server name.
            server = idc.AskStr("", "Server:")
            constants.set_data_to_config_file("server", server)

        shared.BASE_URL = constants.get_data_from_config_file("server")
        shared.LOG = constants.get_data_from_config_file("log")

        self._window_handler = create_hidden_window()
        self._id = insert_to_registery(self._window_handler)
        log("Created window")

        shared.INTEGRATOR_WINDOW_ID = self._id
        shared.COMMUNICATION_MANAGER_WINDOW_ID = struct.unpack(
            ">I", os.urandom(4))[0]
        si = subprocess.STARTUPINFO()
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        subprocess.Popen([
            "python",
            "{0}\communication_manager.py".format(idaapi.idadir("plugins")),
            str(shared.INTEGRATOR_WINDOW_ID),
            str(shared.COMMUNICATION_MANAGER_WINDOW_ID)
        ])
        time.sleep(1)

        shared.IS_COMMUNICATION_MANAGER_STARTED = True
        if shared.USERID != -1:  #started.
            communication_manager_window_handler = constants.get_window_handler_by_id(
                shared.COMMUNICATION_MANAGER_WINDOW_ID)
            constants.send_data_to_window(
                communication_manager_window_handler,
                constants.CHANGE_PROJECT_ID,
                json.dumps({"project-id": shared.PROJECT_ID}))
            constants.send_data_to_window(
                communication_manager_window_handler, constants.CHANGE_USER,
                json.dumps({
                    "username": shared.USERNAME,
                    "id": shared.USERID,
                    "token": shared.USER_TOKEN
                }))

        self.hook()
        for widget in qApp.topLevelWidgets():
            if isinstance(widget, QMainWindow):
                self._window = widget
                break
        return idaapi.PLUGIN_KEEP
Exemple #18
0
def load_idb(path):
    cmd = idaapi.idadir('ida')
    if float(idaapi.get_kernel_version()) < 7:
        cmd += 'q'
    if path.endswith('.i64'):
        cmd += '64'

    my_path = os.path.abspath(os.path.expanduser(__file__))
    if os.path.islink(my_path):
        my_path = os.readlink(my_path)
    f = os.path.join(os.path.dirname(os.path.dirname(my_path)), 'run.py')

    p = QProcess()
    p.startDetached(cmd, ['-S%s' % f, path])
    wait(3)
    idc.ProcessUiAction('Quit', 0)
Exemple #19
0
def _generate_hotkey_table():
    ida_plugins_dir = idaapi.idadir("plugins")
    ida_plugins_cfg_path = os.path.join(ida_plugins_dir, 'plugins.cfg')
    list_lines = open(ida_plugins_cfg_path, 'r').readlines()
    first_index = list_lines.index(';REDB: ENTER\n') + 1
    try:
        last_index = list_lines.index(';REDB: EXIT\n')
    except:
        last_index = list_lines.index(';REDB: EXIT')
    hotkeys = []
    list_lines = list_lines[first_index:last_index]
    for line in list_lines:
        split_line = line.split("\t")
        hotkeys.append((split_line[0].replace('_', ' '), split_line[2]))

    return hotkeys
Exemple #20
0
    def set_default_values(self):
        """
        Set installation default values.
        """
        ida_plugins = idaapi.idadir("plugins")

        self.__ghidra_plugins_path = os.path.join(ida_plugins, "ghida_plugin",
                                                  "ghidra_plugin")
        if 'linux' in sys.platform:
            self.__ghidra_install_path = LP
            self.__ghidra_headless_path = os.path.join(
                self.__ghidra_install_path, "support", "analyzeHeadless")
        else:
            self.__ghidra_install_path = WP
            self.__ghidra_headless_path = os.path.join(
                self.__ghidra_install_path, "support", "analyzeHeadless.bat")
        self.__ghidra_server_url = GAAS
Exemple #21
0
def load_signatures():
    db = idadir("plugins/findhash.xml")
    if not os.path.isfile(db):
        db = os.path.join(get_user_idadir(), "plugins/findhash.xml")
    root = ET.parse(db).getroot()

    signature = []
    for p in root:
        name, data = p.attrib['t'].split(" [")
        bits, size = data[:-1].split(".")
        bits = int(bits)

        signature.append({
            "name": name,
            "bits": bits,
            "size": int(size),
            "data": codecs.decode(p.text, ('hex')),
        })

    return signature
Exemple #22
0
    def apply_psyq_signatures_by_version(self, ver: str) -> None:
        ida_psyq = idaapi.idadir(os.path.join(idaapi.LDR_SUBDIR, 'psyq'))
        patches_file = os.path.join(ida_psyq, 'patches.json')
        ver_dir = os.path.join(ida_psyq, ver)

        files = list()
        for file in os.listdir(ver_dir):
            if file.endswith('.json'):
                files.append(file)

        for file in files:
            fn = os.path.basename(file)

            if fn in self._appliers:
                sig = self._appliers[fn]
            else:
                sig = SigApplier(self._exe_name, os.path.join(ver_dir, file), patches_file,
                                 self._only_first, self._min_entropy)
                self._appliers[fn] = sig

            sig.apply_signatures(self.rom_addr, self.rom_addr + self.rom_size)
Exemple #23
0
def load_function_set():

    function_addresses = set()

    dataf_path = idaapi.idadir('function_set.txt')
    if os.path.exists(dataf_path) and os.path.isfile(dataf_path):

        dataf = file(dataf_path, 'rt')
        while True:

            line = dataf.readline()
            if not line:
                break
            try:
                function_addresses.add(int(line, 16))
            except ValueError:
                pass

        dataf.close()

    return function_addresses
Exemple #24
0
def load_function_set():
    
    function_addresses = set()
    
    dataf_path = idaapi.idadir('function_set.txt')
    if os.path.exists(dataf_path) and os.path.isfile(dataf_path):
    
        dataf = file(dataf_path, 'rt')
        while True:
        
            line = dataf.readline()
            if not line:
                break
            try:
                function_addresses.add(int(line, 16))
            except ValueError:
                pass
            
        dataf.close()
            
    return function_addresses
# Created by: Storm Shadow http://www.techbliss.org

# WARNING! All changes made in this file will be lost!
import re
import idaapi
import idc
from idc import *
from idaapi import *
import sys
sys.path.insert(0 , idaapi.idadir("plugins\\recorder\\icons"))
import ico
from ico import *
class hawk(idaapi.plugin_t):
    flags = idaapi.PLUGIN_FIX
    comment = "This is a comment"

    help = "Screen Recorder"
    wanted_name = "Screen Recorder"
    wanted_hotkey = "Shift-R"



    def init(self):
        idaapi.msg("Screen Recorder Is Found Use Shift-R to load to menu \n")
        return idaapi.PLUGIN_OK


    def run(self, arg):
        idaapi.msg("run() called with %d!\n" % arg)

    def term(self):
Exemple #26
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)
import glob
import os
import itertools
import idaapi
import idc

PLUGINS_LIST = "plugins-{}.list".format(idaapi.get_kernel_version())

USER_PLUGIN_LIST_PATH = os.path.join(idaapi.get_user_idadir(), PLUGINS_LIST)
SYS_PLUGIN_LIST_PATH = os.path.join(idaapi.idadir(idaapi.CFG_SUBDIR),
                                    PLUGINS_LIST)
if idc.GetIdbPath():
    PROJECT_PLUGIN_LIST_PATH = os.path.join(os.path.dirname(idc.GetIdbPath()),
                                            PLUGINS_LIST)
else:
    PROJECT_PLUGIN_LIST_PATH = None


def message(*messages):
    for msg in messages:
        for line in msg.splitlines():
            idaapi.msg("[PluginLoader] {}\n".format(line))


def iter_without_duplicates(*iterables):
    visited = set()
    chained_iterables = itertools.chain(*iterables)
    for item in chained_iterables:
        if item in visited:
            continue
        yield item
Exemple #28
0
"""
BB matcher initialization script.

This script ensures that it runs once per Python runtime.


11/07/2013 - eliasb - Initial version
"""

import os
import sys
import idaapi

# Get the script path
lib_path = os.path.join(idaapi.idadir("plugins"), "GraphSlick")

# Run this code once by checking if the required scripts
# are in the path
if lib_path not in sys.path:
    sys.path.append(lib_path)
    print sys.path

    # Import the matcher module
    import bb_match

    #print "Imported"
else:
    #print "Already imported"
    pass
Exemple #29
0
 def popeye(self):
     g = globals()
     idahome = idaapi.idadir("plugins\\Code editor")
     IDAPython_ExecScript(idahome + "\\pyeditor.py", g)
Exemple #30
0
def resource_file(filename):
    """
    Return the absolute 'resource' filepath for a given filename.
    """
    return os.path.join(idaapi.idadir("plugins"), "lighthouse", "ui",
                        "resources", filename)
import idaapi
import os,sys, types
from idc import *
from payload import Item
from copy import deepcopy
import dataviewers

drgadget_plugins_path = idaapi.idadir(os.path.join("plugins", "drgadget", "plugins"))

sys.path.append(drgadget_plugins_path)

# TODO: remove load- and save payload dialogs from context menu
# and move to IDA's File menu?
class ropviewer_t(idaapi.simplecustviewer_t):

    def __init__(self, payload):
        self.payload = payload

        # FIXME: ugly
        self.menu_loadfromfile  = None
        self.menu_savetofile    = None
        self.menu_copyitem      = None
        self.menu_cutitem       = None
        self.menu_pasteitem     = None
        self.menu_insertitem    = None
        self.menu_jumpto        = None
        self.menu_toggle        = None
        self.menu_deleteitem    = None
        self.menu_edititem      = None
        self.menu_reset         = None
 
 def popeye(self):
     g = globals()
     idahome = idaapi.idadir("plugins\\Code editor")
     IDAPython_ExecScript(idahome +  "\\pyeditor.py", g)
Exemple #33
0
def loadAllPythonPlugins():
    plugins_dir = idaapi.idadir('plugins')
    print("idascript: loading all .py plugins in %s" % plugins_dir)
    files = [f for f in os.listdir(plugins_dir) if re.match(r'.*\.py', f)]
    for path in files:
        idaapi.load_plugin(path)
Exemple #34
0
import os
import idaapi
import itertools

PLUGINS_LIST = "plugins.list"

USER_PLUGIN_LIST_PATH = os.path.join(idaapi.get_user_idadir(), PLUGINS_LIST)
SYS_PLUGIN_LIST_PATH = os.path.join(idaapi.idadir(idaapi.CFG_SUBDIR), PLUGINS_LIST)


def message(*messages):
    for msg in messages:
        for line in msg.splitlines():
            idaapi.msg("[PluginLoader] {}\n".format(line))


def iter_without_duplicates(*iterables):
    visited = set()
    chained_iterables = itertools.chain(*iterables)
    for item in chained_iterables:
        if item in visited:
            continue
        yield item
        visited.add(item)


def iter_paths(filepath):
    try:
        with open(filepath) as f:
            for line in f:
                # Use `#` for comments
 def Toast(self):
     g = globals()
     idahome = idaapi.idadir("QTApps\\diaphora")
     IDAPython_ExecScript(idahome +  "\\diaphora_loader.py", g)
 def run(self, arg):
     jarvis_loc = os.path.join('plugins', 'jarvis', 'jarvis.py')
     full_path = idaapi.idadir(jarvis_loc)
     idaapi.load_and_run_plugin(full_path, 0)
 def Poppers(self):
     g = globals()
     idahome = idaapi.idadir("QTApps\\Frida")
     IDAPython_ExecScript(idahome +  "\\Frida_For_Ida_Pro.py", g)
Exemple #38
0
    import idaapi
except ImportError:
    # This module can sometimes be invoked outside IDA, so
    # don't blow up if that happens
    #
    pass


ida2sql_path = os.environ.get('IDA2SQLPATH', None)

if ida2sql_path:
    print 'Environment variable IDA2SQLPATH found: [%s]' % ida2sql_path
    os.sys.path.append(ida2sql_path)
else:
    print 'Environment variable IDA2SQLPATH not found'
    os.sys.path.append(idaapi.idadir(os.path.join('plugins', 'ida2sql.zip')))

# Import the main module located in the IDA plugins directory
#

import ida_to_sql

import ida_to_sql.common

__version__ = ida_to_sql.common.__version__

# Start the exporter
#
ida_to_sql.ida_to_sql.main()

#import cProfile
 def eyes(self):
     g = globals()
     idahome = idaapi.idadir("plugins\\recorder")
     IDAPython_ExecScript(idahome +  "\\rec_main.py", g)
# Created by: Storm Shadow http://www.techbliss.org

import re
import idaapi
import idc
from idc import *
from idaapi import *
import sys
sys.path.insert(0 , idaapi.idadir("plugins\\Code editor\\icons"))
import ico
from ico import *
class ripeye(idaapi.plugin_t):
    flags = idaapi.PLUGIN_FIX
    comment = "This is a comment"

    help = "Python Editor"
    wanted_name = "Python Editor"
    wanted_hotkey = "ALT-E"



    def init(self):
        idaapi.msg("Python Editor Is Found Use Alt+E to load to menu \n")
        return idaapi.PLUGIN_OK


    def run(self, arg):
        idaapi.msg("run() called with %d!\n" % arg)

    def term(self):
        idaapi.msg("")
Exemple #41
0
#!/usr/bin/python
# coding: utf-8
#
# HeapViewer - by @danigargu
#

import idaapi
import os
import sys

PLUGIN_DIR = idaapi.idadir(os.path.join("plugins", "heap_viewer"))
sys.path.append(PLUGIN_DIR)

idaapi.require('plugin_gui')

#------------------------------------------------------------------------

from plugin_gui import HeapPluginForm, PLUGNAME

# -----------------------------------------------------------------------
class HeapViewPlugin(idaapi.plugin_t):
    flags = 0
    comment = ""
    help = ""
    wanted_name = PLUGNAME
    wanted_hotkey = "Ctrl-H"

    def init(self):
        self.icon_id = 0
        return idaapi.PLUGIN_KEEP
Exemple #42
0
# Created by: Storm Shadow http://www.techbliss.org

import re
import idaapi
import idc
from idc import *
from idaapi import *
import sys
sys.path.insert(0, idaapi.idadir("plugins\\Code editor\\icons"))
import ico
from ico import *


class ripeye(idaapi.plugin_t):
    flags = idaapi.PLUGIN_FIX
    comment = "This is a comment"

    help = "Python Editor"
    wanted_name = "Python Editor"
    wanted_hotkey = "ALT-E"

    def init(self):
        idaapi.msg("Python Editor Is Found Use Alt+E to load to menu \n")
        return idaapi.PLUGIN_OK

    def run(self, arg):
        idaapi.msg("run() called with %d!\n" % arg)

    def term(self):
        idaapi.msg("")
Exemple #43
0
# pylint: disable=invalid-name,protected-access
import ctypes
import os
import traceback

import idaapi

from ..config import g, _save_config
from ..env import ea as current_ea, os as current_os, version_info
from ..logger import getLogger
from ..process import system

IDADIR = idaapi.idadir('')
log = getLogger(__name__)


def _os_error():
    return Exception("unknown os: %r" % current_os)


def _ida_lib_path(ea):
    ea_name = 'ida64' if ea == 64 else 'ida'
    if current_os == 'win':
        path = os.path.join(IDADIR, ea_name + ".dll")
    elif current_os == 'mac':
        path = os.path.join(IDADIR, "lib" + ea_name + ".dylib")
    elif current_os == 'linux':
        path = os.path.join(IDADIR, "lib" + ea_name + ".so")
    else:
        raise _os_error()
    return os.path.normpath(path)
Exemple #44
0
                    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")

    return success


#main
#set the maximum name length or we'll get failures in set_name()
idc.SetLongPrm(idc.INF_NAMELEN, 500)
pythoncom.CoInitialize()
iMan = pyTypeLibs.interfaceMan()
tMan = pyTypeLibs.typeLibMan(iMan)
tMan.addRegistryTypeLibs()
tlbDir = idaapi.idadir("python") + os.sep + "sdk-tlbs"

for f in os.listdir(tlbDir):
    tFile = os.path.join(tlbDir, f)
    tMan.addTypeLibFile(tFile)

iMan.addSystemInterfaces()

inFile = idaapi.get_input_file_path()
if not queryFile(inFile, tMan, iMan):
    clsid = idc.AskStr(None, "Enter a CLSID to instantiate?")
    name = idc.AskStr("tmpCoClass", "Now give it a name")
    if clsid and clsid != "":
        queryFile(inFile, tMan, iMan, clsid, name)
Exemple #45
0
 def Toast(self):
     g = globals()
     idahome = idaapi.idadir("QTApps\\Pips")
     IDAPython_ExecScript(idahome +  "\\pips.py", g)
Exemple #46
0
"""Module for reading from and writing to the bap.cfg config file."""

import os
import idaapi

cfg_dir = idaapi.idadir('cfg')
cfg_path = os.path.join(cfg_dir, 'bap.cfg')


def _read():
    if not os.path.exists(cfg_path):
        return {}
    cfg = {'default': []}
    with open(cfg_path, 'r') as f:
        current_section = 'default'
        for line in f.read().split('\n'):
            if len(line) == 0:  # Empty line
                continue
            elif line[0] == '.':  # Section
                current_section = line[1:]
                if current_section not in cfg:
                    cfg[current_section] = []
            else:
                cfg[current_section].append(line)
    return cfg


def _write(cfg):
    new_config = []
    for section in cfg:
        new_config.append('.' + section)
 def AdbCall(self):
     g = globals()
     idahome = idaapi.idadir("QTApps\\SuperADB")
     IDAPython_ExecScript(idahome +  "\\ADB_QT.py", g)
# Created by: Storm Shadow http://www.techbliss.org

# WARNING! All changes made in this file will be lost!
import re
import idaapi
import idc
from idc import *
from idaapi import *
import sys

sys.path.insert(0, idaapi.idadir("plugins\\geo\\icons"))
import ico
from ico import *
import subprocess
from subprocess import Popen


class ripeyess(idaapi.plugin_t):
    flags = idaapi.PLUGIN_FIX
    comment = "This is a comment"

    help = "geo"
    wanted_name = "http ip locator"
    wanted_hotkey = "ALT-G"

    def init(self):
        idaapi.msg("http ip locator Is Found Use Alt+G to load to menu \n")
        return idaapi.PLUGIN_OK

    def run(self, arg):
        idaapi.msg("run() called with %d!\n" % arg)
Exemple #49
0
        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")

    return success

#main
#set the maximum name length or we'll get failures in set_name()
idc.SetLongPrm(idc.INF_NAMELEN, 500)
pythoncom.CoInitialize()
iMan = pyTypeLibs.interfaceMan()
tMan = pyTypeLibs.typeLibMan(iMan)
tMan.addRegistryTypeLibs()
tlbDir = idaapi.idadir("python") + os.sep + "sdk-tlbs"

for f in os.listdir(tlbDir):
    tFile = os.path.join(tlbDir, f)
    tMan.addTypeLibFile(tFile)

iMan.addSystemInterfaces()

inFile = idaapi.get_input_file_path()
if not queryFile(inFile, tMan, iMan):
    clsid = idc.AskStr(None, "Enter a CLSID to instantiate?")
    name = idc.AskStr("tmpCoClass", "Now give it a name")
    if clsid and clsid != "":
        queryFile(inFile, tMan, iMan, clsid, name)
Exemple #50
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 popeye(self):
     idahome = idaapi.idadir("plugins\\geo")
     os.chdir(idahome)
     subprocess.Popen('python.exe geo.py')
Exemple #52
0
"""Module for reading from and writing to the bap.cfg config file."""

import os
import idaapi

cfg_dir = idaapi.idadir('cfg')
cfg_path = os.path.join(cfg_dir, 'bap.cfg')


def _read():
    if not os.path.exists(cfg_path):
        return {}
    cfg = {'default': []}
    with open(cfg_path, 'r') as f:
        current_section = 'default'
        for line in f.read().split('\n'):
            if len(line) == 0:  # Empty line
                continue
            elif line[0] == '.':  # Section
                current_section = line[1:]
                if current_section not in cfg:
                    cfg[current_section] = []
            else:
                cfg[current_section].append(line)
    return cfg


def _write(cfg):
    new_config = []
    for section in cfg:
        new_config.append('.' + section)
Exemple #53
0
        # also, are some attributes to process:
        # 'wanted_name' which is for idc.
        # 'wanted_hotkey', which should be mapped to a keypress.
        # 'comment' self-explanatory
        # 'help' self-explanatory

        # hotkey can be done by:
        # idaapi.CompileLine('static myname() { RunPythonStateMent("CallSomePython()") }')
        # idc.AddHotKey(module.wanted_hotkey, "myname")

        # idaapi.require
        pass

## ida's native api
if sys.platform == 'darwin':
    sys.meta_path.append( internal_object('ida', library(idaapi.idadir('libida.dylib'))) )
elif sys.platform in 'linux2':
    sys.meta_path.append( internal_object('ida', library('libida.so')) )
elif sys.platform == 'win32':
    if __import__('os').path.exists(idaapi.idadir('ida.wll')):
        sys.meta_path.append( internal_object('ida', library(idaapi.idadir('ida.wll'))) )
    elif idaapi.BADADDR >= 0x100000000:
        sys.meta_path.append( internal_object('ida', library(idaapi.idadir("ida{:s}.dll".format("64")))) )
    else:
        sys.meta_path.append( internal_object('ida', library(idaapi.idadir("ida{:s}.dll".format("")))) )
else:
    raise NotImplementedError

# private api
sys.meta_path.append( internal_submodule('internal', os.path.join(root, 'base'), include='_*.py') )