示例#1
0
def main():
    # Don't support the legacy api.
    sys.modules["__main__"].IDAPYTHON_COMPAT_695_API = False

    import idc

    kordesii.setup_logging()

    try:
        Pyro4.config.SERVERTYPE = "multiplex"
        Pyro4.config.FLAME_ENABLED = "True"
        Pyro4.config.SERIALIZERS_ACCEPTED = {"dill"}

        logger.debug("Starting daemon...")
        daemon = Pyro4.Daemon(host="localhost")
        warnings.simplefilter("ignore")

        uri = _register(daemon)

        logger.info("Listening on {}".format(uri))
        # Send port back to the client.
        _send_result(uri.port)

        # Start listener
        idc.auto_wait()
        daemon.requestLoop(loopCondition=lambda: not daemon_stop.is_set())

        if _close_ida:
            idc.qexit(0)

    except Exception as e:
        # Send exception back to the client, so they can raise it outside of IDA.
        _send_result(e)
def main():
    """
    Initialize rpyc connection.
    """
    # Don't compress to improve speed.
    rpyc.core.channel.Channel.COMPRESSION_LEVEL = 0

    # Importing idc here so we can still import the server externally.
    import idc

    if not idc.ARGV[1:]:
        raise RuntimeError(f"No connection parameter provided.")

    if sys.platform == "win32":
        pipe_name = idc.ARGV[1]
        stream = NamedPipeStream.create_server(pipe_name)
        with rpyc.classic.connect_stream(stream) as srv:
            srv.serve_all()
    else:
        socket_path = idc.ARGV[1]
        server = OneShotServer(SlaveService,
                               socket_path=socket_path,
                               auto_register=False)
        server.start()

    idc.qexit(0)
示例#3
0
def log_pp_guids():
    idc.auto_wait()
    analyser = Analyser()
    if not analyser.valid:
        idc.qexit(-1)
    analyser.get_boot_services()
    analyser.get_protocols()
    analyser.get_prot_names()
    data = {}
    data['module_name'] = idaapi.get_root_filename()
    data['protocols'] = []
    for protocol_record in analyser.Protocols['all']:
        if (protocol_record['protocol_name'] == 'ProprietaryProtocol'):
            guid = get_guid_str(protocol_record['guid'])
            service = protocol_record['service']
            address = '{addr:#x}'.format(addr=protocol_record['address'])
            data['protocols'].append({
                'guid': guid,
                'service': service,
                'address': address
            })
    logs_dir = os.path.join(tempfile.gettempdir(), 'uefi-retool-pp-guids')
    if not os.path.isdir(logs_dir):
        os.mkdir(logs_dir)
    log_fname = os.path.join(
        logs_dir, '{}.json'.format(
            binascii.hexlify(ida_nalt.retrieve_input_file_md5()).decode()))
    with open(log_fname, 'w') as f:
        json.dump(data, f, indent=4)
    idc.qexit(0)
示例#4
0
def log_pp_guids():
    idc.auto_wait()
    analyser = Analyser()
    if not analyser.valid:
        idc.qexit(-1)
    analyser.get_boot_services()
    analyser.get_protocols()
    analyser.get_prot_names()
    data = dict()
    data["module_name"] = idaapi.get_root_filename()
    data["protocols"] = list()
    for protocol_record in analyser.Protocols["all"]:
        if protocol_record["protocol_name"] == "ProprietaryProtocol":
            guid = get_guid_str(protocol_record["guid"])
            service = protocol_record["service"]
            addr = protocol_record["address"]
            address = f"{addr:#x}"
            data["protocols"].append({
                "guid": guid,
                "service": service,
                "address": address
            })
    logs_dir = os.path.join(tempfile.gettempdir(), "uefi-retool-pp-guids")
    if not os.path.isdir(logs_dir):
        os.mkdir(logs_dir)
    log_fname = f"{binascii.hexlify(ida_nalt.retrieve_input_file_md5()).decode()}.json"
    log_fpath = os.path.join(logs_dir, log_fname)
    with open(log_fpath, "w") as f:
        json.dump(data, f, indent=2)
    idc.qexit(0)
def main():
    while True:
        cmnd = recv_from_pipe()
        if cmnd == IDA_ERROR:
            break

        elif cmnd == UNKOWN_CMND:
            send_in_pipe(END)
            break

        elif type(cmnd) == tuple:
            command = cmnd[0]
            if len(cmnd) == 1:
                if command == START:
                    logger.info("Received START...")
                    if send_in_pipe(START) == IDA_ERROR:
                        break

                    idc.auto_wait()
                    continue

                elif command == END:
                    logger.info("Received END...")
                    if not clean_the_mess():
                        break
                    if send_in_pipe(END) == IDA_ERROR:
                        break
                    idc.qexit(0)
                    return
            elif len(cmnd) >= 2:
                bbl = BBL(cmnd[1])
                if command == TYPE:
                    logger.info("Received TYPE...")
                    res = bbl.get_branch_type()
                elif command == DREFS:
                    logger.info("Received DREFS...")
                    res = bbl.get_data_refs()
                elif command == CREFS:
                    logger.info("Received CREFS...")
                    res = bbl.get_code_refs()
                elif command == VRET:
                    logger.info("Received VRET...")
                    res = bbl.is_nonvoid_ret()
                elif command == FEND:
                    logger.info("Received FEND...")
                    res = bbl.func_bound()
                elif command == FNAM:
                    logger.info("Received FNAM...")
                    res = bbl.func_name()
                elif command == DOMIN:
                    logger.info("Received DOMIN...")
                    res = bbl.is_dominant(cmnd[2])
                if send_in_pipe(command, res) == IDA_ERROR:
                    break
        else:
            break

    idc.qexit(-1)
    return
示例#6
0
文件: core.py 项目: ddash-ct/kordesii
def decoder_entry(main_func):
    """
    Main entry code that will trigger IDA script execution.

    Decorate your main function like so:

        @kordesii.script_entry
        def main():
            # ....

    WARNING: The decorated function MUST be at the end of the module.

    :param main_func: function to call
    """
    try:
        decoder_locals = inspect.stack(0)[1][0].f_locals
    except TypeError:
        return main_func
    if decoder_locals.get("__name__") == "__main__":
        if in_ida:
            # Setup logging.
            logutil.setup_logging()

            # Run main()
            idc.auto_wait()
            try:
                main_func()
            except Exception as e:
                # Catch all exceptions, otherwise we have to go fish it out of ida_log.txt
                logger.exception(e)
            finally:
                # Clear out the serializer so we can run multiple decoders in the same idb.
                # Must import here to avoid cyclic import.
                # FIXME: A proper fix for the serializer should be put in place.
                from kordesii import serialization

                serialization._serializers = {}
                # Exit if called from framework
                if called_from_framework:
                    idc.qexit(0)
        else:
            sys.exit("Script must be called from IDA or kordesii.")
            # TODO: We could possibly call run_ida() if outside.

    return main_func
示例#7
0
def log_pp_guids():
    if not os.path.isfile(LOG_FILE) or not os.path.getsize(LOG_FILE):
        print_log(get_table_line('Guid', 'Module', 'Service', 'Address'))
        print_log(get_table_line('---', '---', '---', '---'))
    idc.auto_wait()
    analyser = Analyser()
    if not analyser.valid:
        idc.qexit(-1)
    analyser.get_boot_services()
    analyser.get_protocols()
    analyser.get_prot_names()
    for protocol_record in analyser.Protocols['all']:
        if (protocol_record['protocol_name'] == 'ProprietaryProtocol'):
            guid = get_guid_str(protocol_record['guid'])
            module = idaapi.get_root_filename()
            service = protocol_record['service']
            address = '{addr:#x}'.format(addr=protocol_record['address'])
            print_log(get_table_line(guid, module, service, address))
    idc.qexit(1)
示例#8
0
def log_all():
    data = dict()
    idc.auto_wait()
    analyser = Analyser()
    if not analyser.valid:
        idc.qexit(-1)
    analyser.get_boot_services()
    module = idaapi.get_root_filename()
    boot_services = get_boot_services(analyser)
    protocols = get_protocols(analyser)
    data["module_name"] = module
    data["boot_services"] = boot_services
    data["protocols"] = protocols
    logs_dir = os.path.join(tempfile.gettempdir(), "uefi-retool-all-info")
    if not os.path.isdir(logs_dir):
        os.mkdir(logs_dir)
    log_fname = f"{binascii.hexlify(ida_nalt.retrieve_input_file_md5()).decode()}.json"
    log_fpath = os.path.join(logs_dir, log_fname)
    with open(log_fpath, "w") as f:
        json.dump(data, f, indent=2)
    idc.qexit(0)
示例#9
0
def log_pp_guids():
    if os.path.isfile(LOG_FILE) == 0 or os.path.getsize(LOG_FILE) == 0:
        print_log(get_table_line("Guid", "Module", "Service", "Address"))
        print_log(get_table_line("---", "---", "---", "---"))

    idc.auto_wait()
    analyser = Analyser()
    analyser.get_boot_services()
    analyser.get_protocols()
    analyser.get_prot_names()

    for protocol_record in analyser.Protocols["All"]:
        if (protocol_record["protocol_name"] == "ProprietaryProtocol"):
            guid = str(map(hex, protocol_record["guid"]))
            guid = guid.replace("L", "").replace("'", "")
            module = idaapi.get_root_filename()
            service = protocol_record["service"]
            address = hex(protocol_record["address"])
            address = address.replace("L", "")
            print_log(get_table_line(guid, module, service, address))
    idc.qexit(0)
示例#10
0
def log_all():
    idc.auto_wait()
    analyser = Analyser()
    analyser.get_boot_services()
    print_log("## Module: " + idaapi.get_root_filename())
    print_log("### Boot services:")
    list_boot_services(analyser)
    analyser.get_protocols()
    analyser.get_prot_names()
    data = analyser.Protocols["All"]
    print_log("### Protocols:")
    if (len(data) == 0):
        print_log("* empty")
    for element in data:
        guid_str = "[guid] " + str(map(hex, element["guid"])).replace(
            "L", "").replace("'", "")
        print_log("* [{0}]".format(hex(element["address"]).replace("L", "")))
        print_log("\t - [service] " + element["service"])
        print_log("\t - [protocol_name] " + element["protocol_name"])
        print_log("\t - [protocol_place] " + element["protocol_place"])
        print_log("\t - " + guid_str)
    idc.qexit(0)
示例#11
0
def log_all():
    data = {}
    idc.auto_wait()
    analyser = Analyser()
    if not analyser.valid:
        idc.qexit(-1)
    analyser.get_boot_services()
    module = idaapi.get_root_filename()
    boot_services = get_boot_services(analyser)
    protocols = get_protocols(analyser)
    data['module_name'] = module
    data['boot_services'] = boot_services
    data['protocols'] = protocols
    logs_dir = os.path.join(tempfile.gettempdir(), 'uefi-retool-all-info')
    if not os.path.isdir(logs_dir):
        os.mkdir(logs_dir)
    log_fname = os.path.join(
        logs_dir, '{}.json'.format(
            binascii.hexlify(ida_nalt.retrieve_input_file_md5()).decode()))
    with open(log_fname, 'w') as f:
        json.dump(data, f, indent=4)
    idc.qexit(0)
示例#12
0
def log_all():
    idc.auto_wait()
    analyser = Analyser()
    if not analyser.valid:
        idc.qexit(0)
    analyser.get_boot_services()
    print_log("## Module: " + idaapi.get_root_filename())
    print_log("### Boot services:")
    list_boot_services(analyser)
    analyser.get_protocols()
    analyser.get_prot_names()
    data = analyser.Protocols["All"]
    print_log("### Protocols:")
    if (len(data) == 0):
        print_log("* empty")
    for element in data:
        guid_str = "[guid] " + utils.get_guid_str(element["guid"])
        print_log("* [{0}]".format("{addr:#x}".format(addr=element["address"])))
        print_log("\t - [service] " + element["service"])
        print_log("\t - [protocol_name] " + element["protocol_name"])
        print_log("\t - [protocol_place] " + element["protocol_place"])
        print_log("\t - " + guid_str)
    idc.qexit(0)
示例#13
0
def log_all():
    idc.auto_wait()
    analyser = Analyser()
    if not analyser.valid:
        idc.qexit(-1)
    analyser.get_boot_services()
    print_log('## Module: ' + idaapi.get_root_filename())
    print_log('### Boot services:')
    list_boot_services(analyser)
    analyser.get_protocols()
    analyser.get_prot_names()
    data = analyser.Protocols['all']
    print_log('### Protocols:')
    if not len(data):
        print_log('* empty')
    for element in data:
        guid_str = '[guid] ' + get_guid_str(element['guid'])
        print_log('* [{0}]'.format(
            '{addr:#x}'.format(addr=element['address'])))
        print_log('\t - [service] ' + element['service'])
        print_log('\t - [protocol_name] ' + element['protocol_name'])
        print_log('\t - [protocol_place] ' + element['protocol_place'])
        print_log('\t - ' + guid_str)
    idc.qexit(1)
示例#14
0
def main():
    try:
        # e.g. /path/to/asadbg/asadb.json
        dbname = os.environ["ASADBG_DB"]
    except:
        logmsg("You need to define ASADBG_DB first")
        sys.exit()

    if ida_helper.get_idb_name() == "lina":
        logmsg("Hunting lina...")
        main_lina(dbname)
    elif ida_helper.get_idb_name() == "lina_monitor":
        logmsg("Hunting lina_monitor...")
        main_lina_monitor(dbname)
    elif ida_helper.get_idb_name() == "libc.so":
        logmsg("Hunting libc...")
        main_libc(dbname)
    else:
        logmsg("ERROR: Unsupported filename")

    # This allows us to cleanly exit IDA upon completion
    if "DO_EXIT" in os.environ:
        # XXX - Was Exit(1)
        idc.qexit(1)
import idc
import idautils

functions = idautils.Functions()
f = open(idc.ARGV[1], 'a') if len(idc.ARGV) > 1 else sys.stdout
log = f.write

# log current file path
log(idc.get_input_file_path() + '\n')

# wait for auto-analysis to complete
idc.auto_wait()

for f in functions:
    log(idc.get_func_name(f) + "\n")
    print idc.get_func_name(f)

idc.qexit(4)
示例#16
0
    for each in addr_to_fix:
        tmp1.write(str(each[0])+','+str(each[1]))
        tmp1.write('\n')
    tmp1.close()
    '''

    section_data = ''
    offsets = []
    for index in range(len(ori_op)):
        offsets.append(len(section_data))
        section_data += build_section_data(args0[index], args1[index],
                                           args2[index])

    # add dispatch function
    len_funs = len(section_data)
    section_data = add_dispatch_function(ori_address, offsets) + section_data

    section_file = open(INPUT_PE + '_newSectionData', 'wb')
    section_file.write(section_data)
    section_file.close()
    section_size = len(section_data)
    insert_section(len(section_data), section_data, len_funs)
    #print opcode_all


if __name__ == "__main__":
    idaapi.autoWait()
    create_pe()
    if "DO_EXIT" in os.environ:
        idc.qexit(1)
示例#17
0
import idc
import idaapi
import binascii

idc.set_inf_attr(INF_AF, idc.get_inf_attr(INF_AF) | AF_DODATA)

print("Waiting for the end of the auto analysis...")
idc.auto_wait()
print("Autoanalysis done!")

dumped_netnode_value = 'ca75b28848ea06bcae409699fa2510a03bbaf43bd167eecb17d52918187133a793ebf8d3270230c7164d7a79b53c2c3edd611ede975690784cf2c254abe8b587140d19a3f46b2be109bde1da1b7ed4d7c9f7b58135f2c296db4e86ad29b6f0b999b5599d40c3bae8b29d2cc06ecef63cba0e1b9a9505c1efe9019a7020127e100000000000000000000000000000000000000000000000000000000000000000'
idaapi.netnode('$ user1', 0,
               False).kill()  # deleting netnode with plain text info
idaapi.netnode('$ original user', 0,
               False).supset(0, binascii.unhexlify(dumped_netnode_value))

idc.qexit(0)
示例#18
0
from __future__ import print_function
import os
import sys
import shutil
from glob import glob

try:
    import epydoc.apidoc
    import epydoc.cli
except ImportError as e:
    import idc
    import traceback
    idc.msg("Couldn't import module %s\n" % traceback.format_exc())
    idc.qexit(-1)

# --------------------------------------------------------------------------
DOC_DIR = 'hr-html'


# --------------------------------------------------------------------------
def log(msg):
    #print msg
    pass


def add_header(lines):
    S1 = 'href="epydoc.css"'
    p = lines.find(S1)
    if p < 0:
        return None
    p = lines.find('\n', p)
示例#19
0
文件: hrdoc.py 项目: AmesianX/src
from __future__ import print_function
import os
import sys
import shutil
from glob import glob

try:
    import epydoc.apidoc
    import epydoc.cli
except ImportError as e:
    import idc
    import traceback
    idc.msg("Couldn't import module %s\n" % traceback.format_exc())
    idc.qexit(-1)

# --------------------------------------------------------------------------
DOC_DIR = 'hr-html'

# --------------------------------------------------------------------------
def log(msg):
    #print msg
    pass

def add_header(lines):
    S1 = 'href="epydoc.css"'
    p = lines.find(S1)
    if p < 0:
        return None
    p = lines.find('\n', p)
    if p < 0:
        return None
"""
Stub used to run tests within IDA.
"""

import pytest

import kordesii

if __name__ == "__main__" and kordesii.in_ida:
    import idc

    idc.auto_wait()
    print(idc.get_input_file_path())
    print(idc.ARGV)

    args = idc.ARGV[1:]
    print("Running: pytest {}".format(" ".join(args)))
    idc.qexit(pytest.main(args))
示例#21
0
def analyse_and_exit():
    idc.auto_wait()
    idc.qexit(0)
示例#22
0
 def cmd_exit_ida(self, c):
     idaapi.msg("IdaRemote exiting IDA\n")
     idc.qexit(int(c, 0))
     return "bye"  # not reached?