예제 #1
0
파일: ida_api.py 프로젝트: mcgrady1/Karta
    def databaseFile(self):
        """Return the (full) path of the database file.

        Return Value:
            Path to the database file
        """
        return idc.get_idb_path()
예제 #2
0
    def __init__(self, settings_filename):
        """
            Prepare for execution
        """
        SkelUtils.header()

        logger.info("[+] Init Skelenox")

        # Load settings
        self.skel_settings = SkelConfig(settings_filename)

        self.skel_conn = SkelIDAConnection(self.skel_settings)

        # If having 3 idbs in your current path bother you, change this
        self.crit_backup_file = idc.get_idb_path()[:-4] + "_backup_preskel.idb"
        self.backup_file = idc.get_idb_path()[:-4] + "_backup.idb"

        atexit.register(self.end_skelenox)

        logger.info(
            "Backuping IDB before any intervention (_backup_preskel)")
        idc.save_database(self.crit_backup_file, idaapi.DBFL_TEMP)
        logger.info("Creating regular backup file IDB (_backup)")
        idc.save_database(self.backup_file, idaapi.DBFL_TEMP)
        self.last_saved = time.time()

        if self.skel_hooks is not None:
            self.skel_hooks.cleanup_hooks()

        if not self.skel_conn.get_online():
            logger.error("Cannot get online =(")

        # Synchronize the sample
        self.skel_sync_agent = SkelSyncAgent()
        self.skel_sync_agent.setup_config(settings_filename)

        # setup hooks
        self.skel_hooks = SkelHooks(self.skel_conn)

        # setup UI
        if self.skel_settings.use_ui:
            self.skel_ui = SkelUI(settings_filename)

        # setup skelenox terminator
        self.setup_terminator()

        logger.info("Skelenox init finished")
예제 #3
0
    def __init__(self, settings_filename):
        """
            Prepare for execution
        """
        SkelUtils.header()

        logger.info("[+] Init Skelenox")

        # Load settings
        self.skel_settings = SkelConfig(settings_filename)

        self.skel_conn = SkelIDAConnection(self.skel_settings)

        # If having 3 idbs in your current path bother you, change this
        self.crit_backup_file = idc.get_idb_path()[:-4] + "_backup_preskel.idb"
        self.backup_file = idc.get_idb_path()[:-4] + "_backup.idb"

        atexit.register(self.end_skelenox)

        logger.info("Backuping IDB before any intervention (_backup_preskel)")
        idc.save_database(self.crit_backup_file, idaapi.DBFL_TEMP)
        logger.info("Creating regular backup file IDB (_backup)")
        idc.save_database(self.backup_file, idaapi.DBFL_TEMP)
        self.last_saved = time.time()

        if self.skel_hooks is not None:
            self.skel_hooks.cleanup_hooks()

        if not self.skel_conn.get_online():
            logger.error("Cannot get online =(")

        # Synchronize the sample
        self.skel_sync_agent = SkelSyncAgent()
        self.skel_sync_agent.setup_config(settings_filename)

        # setup hooks
        self.skel_hooks = SkelHooks(self.skel_conn)

        # setup UI
        if self.skel_settings.use_ui:
            self.skel_ui = SkelUI(settings_filename)

        # setup skelenox terminator
        self.setup_terminator()

        logger.info("Skelenox init finished")
예제 #4
0
    def connect(self, ip, port):
        if self._socket_manager.connected:
            return

        self._socket = socket.socket()

        self._socket.connect((ip, port))
        set_socket_keepalive(self._socket)

        self._socket_manager.initialize_socket(self._socket)

        if idc.get_idb_path():
            path = unicode(os.path.split(idc.get_idb_path())[-1])
        else:
            path = u'no_idb'

        pkt = create_connection_packet(path, '\x00' * 20)
        self._socket_manager.send_packet(pkt)
예제 #5
0
파일: lib.py 프로젝트: zysyyz/GhIDA
def get_ida_exported_files():
    """
    Return the path of the XML and bytes files.
    """
    create_random_filename()
    dirname = os.path.dirname(idc.get_idb_path())
    file_path = os.path.join(dirname, GLOBAL_FILENAME)
    xml_file_path = file_path + ".xml"
    bin_file_path = file_path + ".bytes"

    return xml_file_path, bin_file_path
예제 #6
0
    def on_import_clicked(self):
        dir_path = os.path.dirname(idc.get_idb_path())
        file_path, _ = QFileDialog.getOpenFileName(self,
                                                   'Select File to Import',
                                                   dir_path,
                                                   'Dump file (*.json)')
        if not file_path:
            return

        self._import_dialog = ImportDialog(file_path, self)
        self._import_dialog.show()
예제 #7
0
def get_input_file(freeze=True):
    """
    get input file path

        freeze (bool): if True, get freeze file if it exists
    """
    # try original file in same directory as idb/i64 without idb/i64 file extension
    input_file = idc.get_idb_path()[:-4]

    if freeze:
        # use frozen file if it exists
        freeze_file_cand = "%s%s" % (input_file, CAPA_EXTENSION)
        if os.path.isfile(freeze_file_cand):
            return freeze_file_cand

    if not os.path.isfile(input_file):
        # TM naming
        input_file = "%s.mal_" % idc.get_idb_path()[:-4]
        if not os.path.isfile(input_file):
            input_file = idaapi.ask_file(0, "*.*",
                                         "Please specify input file.")
    if not input_file:
        raise ValueError("could not find input file")
    return input_file
예제 #8
0
    def init(self):
        # put import in code block for hot laod
        from aaf import utils
        architecture = utils.getIdaArchitecture()
        if architecture != "arm":
            logging.info("%s unsupported architecture: %s" %
                         (self.wanted_name, architecture))
            return idaapi.PLUGIN_SKIP

        ida_kernwin.msg("Initializing %s\n" % self.wanted_name)

        from aaf import adb
        wrapper = adb.AdbWrapper("")

        from aaf import AndroidAttacher
        utilsJar = os.path.join(get_plugin_home(), "aaf", "utils.jar")
        config_file = os.path.splitext(idc.get_idb_path())[0] + ".aaf.conf"
        self.androidAttacher = AndroidAttacher(wrapper, utilsJar, config_file)
        return idaapi.PLUGIN_KEEP
예제 #9
0
    def activate(self, ctx):
        target_filename = self.get_filename()
        if target_filename and os.path.isfile(target_filename):
            src_filename = os.path.splitext(idc.get_idb_path())[0] + '.db'
            print('Diffing: %s - %s' % (src_filename, target_filename))

            if self.use_process:
                launcher = binkit.python.Launcher()
                script_name = os.path.splitext(
                    binkit.binaries.__file__)[0] + '.py'
                parameters = [
                    script_name, '-o', 'output.json', src_filename,
                    target_filename
                ]
                print(parameters)
                launcher.run(parameters)
            else:
                t = threading.Thread(target=self.match_thread,
                                     args=(src_filename, target_filename))
                t.start()

        return 1
예제 #10
0
def get_directory_config_path(directory=None):
    if directory is None:
        directory = os.path.dirname(idc.get_idb_path())
    config_path = os.path.join(directory, CONFIG_FILE_NANE)
    return config_path
예제 #11
0
import ida_utils
import json
import codecs
import sys
import os
import idaapi
import idc
import gzip
sys.path.append(os.path.dirname(__file__))

print('jarv1s script for idapro is now running...')
print('Waiting for idapro...')
idaapi.auto_wait()
print('start persisting...')

file_name = os.path.splitext(idc.get_idb_path())[0] + '.asm.json.gz'
output_file = os.getenv('output_file_path', file_name)

data = ida_utils.get_all(with_blocks=True)

content = json.dumps(data, ensure_ascii=False).encode('utf-8')

# with codecs.open(output_file, 'w', encoding='utf-8') as outfile:
#     json.dump(data, outfile, ensure_ascii=False)

with gzip.GzipFile(output_file, 'w') as gf:
    gf.write(content)

idc.qexit(0)
예제 #12
0
import os
import itertools
import idaapi
import idc

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)
if idc.get_idb_path():
    PROJECT_PLUGIN_LIST_PATH = os.path.join(os.path.dirname(idc.get_idb_path()), 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
        visited.add(item)

예제 #13
0
def run_ida_server(errors):
    from epc.py3compat import SocketServer
    from epc.handler import EPCHandler
    from epc.server import EPCServer
    from epc.utils import newthread
    server_ports_filename = os.path.join(tempfile.gettempdir(), 'ida_servers.txt')
    def update_ida_server_port(db_path, _image_name, port):
        if port is None:
            port = '-'
        else:
            port = str(port)
        _image_name = _image_name.replace('\\', '/')
        with open(db_path, 'w+t') as f:
             f.seek(0)
             should_write_filename = False
             while True:
                 current_pos = f.tell()
                 l = f.readline()
                 l = l.replace('\n', '')
                 if l == '':
                     should_write_filename = True
                     break
                 try:
                     image_name_in_file = l.split(None, 1)[1]
                 except:
                     errors.append("invalid database name %r" % (l,))
                 else:
                     if image_name_in_file == _image_name:
                         break
             f.seek(current_pos)
             f.write(port.ljust(8))
             if should_write_filename:
                 f.write(_image_name + '\n')
    class ThreadingDaemonEPCHandler(EPCHandler):
        def _handle(self, sexp):
            # running this thread makes sure each request from the same user will be in its own thread
            t = newthread(self, target=EPCHandler._handle, args=(self, sexp))
            t.daemon = True
            t.start()
    class ThreadingDaemonEPCServer(SocketServer.ThreadingMixIn, EPCServer):
        # inheriting from ThreadingMixIn makes sure each client request listener has its own thread
        daemon_threads = True
        def __init__(self, *args, **kwds):
            kwds.update(RequestHandlerClass=ThreadingDaemonEPCHandler)
            EPCServer.__init__(self, *args, **kwds)
    ida_server = ThreadingDaemonEPCServer(('localhost', 0))
    @ida_server.register_function
    def decompile_with_ea_lines(offset):
        batch(1)
        try:
            return match_lines_asm(offset)
        finally:
            batch(0)
    ida_server_port = ida_server.server_address[1]
    ida_server_thread = threading.Thread(target=ida_server.serve_forever)
    ida_server_thread.daemon = True
    image_name =  idc.get_idb_path()
    def closeserver(_image_name):
        try:
            update_ida_server_port(server_ports_filename, _image_name, None)
        finally:
            ida_server.shutdown()
            ida_server_thread.join()
    atexit.register(closeserver, image_name)
    update_ida_server_port(server_ports_filename, image_name, ida_server_port)
    ida_server_thread.start()
예제 #14
0
import os
import idc
import idaapi
import binascii

idb_path = idc.get_idb_path()

if ".idb" in idb_path:
    export_table_file_name = idb_path.split(".idb")[0].split("\\")[-1] + ".txt"
elif ".i64" in idb_path:
    export_table_file_name = idb_path.split(".i64")[0].split("\\")[-1] + ".txt"
elif ".dll" in idb_path:
    export_table_file_name = idb_path.split(".dll")[0].split("\\")[-1] + ".txt"
else:
    export_table_file_name = idb_path.split("\\")[-1] + ".txt"

out_path = "D:\\fix_vmp_dump"

if not os.path.exists(out_path):
    os.makedirs(out_path)

file_name = out_path + "\\" + export_table_file_name
if os.path.exists(file_name):
    os.remove(file_name)

count = idc.get_entry_qty()
with open(file_name, "a") as fa:
    for i in range(0, count - 1):
        try:
            fa.write(
                idc.get_entry_name(idc.get_entry_ordinal(i)) + " " +
예제 #15
0
from xmlrpc.server import SimpleXMLRPCServer
from xml.sax.saxutils import escape

import idaapi
import idc

# Wait for any processing to get done
idaapi.auto_wait()

# On Windows with NTFS filesystem a filepath with ':'
# is treated as NTFS ADS (Alternative Data Stream)
# and so saving file with such name fails
dt = datetime.datetime.now().isoformat().replace(":", "-")

# Save the database so nothing gets lost.
idc.save_database(idc.get_idb_path() + "." + dt)

DEBUG_MARSHALLING = False


def create_marshaller(use_format=None, just_to_str=False):
    assert (
        use_format or just_to_str
    ), "Either pass format to use or make it converting the value to str."

    def wrapper(_marshaller, value, appender):
        if use_format:
            marshalled = use_format % value
        elif just_to_str:
            marshalled = "<value><string>%s</string></value>" % escape(
                str(value))
예제 #16
0
import sys

prog = idc.ARGV[0] if len(idc.ARGV) else None
parser = argparse.ArgumentParser(prog=prog, description='Export IDA database')
parser.add_argument('bin_dir', type=os.path.abspath, help='YaCo bin directory')
parser.add_argument("--output",
                    type=os.path.abspath,
                    default="database/database.yadb",
                    help="output filename")
args = parser.parse_args(idc.ARGV[1:])

root_dir = os.path.abspath(os.path.join(args.bin_dir, '..'))
for path in ['bin', 'YaCo']:
    sys.path.append(os.path.join(root_dir, path))

# import yatools dependencies
if idc.__EA64__:
    import YaToolsPy64 as ya
else:
    import YaToolsPy32 as ya

idc.Wait()

name, _ = os.path.splitext(idc.get_idb_path())
try:
    os.makedirs(os.path.dirname(args.output))
except:
    pass
ya.export_from_ida(name, args.output)
idc.Exit(0)
예제 #17
0
파일: export.py 프로젝트: mewbak/smda
from smda.Disassembler import Disassembler

LOGGER = logging.getLogger(__name__)


def detectBackend():
    backend = ""
    version = ""
    try:
        import idaapi
        import idc
        import idautils
        backend = "IDA"
        version = idaapi.IDA_SDK_VERSION
    except:
        pass
    return (backend, version)


if __name__ == "__main__":
    BACKEND, VERSION = detectBackend()
    if BACKEND == "IDA":
        DISASSEMBLER = Disassembler(config, backend=BACKEND)
        REPORT = DISASSEMBLER.disassembleBuffer(None, None)
        output_path = idc.get_idb_path()
        with open(output_path + ".smda", "wb") as fout:
            json.dump(REPORT, fout, indent=1, sort_keys=True)
            LOGGER.info("Output saved to: %s.smda", output_path)
    else:
        raise Exception("No supported backend found.")
예제 #18
0
# Copyright (C) 2020 Alibaba Group Holding Limited

import idaapi
import idc
import shutil
import os

idb_fp = idc.get_idb_path()
modulename = os.path.basename(idb_fp)[:-4]
idb_dirpath = os.path.dirname(idb_fp)
til_dirpath = os.path.join(idb_dirpath, "tils")
if not os.path.isdir(til_dirpath):
    os.makedirs(til_dirpath)
self_til = idaapi.get_idati()
ida_typeinf.compact_til(self_til)
ida_typeinf.store_til(self_til, None,
                      os.path.join(til_dirpath, modulename + ".til"))
#til_fp = modulename + ".til"
#shutil.copy(til_fp, til_fp[:-4]+".exported.til")
idc.Exit(0)
예제 #19
0
def GetIdbFile():
    return idc.get_idb_path()