Esempio n. 1
0
def load():
    """
    Perform necessary steps to load the plugin inside IDA. If no IDB is open, it
    will wait until it is open to load it.
    """
    if idaapi.get_root_filename() is None:
        # No idb open yet
        def handler(event, old=0):
            if event == idaapi.NW_OPENIDB:
                _do_load()
            elif event == idaapi.NW_TERMIDA:
                idaapi.notify_when(
                    idaapi.NW_TERMIDA | idaapi.NW_OPENIDB | idaapi.NW_REMOVE,
                    handler)

        def _install():
            idaapi.notify_when(idaapi.NW_TERMIDA | idaapi.NW_OPENIDB, handler)
            # return -1 to remove the timer
            return -1

        # It's possible we can't use the notify_when API call yet when IDA opens
        # so try register a timer to add the event listner in the proper "state"
        idaapi.register_timer(1, _install)
    else:
        # IDA is fully loaded and an idb is open, just load the plugin.
        _do_load()
Esempio n. 2
0
 def __init__(self, parser):
     self.color = False
     self.prev_loc = None
     self.prev_node = None
     self.name = idaapi.get_root_filename()
     self.base = idaapi.get_imagebase()
     rs_log("module base 0x%x" % self.base)
     self.base_remote = None
     self.gm = GraphManager()
     self.hexsync = Syncrays()
     self.parser = parser
     self.broker_sock = None
     self.is_active = False
     self.dbg_dialect = None
     self.req_handlers = {
         'broker': self.req_broker,
         'loc': self.req_loc,
         'cmd': self.req_cmd,
         'cmt': self.req_cmt,
         'rcmt': self.req_rcmt,
         'fcmt': self.req_fcmt,
         'raddr': self.req_raddr,
         'rbase': self.req_rbase,
         'cursor': self.req_cursor,
         'patch': self.req_patch,
         'rln': self.req_rln,
         'rrln': self.req_rrln,
         'lbl': self.req_lbl,
         'bc': self.req_bc,
         'bps_get': self.req_bps_get,
         'bps_set': self.req_bps_set,
         'modcheck': self.req_modcheck,
         'dialect': self.req_set_dbg_dialect
     }
     self.prev_req = ""  # used as a cache if json is not completely received
Esempio n. 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)
Esempio n. 4
0
 def __init__(self, parser):
     self.color = False
     self.prev_loc = None
     self.prev_node = None
     self.name = idaapi.get_root_filename()
     print "[sync] name %s" % self.name
     self.base = idaapi.get_imagebase()
     print "[sync] module base 0x%x" % self.base
     self.base_remote = None
     self.gm = GraphManager()
     self.parser = parser
     self.broker_sock = None
     self.is_active = False
     self.dbg_dialect = None
     self.req_handlers = {
         'broker': self.req_broker,
         'loc': self.req_loc,
         'cmd': self.req_cmd,
         'cmt': self.req_cmt,
         'rcmt': self.req_rcmt,
         'fcmt': self.req_fcmt,
         'raddr': self.req_raddr,
         'rln': self.req_rln,
         'lbl': self.req_lbl,
         'bc': self.req_bc,
         'bps_get': self.req_bps_get,
         'bps_set': self.req_bps_set,
         'modcheck': self.req_modcheck,
         'dialect': self.req_set_dbg_dialect
     }
Esempio n. 5
0
def export_tags(tags):
    out_dir = idautils.GetIdbDir() + idaapi.get_root_filename(
    ) + "_TagSource" + ".json"
    with open(out_dir, 'wb') as f:
        json.dump(tags, f)
    print("[TagSource] Tags created : " + str(len(tags)))
    print("[TagSource] Tags exported : " + out_dir)
Esempio n. 6
0
 def __init__(self, parser):
     self.color = False
     self.prev_loc = None
     self.prev_node = None
     self.name = idaapi.get_root_filename()
     print "[sync] name %s" % self.name
     self.base = idaapi.get_imagebase()
     print "[sync] module base 0x%x" % self.base
     self.base_remote = None
     self.gm = GraphManager()
     self.parser = parser
     self.broker_sock = None
     self.is_active = False
     self.dbg_dialect = None
     self.req_handlers = {
         "broker": self.req_broker,
         "loc": self.req_loc,
         "cmd": self.req_cmd,
         "cmt": self.req_cmt,
         "rcmt": self.req_rcmt,
         "fcmt": self.req_fcmt,
         "raddr": self.req_raddr,
         "rln": self.req_rln,
         "lbl": self.req_lbl,
         "bc": self.req_bc,
         "bps_get": self.req_bps_get,
         "bps_set": self.req_bps_set,
         "modcheck": self.req_modcheck,
         "dialect": self.req_set_dbg_dialect,
     }
Esempio n. 7
0
    def handle_name_aliasing(self):
        name = idaapi.get_root_filename()
        rs_log("default idb name: %s" % name)

        # check in conf for name aliasing
        os.environ['IDB_PATH'] = os.path.realpath(IDB_PATH)
        for loc in ('IDB_PATH', 'USERPROFILE', 'HOME'):
            if loc in os.environ:
                try:
                    confpath = os.path.join(os.path.realpath(os.environ[loc]), '.sync')
                    if os.path.exists(confpath):
                        rs_log("found config file: %s" % confpath)
                        config = SafeConfigParser()
                        config.read(confpath)

                        if config.has_option('ALIASES', name):
                            alias = config.get('ALIASES', name)
                            if alias != "":
                                name = alias
                                rs_log("overwrite idb name with %s" % name)

                        break
                except Exception as e:
                    err_log('failed to load configuration file')

        self.pdb_name_warning(name)
        return name
Esempio n. 8
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)
Esempio n. 9
0
 def __init__(self, parser, form):
     self.form = form
     self.color = False
     self.prev_loc = None
     self.prev_node = None
     self.name = idaapi.get_root_filename()
     print "[sync] name %s" % self.name
     self.base = idaapi.get_imagebase()
     print "[sync] module base 0x%x" % self.base
     self.base_remote = None
     self.gm = GraphManager()
     self.parser = parser
     self.broker_sock = None
     self.is_active = False
     self.dbg_dialect = None
     self.req_handlers = {
         'broker': self.req_broker,
         'loc': self.req_loc,
         'cmd': self.req_cmd,
         'cmt': self.req_cmt,
         'rcmt': self.req_rcmt,
         'fcmt': self.req_fcmt,
         'raddr': self.req_raddr,
         'rln': self.req_rln,
         'lbl': self.req_lbl,
         'bc': self.req_bc,
         'bps_get': self.req_bps_get,
         'bps_set': self.req_bps_set,
         'modcheck': self.req_modcheck,
         'dialect': self.req_set_dbg_dialect
     }
Esempio n. 10
0
    def __init__(self):
        self.fileName = idaapi.get_root_filename()
        self.fileMD5 = idautils.GetInputFileMD5()
        self.authorName = idc.ARGV[1]
        self.allStrings = {}
        self.subStrings = ["cout", "endl", "Xlength_error", "cerr"]
        self.returns = {"ret": 0, "retn": 0}
        self.libraryFunctionNamesDict = {
            "printf": [0, 0],
            "fprintf": [0, 0],
            "cout": [0, 0],
            "exit": [0, 0],
            "fflush": [0, 0],
            "endl": [0, 0],
            "puts": [0, 0],
            "Xlength_error": [0, 0],
            "clock": [0, 0],
            "cerr": [0, 0]
        }  #,"scanf":[0,0]}

        self.standardRegisters = {
            "eax": 0,
            "ebx": 0,
            "ecx": 0,
            "edx": 0,
            "esi": 0,
            "edi": 0
        }
        self.libraryFunctionNameEADict = {}
Esempio n. 11
0
    def OnCreate(self, form):
        print "[sync] form create"

        # Get parent widget
        parent = self.FormToPyQtWidget(form)

        # Create checkbox
        self.cb = QtWidgets.QCheckBox("Synchronization enable")
        self.cb.move(20, 20)
        self.cb.stateChanged.connect(self.cb_change_state)

        # Create label
        label = QtWidgets.QLabel('Overwrite idb name:')

        name = idaapi.get_root_filename()
        print "[sync] default idb name: %s" % name
        # Check in conf for name overwrite
        confpath = os.path.join(os.path.realpath(IDB_PATH), '.sync')
        if os.path.exists(confpath):
            print "[sync] found config file: %s" % confpath
            config = ConfigParser.SafeConfigParser()
            config.read(confpath)
            if config.has_option(name, 'name'):
                name = config.get(name, 'name')
                print "[sync] overwrite idb name with %s" % name

        # Create input field
        self.input = QtWidgets.QLineEdit(parent)
        self.input.setText(name)
        self.input.setMaxLength = 256
        self.input.setFixedWidth(300)

        # Create restart button
        self.btn = QtWidgets.QPushButton('restart', parent)
        self.btn.setToolTip('Restart broker.')
        self.btn.clicked.connect(self.cb_btn_restart)

        # Create layout
        layout = QtWidgets.QGridLayout()
        layout.addWidget(self.cb)
        layout.addWidget(label)
        layout.addWidget(self.input)
        layout.addWidget(self.btn, 2, 2)
        layout.setColumnStretch(3, 1)
        layout.setRowStretch(3, 1)
        parent.setLayout(layout)

        # workaround: crash when instanciated in Broker.__init__
        # weird interaction with Qtxxx libraries ?
        #  File "C:\Python27\Lib\argparse.py", line 1584, in __init__
        #    self._positionals = add_group(_('positional arguments'))
        #  File "C:\Python27\Lib\gettext.py", line 566, in gettext
        #    return dgettext(_current_domain, message)
        #  TypeError: 'NoneType' object is not callable
        self.parser = argparse.ArgumentParser()
        self.parser.add_argument("-a", "--address", nargs=1, action='store')
        self.parser.add_argument('msg', nargs=argparse.REMAINDER)

        # Synchronization is enabled by default
        self.cb.toggle()
Esempio n. 12
0
    def run(self, arg):
        if not idaapi.get_root_filename():
            print('[sync] please load a file/idb before')
            return

        global SyncForm
        SyncForm = SyncForm_t()
        SyncForm.Show()
Esempio n. 13
0
    def __init__(self):
        self.client = MongoClient('localhost', 27017)
        self.db = self.client.BinAuthor
        self.collection = self.db.Mahalanobis

        self.fileName = idaapi.get_root_filename()
        self.fileMD5 = idautils.GetInputFileMD5()
        self.authorName = self.fileName
Esempio n. 14
0
 def run(self, arg_=None):
     tmp_file = "/tmp/tinfo_storage"  # windows, do something lol
     if len(get_root_filename()) == 15:  # dest -> 15, source !15
         tinfo_map = self.receive_message(tmp_file)
         self.type_one_function(tinfo_map)
     else:
         self.dump_tinfos(tmp_file)
     print "done"
Esempio n. 15
0
def setup():
    if idaapi.get_root_filename():
        on_open()
    else:
        idaapi.notify_when(
            idaapi.NW_OPENIDB | idaapi.NW_CLOSEIDB | idaapi.NW_TERMIDA,
            eventhook)
    return -1
Esempio n. 16
0
    def OnCreate(self, form):
        print "[sync] form create"

        # Get parent widget
        parent = self.FormToPySideWidget(form)

        # Create checkbox
        self.cb = QtGui.QCheckBox("Synchronization enable")
        self.cb.move(20, 20)
        self.cb.stateChanged.connect(self.cb_change_state)

        # Create label
        label = QtGui.QLabel("Overwrite idb name:")

        # Check in conf for name overwrite
        name = idaapi.get_root_filename()
        confpath = os.path.join(os.path.realpath(IDB_PATH), ".sync")
        if os.path.exists(confpath):
            config = ConfigParser.SafeConfigParser()
            config.read(confpath)
            if config.has_option(name, "name"):
                name = config.get(name, "name")
                print "[sync] overwrite idb name with %s" % name

        # Create input field
        self.input = QtGui.QLineEdit(parent)
        self.input.setText(name)
        self.input.setMaxLength = 256
        self.input.setFixedWidth(300)

        # Create restart button
        self.btn = QtGui.QPushButton("restart", parent)
        self.btn.setToolTip("Restart broker.")
        self.btn.clicked.connect(self.cb_btn_restart)

        # Create layout
        layout = QtGui.QGridLayout()
        layout.addWidget(self.cb)
        layout.addWidget(label)
        layout.addWidget(self.input)
        layout.addWidget(self.btn, 2, 2)
        layout.setColumnStretch(3, 1)
        layout.setRowStretch(3, 1)
        parent.setLayout(layout)

        # workaround: crash when instanciated in Broker.__init__
        # weird interaction with Qtxxx libraries ?
        #  File "C:\Python27\Lib\argparse.py", line 1584, in __init__
        #    self._positionals = add_group(_('positional arguments'))
        #  File "C:\Python27\Lib\gettext.py", line 566, in gettext
        #    return dgettext(_current_domain, message)
        #  TypeError: 'NoneType' object is not callable
        self.parser = argparse.ArgumentParser()
        self.parser.add_argument("-a", "--address", nargs=1, action="store")
        self.parser.add_argument("msg", nargs=argparse.REMAINDER)

        # Synchronization is enabled by default
        self.cb.toggle()
Esempio n. 17
0
    def run(self, arg):
        if not idaapi.get_root_filename():
            rs_log('please load a file/idb before')
            return

        global SyncForm
        SyncForm = SyncForm_t()
        SyncForm.Show()
        rs_log("plugin loaded")
Esempio n. 18
0
 def wrapper(*args, **kwargs):
     if cls.get_dbg_mode():
         cur_workpath = os.getcwd()
         log_filename = '%s.xdbg' % idaapi.get_root_filename()
         log_filepath = os.path.join(cur_workpath, log_filename)
         cls.log_path = log_filepath
         if cls.log_fd:
             cls.log_fd = None
         cls.log_fd = open(cls.log_path, 'a')
     return func(*args, **kwargs)
Esempio n. 19
0
def on_open():
    print 'revsync: file opened:', idaapi.get_root_filename()
    global auto_wait
    if autoIsOk():
        on_load()
        auto_wait = False
    else:
        auto_wait = True
        print 'revsync: waiting for auto analysis'
        if not hasattr(IDP_Hooks, 'auto_empty_finally'):
            idaapi.register_timer(1000, wait_for_analysis)
Esempio n. 20
0
 def __init__(self):
     self.functionAddresstoRealFunctionName = {}
     self.functionRegisterChains = {}
     self.finalOutput = ''
     self.finalOutputFunctionLevel = ''
     self.simhashList = []
     self.registerChainMinhash = []
     self.blocks = []
     self.fileName = idaapi.get_root_filename()
     self.fileMD5 = idautils.GetInputFileMD5()
     self.authorName = idc.ARGV[1]
Esempio n. 21
0
 def upload(self, ctx):
     start = time.time()
     func_count = 0
     bb_count = 0
     call_count = 0
     target = idaapi.get_root_filename()
     hash = idc.GetInputMD5()
     tx = self.neo.cypher.begin()
     insert_binary = "MERGE (n:Binary {name:{N},hash:{H}}) RETURN n"
     insert_func = "MERGE (n:Function {name:{N},start:{S},flags:{F}}) RETURN n"
     insert_bb = "MERGE (n:BasicBlock {start:{S}, end:{E}}) RETURN n"
     create_relationship = "MATCH (u:Function {name:{N}}), (r:Function {start:{S}}) CREATE (u)-[:CALLS]->(r)"
     create_contains = "MATCH (u:BasicBlock {start:{S}}), (f:Function {name:{N}}) CREATE (f)-[:CONTAINS]->(u)"
     create_inside = "MATCH (u:Function {start:{S}}), (b:Binary {hash:{H}}) CREATE (f)-[:INSIDE]->(b)"
     self.neo.cypher.execute(insert_binary, {"N": target, "H": hash})
     self.neo.cypher.execute("CREATE INDEX ON :Function(start)")
     #self.neo.cypher.execute("CREATE INDEX ON :Function(name)")
     self.neo.cypher.execute("CREATE INDEX ON :BasicBlock(start)")
     for f in Functions():
         tx.append(create_inside, {"S": f, "H": hash})
         callee_name = GetFunctionName(f)
         flags = get_flags(f)
         type = GetType(f)
         if type:
             return_type = type.split()[0]
             print type
             end_return = type.find(' ')
             start_args = type.find('(')
             print type[end_return + 1:start_args]
             print type[start_args + 1:].split(',')
         else:
             print GuessType(f)
         tx.append(insert_func, {"N": callee_name, "S": f, "F": flags})
         func_count += 1
         fc = idaapi.FlowChart(idaapi.get_func(f))
         for block in fc:
             tx.append(insert_bb, {"S": block.startEA, "E": block.endEA})
             tx.append(create_contains, {"S": block.startEA, "N": f})
             bb_count += 1
     tx.process()
     tx.commit()
     tx = self.neo.cypher.begin()
     for f in Functions():
         for xref in CodeRefsTo(f, 0):
             caller_name = GetFunctionName(xref)
             if caller_name != '':
                 tx.append(create_relationship, {"N": caller_name, "S": f})
                 call_count += 1
     tx.process()
     tx.commit()
     print "Upload ran in: " + str(time.time() - start)
     print "Uploaded " + str(func_count) + " functions, " + str(
         call_count) + " function calls and " + str(
             bb_count) + " basic blocks."
Esempio n. 22
0
def get_all_pooltags():
    """ Returns a string with a 'pooltags.txt' formatted string of 'pool tag' - 'driver' - 'functions which use it'.
	"""

    tags = find_pool_tags()
    out = ''
    file_name = idaapi.get_root_filename()
    for tag in tags.keys():
        desc = 'Called by: '
        desc += ', '.join(tags[tag])
        out += '{} - {} - {}\n'.format(tag, file_name, desc)
    return out
Esempio n. 23
0
def main(function, f_image, f_all, f_overwrite):

    sys.setrecursionlimit(3000)

    program = idaapi.get_root_filename()
    start_time = time.time()
    cfgs = get_cfgs()
    dump_function_info(cfgs, program, function, f_image, f_all, f_overwrite)
    result_time = time.time() - start_time

    print "Dump finished."
    print "result_time: " + str(result_time) + " sec."
Esempio n. 24
0
	def upload(self,ctx):
		start = time.time()
		func_count = 0
		bb_count = 0
		call_count = 0
		target = idaapi.get_root_filename()
		hash = idc.GetInputMD5()
		tx = self.neo.cypher.begin()
		insert_binary = "MERGE (n:Binary {name:{N},hash:{H}}) RETURN n"
		insert_func = "MERGE (n:Function {name:{N},start:{S},flags:{F}}) RETURN n"
		insert_bb = "MERGE (n:BasicBlock {start:{S}, end:{E}}) RETURN n"
		create_relationship = "MATCH (u:Function {name:{N}}), (r:Function {start:{S}}) CREATE (u)-[:CALLS]->(r)"
		create_contains = "MATCH (u:BasicBlock {start:{S}}), (f:Function {name:{N}}) CREATE (f)-[:CONTAINS]->(u)"
		create_inside = "MATCH (u:Function {start:{S}}), (b:Binary {hash:{H}}) CREATE (f)-[:INSIDE]->(b)"
		self.neo.cypher.execute(insert_binary, {"N":target, "H":hash})
		self.neo.cypher.execute("CREATE INDEX ON :Function(start)")
		#self.neo.cypher.execute("CREATE INDEX ON :Function(name)")
		self.neo.cypher.execute("CREATE INDEX ON :BasicBlock(start)")
		for f in Functions():
			tx.append(create_inside, {"S":f, "H":hash})
			callee_name = GetFunctionName(f)
			flags = get_flags(f)
			type = GetType(f)
			if type:
				return_type = type.split()[0]
				print type
				end_return = type.find(' ')
				start_args = type.find('(')
				print type[end_return +1:start_args]
				print type[start_args+1:].split(',')
			else:
				print GuessType(f)
			tx.append(insert_func, {"N": callee_name, "S":f, "F":flags})
			func_count += 1
			fc = idaapi.FlowChart(idaapi.get_func(f))
			for block in fc:
				tx.append(insert_bb, {"S":block.startEA,"E":block.endEA})
				tx.append(create_contains,{"S":block.startEA,"N":f})
				bb_count += 1
		tx.process()
		tx.commit()
		tx = self.neo.cypher.begin()
		for f in Functions():
			for xref in CodeRefsTo(f,0):
				caller_name = GetFunctionName(xref)
				if caller_name != '':
					tx.append(create_relationship,{"N":caller_name,"S":f})
					call_count += 1
		tx.process()
		tx.commit()
		print "Upload ran in: " + str(time.time() - start)
		print "Uploaded " + str(func_count) + " functions, " + str(call_count) +" function calls and " + str(bb_count) + " basic blocks."
Esempio n. 25
0
def main():
    if not idaapi.get_root_filename():
        print "[sync] please load a file/idb before"
        return

    global SyncForm

    try:
        SyncForm
    except:
        SyncForm = SyncForm_t()

    SyncForm.Show()
Esempio n. 26
0
def main():
    if not idaapi.get_root_filename():
        print "[sync] please load a file/idb before"
        return

    global SyncForm

    try:
        SyncForm
    except:
        SyncForm = SyncForm_t()

    SyncForm.Show()
Esempio n. 27
0
def colorBlocks():
    ''' return list of branches not taken '''
    fname = idaapi.get_root_filename()
    latest_funs_file = fname+'.hits' 
    if not os.path.isfile(latest_funs_file):
        ''' maybe a symbolic link, ask monitor for name '''
        cmd = '@cgc.getCoverageFile()'
        latest_funs_file = gdbProt.Evalx('SendGDBMonitor("%s");' % cmd).strip()
        if not os.path.isfile(latest_funs_file):
            print('No hits file found %s' % latest_funs_file)
            return
    all_hits_file = fname+'.all.hits'
    pre_hits_file = fname+'.pre.hits'
    edges = doColor(latest_funs_file, all_hits_file, pre_hits_file)
    return edges
Esempio n. 28
0
    def OnCreate(self, form):
        print "[sync] form create"

        # Get parent widget
        parent = self.FormToPySideWidget(form)

        # Create checkbox
        self.cb = QtGui.QCheckBox("Synchronization enable")
        self.cb.move(20, 20)
        self.cb.stateChanged.connect(self.cb_change_state)

        # Create label
        label = QtGui.QLabel('Overwrite idb name:')

        # Create input field
        self.input = QtGui.QLineEdit(parent)
        self.input.setText(idaapi.get_root_filename())
        self.input.setMaxLength = 256
        self.input.setFixedWidth(300)

        # Create restart button
        self.btn = QtGui.QPushButton('restart', parent)
        self.btn.setToolTip('Restart broker.')
        self.btn.clicked.connect(self.cb_btn_restart)

        # Create layout
        layout = QtGui.QGridLayout()
        layout.addWidget(self.cb)
        layout.addWidget(label)
        layout.addWidget(self.input)
        layout.addWidget(self.btn, 2, 2)
        layout.setColumnStretch(3, 1)
        layout.setRowStretch(3, 1)
        parent.setLayout(layout)

        # workaround: crash when instanciated in Broker.__init__
        # weird interaction with Qtxxx libraries ?
        #  File "C:\Python27\Lib\argparse.py", line 1584, in __init__
        #    self._positionals = add_group(_('positional arguments'))
        #  File "C:\Python27\Lib\gettext.py", line 566, in gettext
        #    return dgettext(_current_domain, message)
        #  TypeError: 'NoneType' object is not callable
        self.parser = argparse.ArgumentParser()
        self.parser.add_argument("-a", "--address", nargs=1, action='store')
        self.parser.add_argument('msg', nargs=argparse.REMAINDER)

        # Synchronization is enabled by default
        self.cb.toggle()
Esempio n. 29
0
    def __init__(self):
        idaapi.action_handler_t.__init__(self)
        self.sync_on = False
        self.name = None
        name = idaapi.get_root_filename()
        confpath = os.path.join(os.path.realpath(IDB_PATH), '.sync')
        if os.path.exists(confpath):
            config = ConfigParser.SafeConfigParser()
            config.read(confpath)
            if config.has_option(name, 'name'):
                name = config.get(name, 'name')
                print "[sync] overwrite idb name with %s" % name
        self.name = name

        self.hotkeys_ctx = []
        self.broker = None
Esempio n. 30
0
    def __init__(self):
        idaapi.action_handler_t.__init__(self)
        self.sync_on = False
        self.name = None
        name = idaapi.get_root_filename()
        confpath = os.path.join(os.path.realpath(IDB_PATH), '.sync')
        if os.path.exists(confpath):
            config = ConfigParser.SafeConfigParser()
            config.read(confpath)
            if config.has_option(name, 'name'):
                name = config.get(name, 'name')
                print "[sync] overwrite idb name with %s" % name
        self.name = name

        self.hotkeys_ctx = []
        self.broker = None
Esempio n. 31
0
    def handle_name_aliasing(self):
        name = idaapi.get_root_filename()
        rs_log("default idb name: %s" % name)

        try:
            conf = load_configuration(name)
            if conf.path:
                rs_log("found config file: %s" % repr(conf))
            if conf.alias:
                name = conf.alias
                rs_log("overwrite idb name with %s" % name)
        except Exception as e:
            rs_log('failed to load configuration file')

        self.pdb_name_warning(name)
        return name
Esempio n. 32
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 = []
Esempio n. 33
0
    def on_create(self, form):
        self.ImageName = idaapi.get_root_filename()
        self.ImageBase = idaapi.get_imagebase()

        self.parent = self.FormToPyQtWidget(form)

        self.Tree = QtWidgets.QTreeWidget()
        self.Tree.setHeaderLabels(("Name", "Address"))
        self.Tree.setColumnWidth(0, 200)
        self.Tree.setColumnWidth(1, 100)

        self.Tree.itemClicked.connect(self.tree_clicked)

        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.Tree)

        self.populate_tree()
        self.parent.setLayout(layout)
Esempio n. 34
0
    def _normalize_coverage(self, coverage_data, metadata):
        """
        Normalize loaded DrCov data to the database metadata.
        """

        # extract the coverage relevant to this IDB (well, the root binary)
        root_filename   = idaapi.get_root_filename()
        coverage_blocks = coverage_data.filter_by_module(root_filename)

        # rebase the basic blocks
        base = idaapi.get_imagebase()
        rebased_blocks = rebase_blocks(base, coverage_blocks)

        # coalesce the blocks into larger contiguous blobs
        condensed_blocks = coalesce_blocks(rebased_blocks)

        # flatten the blobs into individual instructions or addresses
        return metadata.flatten_blocks(condensed_blocks)
Esempio n. 35
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 = []
Esempio n. 36
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)
Esempio n. 37
0
def genSignatures():

    ea = idc.get_screen_ea()
    sig_dir = '/tmp'
    fname = idaapi.get_root_filename()
    print('file is %s' % fname)
    base_file = os.path.join(sig_dir, fname) + '.json'
    seg_start = idc.SegStart(ea)
    seg_end = idc.SegEnd(ea)
    print('seg start: %x  seg_end: %x' % (seg_start, seg_end))
    blocks = open(base_file, 'w')
    fun_sig = {}
    for function_ea in idautils.Functions(seg_start, seg_end):
        fun_name = idc.GetFunctionName(function_ea)
        fun_sig[fun_name] = getFunSig(function_ea)
    blocks.write(json.dumps(fun_sig))
    print('done creating %s' % base_file)
    blocks.flush()
    blocks.close()
Esempio n. 38
0
def start_binkit_server(connection_filename):
    port = 18861
    while 1:
        try:
            t = ThreadedServer(BinKitService(), port = port, protocol_config = {
                'allow_public_attrs': True,
            })
            print('Listening on %d\n' % port)
            md5 = idc.GetInputMD5().lower()
            try:
                with open(connection_filename, "w") as fd:
                    json.dump({'port': port, 'md5': md5, 'root_fileanem': idaapi.get_root_filename(), 'input_filename': idaapi.get_input_file_path()}, fd)
            except:
                traceback.print_exc()

            t.start()
            break
        except:
            port += 1
            traceback.print_exc()
Esempio n. 39
0
def load():
    """
    Perform necessary steps to load the plugin inside IDA. If no IDB is open, it
    will wait until it is open to load it.
    """
    if idaapi.get_root_filename() is None:
        # No idb open yet
        def handler(event, old=0):
            if event == idaapi.NW_OPENIDB:
                _do_load()
            elif event == idaapi.NW_TERMIDA:
                idaapi.notify_when(idaapi.NW_TERMIDA | idaapi.NW_OPENIDB | idaapi.NW_REMOVE, handler)
        def _install():
            idaapi.notify_when(idaapi.NW_TERMIDA | idaapi.NW_OPENIDB, handler)
            # return -1 to remove the timer
            return -1
        # It's possible we can't use the notify_when API call yet when IDA opens
        # so try register a timer to add the event listner in the proper "state"
        idaapi.register_timer(1, _install)
    else:
        # IDA is fully loaded and an idb is open, just load the plugin.
        _do_load()
Esempio n. 40
0
def filename():
    '''return the filename that the database was built from'''
    return idaapi.get_root_filename()
Esempio n. 41
0
 # python
 "pypath_win32": "C:\\Python26\\python.exe",
 "pypath_linux": "python",
 # default tabs enabled
 "enabled_tabs": ["File System", "Pathfinding", "Scripts"],
 # show splash boolean
 "show_splash": True,
 # architecture
 "architecture": (lambda: idc.__EA64__ and "64" or "32")(),
 # filesystem options
 # valid options are 'netnode' or 'segment'
 "file_system_type": "netnode",
 "netnode_num": 0xBEEFFACE,
 "segment_size": 0x200000,
 "segment_name": ".zip",
 "file_name": idaapi.get_root_filename()[:-4] + ".DB",
 "full_file_name": (lambda x: "." in x and x.split(".")[0] + ".DB" or x + ".DB")(idaapi.get_root_filename()),
 "ida_user_dir": idaapi.get_user_idadir(),
 "user_scripts_dir": idaapi.get_user_idadir() + os.sep + "user" + os.sep + "bin",
 "vtrace_scripts_dir": idaapi.get_user_idadir() + os.sep + "user" + os.sep + "bin" + os.sep + "vtrace",
 "toolbag_dir": idaapi.get_user_idadir() + os.sep + "toolbag",
 # hotkeys
 "history_hotkey": "Ctrl-Space",
 "undo_history": "Ctrl-Z",
 "create_mark_hotkey": "Alt-M",
 "jump_mark_hotkey": "Ctrl-M",
 "path_start": "Ctrl-S",
 "path_end": "Ctrl-E",
 "add_edge_src": "Ctrl-[",
 "add_edge_dst": "Ctrl-]",
 # these two are currently deprecated, ScreenEA() is used
import idc
import idaapi
import idautils

# Initialize IDA Python
idaapi.autoWait()

# List all function names into func_names
func_names = []
for function_address in idautils.Functions():
    func_names.append(idc.GetFunctionName(function_address))

# Output function names to file
filename = idaapi.get_root_filename()
with open('%s_functions.txt' % filename, 'w') as output_file:
    output_file.write('\n'.join(func_names))

idc.Exit(0)
Esempio n. 43
0
import idautils
import idaapi
from py2neo import authenticate, Graph, Node, Relationship

neo_instance = "192.168.1.4:7474"
neo_username = "******"
neo_password = "******"

authenticate(neo_instance,neo_username,neo_password)
neo = Graph("http://192.168.1.4:7474/db/data")
try:
	neo.schema.create_uniqueness_constraint("Function", "name")
except:
	pass
	
target = idaapi.get_root_filename()
for f in Functions():
	callee_name = GetFunctionName(f)
	callee = neo.merge_one("Function","name",callee_name)
	if target not in callee.labels:
		callee.labels.add(target)
		callee.push()
	for xref in XrefsTo(f):
		caller_name = GetFunctionName(xref.frm)
		if caller_name == '':
			print "Indirect call to " + callee_name + " ignored."
			continue
		caller = neo.merge_one("Function","name",caller_name)
		if target not in callee.labels:
			callee.labels.add(target)
			callee.push()