def __init__(self, symbols=True):
        try:
            check_and_configure_bap()
        except:
            idc.Message('BAP> configuration failed\n{0}\n'.
                        format(str(sys.exc_info())))
            traceback.print_exc()
            raise BapIdaError()
        bap = config.get('bap_executable_path')
        if bap is None or not os.access(bap, os.X_OK):
            idc.Warning('''
            The bap application is either not found or is not an executable.
            Please install bap or, if it is installed, provide a path to it.
            Installation instructions are available at: http://bap.ece.cmu.edu.
            ''')
            raise BapNotFound()
        binary = idaapi.get_input_file_path()
        super(BapIda, self).__init__(bap, binary)
        # if you run IDA inside IDA you will crash IDA
        self.args.append('--no-ida')
        self._on_finish = []
        self._on_cancel = []
        self._on_failed = []
        if symbols:
            self._setup_symbols()

        headers = config.is_set('ida_api.enabled')

        if headers:
            self._setup_headers(bap)
Example #2
0
def dump_data():
    """Extracts and dumps useful data from the file being processed.
    The output is written using pickle and it consists of a set with all the
    code heads followed by func.Function objects (ended with a None)."""

    def __dump(out, type, lb=0, ub=0):
        if type == 'code_head':
            cPickle.dump(get_code_heads(), out, cPickle.HIGHEST_PROTOCOL)
            for f in functions_iter():
                cPickle.dump(f, out, cPickle.HIGHEST_PROTOCOL)
        if type == 'code_blk':
            for bc in _get_blocks_codes_per_func_iter():
                cPickle.dump(bc, out, cPickle.HIGHEST_PROTOCOL)
        cPickle.dump(None, out)
        out.close()

    __dump(util.open_dump(idaapi.get_input_file_path(), 'wb', 'dmp'), 'code_head')
    __dump(util.open_dump(idaapi.get_input_file_path(), 'wb', 'code_blk'), 'code_blk')
Example #3
0
    def __init__(self):
        self.__tpargs = ""
        self.__trargs = ""
        self.__taargs = ""
        self.__sffargs = ""
        self.__sfrargs = ""
        self.__taintStart = None
        self.__taintStop = None
        self.TARGET_FILE = idaapi.get_root_filename()
        self.TARGET_PATH = idaapi.get_input_file_path()[:-len(self.TARGET_FILE)]
        self.__programArguments = []

        self.__taintedRegs = []
        self.__taintedMems = []
        self.__taintedAddrs = []
        self.__solutions = []
        self.__chains = []
Example #4
0
        end_offset = begin_offset + idaapi.getseg(seg).size()

        if image_begin == -1:
            image_begin = begin_offset
        image_end = end_offset

    #print("// image 0x%x-0x%x" % (image_begin, image_end))
    print("// extract image: dd skip=$((0x%x)) count=$((0x%x-0x%x)) if=%s of=%s.data bs=1" % \
        (image_begin, image_end, image_begin, idaapi.get_input_file_path(), basename))

def print_section_list():
    for s in idautils.Segments():
        seg = idaapi.getseg(s)
        print("    {name:\"%s\", begin:0x%x, end:0x%x}," % (idc.SegName(s), idc.SegStart(s), idc.SegEnd(s)))

basename = os.path.splitext(idaapi.get_input_file_path())[0]
# basename = os.path.splitext(idaapi.get_root_filename())[0]

# undefine names
names = map(lambda x : x[0], idautils.Names())
names = filter(lambda x : idc.isData(idc.GetFlags(x)), names)

for n in names:
  idc.MakeUnknown(n, 1, 0)

with open(basename + ".cfg", "w") as out:
    prev = sys.stdout
    sys.stdout = out # comment to dump the json into console
    get_file_range()
    print ("{")
    print ("  segments:[")
Example #5
0
    def to_json(self):
        return pb2json(self.config)

    def to_str(self):
        return json.dumps(self.to_json(), indent=2)

    def to_file(self, filename):
        f = open(filename, "w")
        f.write(self.to_str())
        f.close()

    def __str__(self):
        return self.to_str()


if __name__ == "__main__":
    import idaapi, idc
    idaapi.autoWait()
    FT = open(idaapi.get_input_file_path()).read(2)
    import os
    print os.getcwd()
    conf = Configuration()
    conf.set_start_stop(FT)
    conf.create_call_map(FT)
    if len(idc.ARGV) < 2:
        print conf.to_str()
    else:
        conf.to_file(idc.ARGV[1])
        idc.Exit(0)
def GetBinaryName():
    global BinaryName
    if BinaryName is None:
        BinaryName = idaapi.get_input_file_path()
    return BinaryName
def GetBinaryName():
    BinaryName = idaapi.get_input_file_path()
    return BinaryName
def _get_bin_name():
    return idaapi.get_input_file_path()
Example #9
0
                smi_number = r8
            f.write("  [+] SMI number : {}.\n".format(hex(ord(smi_number))))

            # If there is another call to Register() we will start the emulation
            # from here
            start = addr_tmp

    return nb_calls


if __name__ == "__main__":

    # Let IDA load the binary and build the DB.
    idaapi.autoWait()

    f.write("[{}]\n".format(idaapi.get_input_file_path()))

    guid_in_opnd = 0
    # To research from IDA, the GUID need to be a string of bytes, with the
    # correct endianness (by block).

    # TODO : make it more generic
    # The following = { 0xe541b773, 0xdd11, 0x420c, 0xb0, 0x26, 0xdf, 0x99, 0x36, 0x53, 0xf8, 0xbf }
    #guid = "73 b7 41 e5 11 dd 0c 42 b0 26 df 99 36 53 f8 bf"

    # The following = { 0x18a3c6dc, 0x5eea, 0x48c8, 0xa1, 0xc1, 0xb5, 0x33, 0x89, 0xf9, 0x89, 0x99 }
    guid = "dc c6 a3 18 ea 5e c8 48 a1 c1 b5 33 89 f9 89 99"

    # Search for that binary sequence in .data and .rdata. Useless on newer
    # version: GUID are in .text.
    #data = IDA_GetSegmByName(".data").startEA
Example #10
0
def get_input_file_path():
    """Return the name of the currently processed file."""
    return idaapi.get_input_file_path()
Example #11
0
 def input_file(self):
     path = idaapi.get_input_file_path()
     return RemoteFile(open(path, "rb"), path)
Example #12
0
 def input_file(self):
     path = idaapi.get_input_file_path()
     return open(path, "rb")
Example #13
0
    # collect all exports in a dict by 'ea' , remove them from above all-functions dict
    all_exports = dict()
    for index, ordinal, ea, name in idautils.Entries():
        if all_functions.get(str(ea)) is not None:
            all_exports.update({str(ea): all_functions.pop(str(ea))})

    # collect all imports in a dict by 'ea' , remove them from above all-functions dict
    all_imports = dict()
    for ea in all_functions.keys():
        seg_name = idc.SegName(int(ea))
        if seg_name in ['extern']:
            all_imports.update({ea: all_functions.pop(ea)})

    groups_of_functions = []
    groups_of_functions.append({'label': 'exports', 'edges': all_exports})

    groups_of_functions.append({'label': 'others', 'edges': all_functions})

    groups_of_functions.append({'label': 'imports', 'edges': all_imports})

    name, extension = os.path.splitext(idaapi.get_input_file_path())
    fd_out = open(name + '_allxrefs.json', 'w')
    fd_out.write(json.dumps(groups_of_functions, indent=2, sort_keys=False))

except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    logger.error("Uncaught exception",
                 exc_info=(exc_type, exc_value, exc_traceback))

idascript.exit()
from sets import Set
import json
import idaapi
import idc

print('My Script is now running...')
print('Waiting for idapro...')
idaapi.autoWait()
print('start persisting...')

idaapi.rebase_program(-1 * idaapi.get_imagebase(), 0)

ss = idaapi.get_input_file_path()
pn = os.path.splitext(ss)[0]
callees = dict()
funcmap = dict()
data = dict()
data['name'] = pn

for seg_ea in Segments():
    for function_ea in Functions(SegStart(seg_ea), SegEnd(seg_ea)):
        #fill call graph
        # For each of the incoming references
        for ref_ea in CodeRefsTo(function_ea, 0):
            # Get the name of the referring function
            caller_name = GetFunctionName(ref_ea)
            # Add the current function to the list of functions called by the referring function
            callees[caller_name] = callees.get(caller_name, Set())
            callees[caller_name].add(function_ea)

data['functions'] = list()
Example #15
0
 def get_default_db_filename(self):
     """
     Get the default DIE DB filename
     """
     filename, extension = os.path.splitext(idaapi.get_input_file_path())
     return filename + ".ddb"
Example #16
0
# rename functions loading addresses using nm

import idaapi
import idc
from subprocess import Popen, PIPE


def make_func(addr):
    idc.MakeCode(addr)
    idc.MakeFunction(addr)


if __name__ == "__main__":
    executable = idaapi.get_input_file_path()
    proc = Popen(
        "nm {}".format(executable),
        shell=True,
        stdout=PIPE,
        stderr=PIPE)

    out, err = proc.communicate()
    errcode = proc.returncode

    if errcode != 0:
        raise Exception("cannot get symbols!")

    proc = Popen(
        "nm -C {}".format(executable),
        shell=True,
        stdout=PIPE,
        stderr=PIPE)
Example #17
0
File: loader.py Project: isra17/nrs
def load_file(li, netflags, format):
    nsis = nsisfile.NSIS.from_path(idaapi.get_input_file_path())

    # Create NSIS netnode.
    nsis_netnode = idaapi.netnode("$ NSIS", 0, True)
    nsis_netnode.hashset("VERSION_MAJOR", nsis.version_major)
    nsis_netnode.hashset("VERSION_MINOR", nsis.version_minor)

    # Create blocks segments.
    for name, n, sclass in BLOCKS:
        offset = nsis.header.blocks[n].offset
        if offset == 0:
            continue
        content = nsis.block(n)
        # Create block segment
        seg = idaapi.segment_t()
        seg.startEA = offset
        seg.endEA = offset + len(content)
        idaapi.add_segm_ex(seg, name, sclass, 0)
        idaapi.mem2base(content, offset)

    # Add one virtual segment to hold variables.
    var_seg = idaapi.segment_t()
    var_start = align(nsis.size())
    var_seg.startEA = var_start
    var_seg.endEA = var_start + 0x1000  # Size chosen arbitrarily, should be enough.
    idaapi.add_segm_ex(var_seg, "VARS", "BSS", 0)
    # Create standard vars.
    for i, v in enumerate(nrs.strings.SYSVAR_NAMES.values()):
        idaapi.do_name_anyway(var_seg.startEA + i + 20, "$" + v)

    code_base = nsis.header.blocks[fileform.NB_ENTRIES].offset
    # Create sections functions.
    for i, section in enumerate(nsis.sections):
        if section.code == PTR_NONE:
            continue
        name = nsis.get_string(section.name_ptr)
        if not name:
            name = "_section" + str(i)
        ea = code_base + nrs.entry_to_offset(section.code)
        cname = canonize_name(name)
        AddEntryPoint(ea, ea, cname, 1)

    # Mark pages handlers.
    for i, page in enumerate(nsis.pages):
        for fn in ["prefunc", "showfunc", "leavefunc"]:
            addr = getattr(page, fn)
            if addr != PTR_NONE:
                name = "_page_{}_{}".format(i, fn)
                ea = code_base + nrs.entry_to_offset(addr)
                AddEntryPoint(ea, ea, name, 1)

    # Mark installer handlers.
    for event in [
        "Init",
        "InstSuccess",
        "InstFailed",
        "UserAbort",
        "GUIInit",
        "GUIEnd",
        "MouseOverSection",
        "VerifyInstDir",
        "SelChange",
        "RebootFailed",
    ]:
        addr = getattr(nsis.header, "code_on" + event)
        if addr != PTR_NONE:
            name = "_on" + event
            ea = code_base + nrs.entry_to_offset(addr)
            AddEntryPoint(ea, ea, name, 1)

    # Create strings.
    """
    strings_data = nsis.block(fileform.NB_STRINGS)
    strings_off = nsis.header.blocks[fileform.NB_STRINGS].offset
    i = 0
    while i < len(strings_data):
        decoded_string, length = \
            nrs.strings.decode(strings_data, i, nsis.version_major)
        decoded_string = str(decoded_string)
        string_name = canonize_name(decoded_string)
        idaapi.make_ascii_string(strings_off + i, length, ASCSTR_C)
        idaapi.set_cmt(strings_off + i, decoded_string, True)
        idaapi.do_name_anyway(strings_off + i, string_name)
        i += length
    #"""

    # Set processor to nsis script.
    SetProcessorType("nsis", SETPROC_ALL | SETPROC_FATAL)
    return 1
Example #18
0
def get_input_file_path():
    """Return the name of the currently processed file."""

    return idaapi.get_input_file_path()
Example #19
0
 def get_default_db_filename(self):
     """
     Get the default DIE DB filename
     """
     filename, extension = os.path.splitext(idaapi.get_input_file_path())
     return filename + ".ddb"
Example #20
0
from mem import SimSymbolicIdaMemory
import angr
import idaapi
import idc
import claripy

print
print "########### IDAngr ###########"
print "  usage: sm = StateManager()"
print
print " >> creating angr project..."
project = angr.Project(idaapi.get_input_file_path(),
                       load_options={"auto_load_libs": False})
print " >> done."


def StateShot():
    global project
    idc.RefreshDebuggerMemory()

    mem = SimSymbolicIdaMemory(memory_backer=project.loader.memory,
                               permissions_backer=None,
                               memory_id="mem")
    state = project.factory.blank_state(plugins={"memory": mem})

    for reg in sorted(project.arch.registers,
                      key=lambda x: project.arch.registers.get(x)[1]):
        if reg in ("sp", "bp", "ip"):
            continue
        try:
            setattr(state.regs, reg, idc.GetRegValue(reg))
Example #21
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)
Example #22
0
def _get_bin_name():
    return idaapi.get_input_file_path()
Example #23
0
def get_bootblock_start_address():
	file_path = idaapi.get_input_file_path()
	file_size = os.path.getsize(file_path)
	print("File size is {0}".format(file_size))
	addr = file_size - 0x10000
	return addr
Example #24
0
    def get_default_config(analysis_start_va, analysis_stop_va):
        """
        Returns a new AnalyzerConfig for the given entry point & cut
        """
        # this function will use the default parameters
        config = ConfigParser.RawConfigParser()
        config.optionxform = str

        config_path = PluginOptions.config_path
        # Load default part - XXX move this logic to PluginOptions
        configfile = os.path.join(config_path, "conf", "default.ini")
        bc_log.debug("Reading config from %s", configfile)
        r = config.read(configfile)
        if len(r) != 1:
            bc_log.warning("Default config file %s could not be found",
                           configfile)

        code_start_va, code_end_va = ConfigHelpers.get_code_section(
            analysis_start_va)
        code_len = code_end_va - code_start_va

        # [settings] section
        config.add_section('settings')
        config.set('settings', 'mem_model', ConfigHelpers.get_memory_model())
        # IDA doesn't really support real mode
        config.set('settings', 'mode', 'protected')
        config.set('settings', 'call_conv', ConfigHelpers.get_call_convention())
        config.set('settings', 'mem_sz', 32)
        config.set('settings', 'op_sz',
                   ConfigHelpers.get_bitness(code_start_va))
        config.set('settings', 'stack_width', ConfigHelpers.get_stack_width())

        # [loader section]
        config.add_section('loader')
        # code section va
        config.set('loader', 'code_va', "0x%X" % code_start_va)
        # code section offset
        config.set('loader', 'code_phys',
                   hex(idaapi.get_fileregion_offset(code_start_va)))
        # code section length
        config.set('loader', 'code_length', "0x%0X" % code_len)

        config.set('loader', 'analysis_ep', "0x%0X" % analysis_start_va)

        # Load default GDT/Segment registers according to file type
        ftype = ConfigHelpers.get_file_type()
        # XXX move this logic to PluginOptions
        if ftype == "pe":
            os_specific = os.path.join(config_path, "conf", "windows.ini")
        else:  # default to Linux config if not windows
            os_specific = os.path.join(config_path, "conf", "linux.ini")
        bc_log.debug("Reading OS config from %s", os_specific)
        config.read(os_specific)

        # [binary section]
        config.add_section('binary')
        input_file = idaapi.get_input_file_path()
        if not os.path.isfile(input_file):
            # get_input_file_path returns file path from IDB, which may not
            # exist locally if IDB has been moved (eg. send idb+binary to
            # another analyst)
            guessed_path = idc.GetIdbPath().replace('idb', 'exe')
            if os.path.isfile(guessed_path):
                input_file = guessed_path

        config.set('binary', 'filepath', input_file)
        config.set('binary', 'format', ftype)

        # [sections section]
        config.add_section("sections")
        for s in ConfigHelpers.get_sections():
            config.set("sections", "section[%s]" % s[0],
                       "0x%x, 0x%x, 0x%x, 0x%x" % (s[1], s[2], s[3], s[4]))

        # [state section]
        config.add_section("state")
        regs = ConfigHelpers.get_registers_with_state()
        for rname, val in regs.iteritems():
            if rname != "esp":
                config.set("state", ("reg[%s]" % rname), val)
        # Default stack
        config.set("state", "reg[esp]", "0x2000")
        config.set("state", "stack[0x1000*8192]", "|00|?0xFF")

        imports = ConfigHelpers.get_imports()
        # [import] section
        config.add_section('imports')
        for ea, imp in imports.iteritems():
            if imp[0]:
                name = "%s, \"%s\"" % imp
            else:
                name = "all,\"%s\"" % imp[1]
            config.set('imports', ("0x%x" % ea), name)
        # list all files in config_path/lib/*.{c,no}.
        # for each lib (same base filename) keep .no if it exists, else .c
        headers_filenames = glob.glob(os.path.join(config_path, 'lib', '*.no'))
        # Add .c if there is no associated .no
        for c in glob.glob(os.path.join(config_path, 'lib', '*.c')):
            if c[:-2] + '.no' not in headers_filenames:
                headers_filenames.append(c)
        # remove duplicates
        config.set('imports', 'headers', ','.join(headers_filenames))
        # [libc section]
        # config.add_section('libc')
        # config.set('libc', 'call_conv', 'fastcall')
        # config.set('libc', '*', 'open(@, _)')
        # config.set('libc', '*', 'read<stdcall>(@, *, @)')
        ac = AnalyzerConfig(config)
        ac.analysis_ep = analysis_start_va
        ac.stop_address = analysis_stop_va
        return ac
Example #25
0
import sys
import os
import traceback

import idaapi

import logging
logger = logging.getLogger(__name__)
if not logger.handlers:
    handler = logging.StreamHandler(stream=sys.stdout)
    logger.addHandler(handler)

try:
    Wait()
    name = os.path.basename(idaapi.get_input_file_path())

    for seg_ea in Segments():
        # For each of the functions
        for ea in Functions(seg_ea, SegEnd(seg_ea)):
            old_name = GetFunctionName(ea)
            if not old_name.startswith("sub"):
                continue
            new_name = "%s_%s" % (name, old_name)
            idc.MakeNameEx(ea, new_name, idc.SN_NOWARN)

except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    logger.error("Uncaught exception",
                 exc_info=(exc_type, exc_value, exc_traceback))
Example #26
0
            self.init_gp = PsxExe.__get_real_gp(self.rom_addr, self.rom_addr + self.rom_size)

        if self.init_gp != 0:
            idc.process_config_line("MIPS_GP=0x%08X" % self.init_gp)
        else:
            idaapi.warning('$GP from header is zero! Check \'start \' function for a $gp loading instruction.\n')


def accept_file(li_, filename_):
    return 0


def load_file(li_, neflags_, format_):
    return 0


if __name__ == '__main__':
    fname = idaapi.get_input_file_path()
    psx = PsxExe(os.path.basename(fname), ONLY_FIRST, MIN_ENTROPY)

    f = open(fname, 'rb')
    good = psx.parse(f, True)
    f.close()

    if good:
        detect = DetectPsyQ(psx.get_exe_name(), ONLY_FIRST, MIN_ENTROPY)
        version = detect.get_psyq_version(psx.rom_addr, psx.rom_addr + psx.rom_size)
        psx.apply_psyq_signatures_by_version(version)

        psx.update_gp()
from sets import Set
import json
import idaapi
import idc

print('My Script is now running...')
print('Waiting for idapro...')
idaapi.autoWait()
print('start persisting...')

idaapi.rebase_program(-1*idaapi.get_imagebase(), 0)

ss = idaapi.get_input_file_path()
pn = os.path.splitext(ss)[0]
callees = dict()
funcmap = dict()
data = dict()
data['name'] = pn

for seg_ea in Segments():
    for function_ea in Functions(SegStart(seg_ea), SegEnd(seg_ea)):
        #fill call graph
        # For each of the incoming references
        for ref_ea in CodeRefsTo(function_ea, 0):
             # Get the name of the referring function
             caller_name = GetFunctionName(ref_ea)
             # Add the current function to the list of functions called by the referring function
             callees[caller_name] = callees.get(caller_name, Set())
             callees[caller_name].add(function_ea)

data['functions'] = list()
Example #28
0
def get_binary_path():
    return idaapi.get_input_file_path()