示例#1
0
def main():
    f = open(idc.AskFile(0, '*.json', 'Where is the first JSON report you want to load ?'), 'r')
    report = json.load(f)
    l1 = report['basic_blocks_info']['list']

    f = open(idc.AskFile(0, '*.json', 'Where is the second JSON report you want to load ?'), 'r')
    report = json.load(f)
    l2 = report['basic_blocks_info']['list']
    c = idc.AskStr('black', 'Which color do you want ?').lower()

    addresses_l1 = set(r['address'] for r in l1)    
    addresses_l2 = set(r['address'] for r in l2)
    dic_l2 = dict((k['address'], k['nbins']) for k in l2)

    diff = addresses_l2 - addresses_l1
    print '%d bbls in the first execution' % len(addresses_l1)
    print '%d bbls in the second execution' % len(addresses_l2)
    print 'Differences between the two executions: %d bbls' % len(diff)
    
    assert(len(addresses_l1) < len(addresses_l2))

    funcs = defaultdict(list)
    for i in diff:
        try:
            color(i, dic_l2[i], c)
            funcs[get_func(i).startEA].append(i)
        except Exception, e:
            print 'fail %s' % str(e)
示例#2
0
    def TwoProfColor(self):
        self.is_singleprofile = False
        self.is_twoprofile = True

        if not self.is_reanalyse:
            self.ProgectWarning()
            self.fname = idc.AskFile(0, '*.*',
                                     'Select first profile file, plz')
            self.sname = idc.AskFile(0, '*.*',
                                     'Select second profile file, plz')

        if (self.fname == None) or (self.sname == None):
            return False

        first = open(self.fname, 'rb')

        second = open(self.sname, 'rb')

        firstprofile = first.read().split('\n\n')

        secondprofile = second.read().split('\n\n')

        idaapi.msg("Analysing profiles...\n")
        firstprof = self.kern.analyze_callgr_profile(firstprofile)

        secondprof = self.kern.analyze_callgr_profile(secondprofile)

        if not self.is_reanalyse:

            YN = idc.AskYN(
                0,
                'Do you want to make additional funcs, based on callgrind logs?\n(If func not already exist)'
            )

            if YN == 1:
                idaapi.msg("Tryind add funcs...\n")
                num = self.kern.make_funcs_from_profiles(firstprof, secondprof)
                idc.Warning("%d funcs was added" % num)

        actfuncs_dict = self.kern.color_profs(firstprof, secondprof, BLUE, ORG,
                                              GREEN)

        self.ColorFuncsView = FuncsColorChooser("Colored Funcs", actfuncs_dict,
                                                self.fname, self.sname)
        # self.ColorFuncsView.show()
        idaapi.msg("Done, enjoy work!\n")
        idaapi.msg(
            "\nHelp:\n - Click Functions window and Type Alt+1 to see actually executed funcs from profiles\n"
        )
        self.is_reanalyse = False
        return True
示例#3
0
def main():
    if _IN_IDA:
        # # get dyld_shared_cache path from IDA's openFile dialog
        print "[+] Please choose the original dyld_shared_cache_arm64"
        dsc_path = idc.AskFile(0, "*.*", "dyld shared cache file")
    else:
        dsc_path = sys.argv[1]

    if not dsc_path or not os.path.exists(dsc_path):
        raise RuntimeError("Couldn't find the dyld shared cache file..")

    print "[+] about to parse %s.." % (dsc_path)
    dsc_file = open(dsc_path, "rb")
    adrfind = AddrFinder(dsc_file, cache_symbols=False)
    map_shared_bridges(dsc_file, adrfind)
    if _IN_IDA:
        addresses = sorted(set(get_bad_addresses()))
    else:
        addresses = sorted(set(eval(open("addrs.txt", "rb").read())))

    segments, exports = get_segments_and_exports_for_addresses(
        addresses, adrfind)
    # segments = join_neighbors(segments, threshold=0x1000)
    if _IN_IDA:
        map_segments(segments, dsc_file)
        map_exports(exports)
        idaapi.analyze_area(idc.MinEA(), idc.MaxEA())
示例#4
0
    def activate(self, ctx):
        import json

        filepath = idc.AskFile(False, "*.zmu;*.overlay;*",
                               "Load Zelos Overlay...")
        if filepath is None:
            return
        f = open(filepath, "r")
        zelos_data = f.read()
        f.close()

        zelos_data = zelos_data[len("DISAS\n"):]
        zelos_dump = json.loads(zelos_data)

        # Apply the overlay data
        for comment in zelos_dump["comments"]:
            ea = comment["address"]
            try:
                comment_text = str(comment["text"])
            except UnicodeEncodeError:
                comment_text = ""
            color = comment.get("color", 0x73F0DF)

            # Set color of instruction line
            idaapi.set_item_color(ea, color)
            idaapi.set_cmt(ea, comment_text, False)

            # Set function name if not already changed
            idc.GetFunctionAttr(ea, idc.FUNCATTR_START)
            name = idc.GetFunctionName(ea)
            if len(name) > 0 and name.startswith("zmu_") is False:
                idc.MakeName(ea, "zmu_" + name)

        return 1
示例#5
0
def ida_main():
    import idc

    filepath = idc.AskFile(0, "*.map", "Load a Dolphin emulator symbol map")
    if filepath is None:
        return
    symbol_map = load_dolphin_map(filepath)

    for symbol in symbol_map:
        addr = int(symbol.vaddr, 16)
        size = int(symbol.size, 16)
        idc.MakeUnknown(addr, size, 0)
        if symbol.section in [".init", ".text"]:
            idc.MakeCode(addr)
            success = idc.MakeFunction(
                addr, idc.BADADDR if not size else (addr + size))
        else:
            success = idc.MakeData(addr, idc.FF_BYTE, size, 0)

        if not success:
            idc.Message("Can't apply properties for symbol:"
                        " {0.vaddr} - {0.name}\n".format(symbol))

        flags = idc.SN_NOCHECK | idc.SN_PUBLIC
        if symbol.name.startswith("zz_"):
            flags |= idc.SN_AUTO | idc.SN_WEAK
        else:
            flags |= idc.SN_NON_AUTO
        idc.MakeNameEx(addr, symbol.name, flags)
 def importb(self):
     #将文件中的内容导入到buffer中
     fileName = idc.AskFile(0, "*.*", 'Import File')
     try:
         self.buffer = open(fileName, 'rb').read()
     except:
         sys.stdout.write('ERROR:Cannot access file')
示例#7
0
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        store = idaapi.netnode(Config().idb_store, 0, True)
        maze = store.getblob(0, 'N')
        if maze is None:
            maze_file = idc.AskFile(0, '*.json', 'Select the Maze...')
            if maze_file:
                with open(maze_file, 'r') as fd:
                    ma_id = int(idc.GetInputFile().split('_')[1], 10)
                    blob = fd.read()
                    maze = json.loads(blob)
                    for i in range(len(maze["mem_areas"])):
                        if maze["mem_areas"][i]["id"] == ma_id:
                            del maze["mem_areas"][0:i]
                            del maze["mem_areas"][1:]
                            break
                    self.update(maze)

                    CallAsPushAnalysis.Analyze(self)
                    self.__mark_bbls()
                    self.__mark_calls()

                    blob = json.dumps(maze)
                    store.setblob(blob, 0, "N")
        else:
            self.update(json.loads(maze))

        self.__create_luts()
示例#8
0
文件: rizzo.py 项目: Eterna1/ida
def rizzo_produce(arg):
    fname = idc.AskFile(1, "*.riz", "Save signature file as")
    if fname:
        if '.' not in fname:
            fname += ".riz"
        RizzoBuild(fname)
    return None
示例#9
0
def main():
    info("Running pintool")
    
    # OPEN = 0, SAVE = 1
    #filename = idc.AskFile(0, "*", "Choose a file to run under pintool")     
    #arguments = idc.AskStr("", "Specify command line arguments for %s" % os.path.basename(filename))
 
    #info("Got filename %s" % filename)
    #info("Got arguments %s" % arguments)
        
    try:
        #tool = PinnaclePintool()
        trace_log = idc.AskFile(0, "*", "Choose a file to run under pintool")
        if not os.path.exists(trace_log):  
            tool.run(filename + arguments)
         
        tr = TraceReader(trace_log)
        
        m = BasicBlockMarker(tr.bbhit_trace)
        m.mark()
        
        m = TaintedMarker(tr.ins_trace)
        m.mark()

        m = AssertionMarker(tr.assertion_trace)
        m.mark()
        
    except InvalidTraceFileException, e:
        info("Could not find trace file")
        return -1
示例#10
0
    def activate(self, ctx):
        import json

        filepath = idc.AskFile(False, '*.zmu;*.overlay;*',
                               'Load Zemu Overlay...')
        if filepath is None:
            return
        f = open(filepath, 'r')
        zemu_data = f.read()
        f.close()

        zemu_data = zemu_data[len('DISAS\n'):]
        zemu_dump = json.loads(zemu_data)

        # Apply the overlay data
        for comment in zemu_dump['comments']:
            ea = comment['address']
            comment_text = str(comment['text'])
            color = comment.get('color', 0x73f0df)

            # Set color of instruction line
            idaapi.set_item_color(ea, color)
            idaapi.set_cmt(ea, comment_text, False)

            # Set function name if not already changed
            idc.GetFunctionAttr(ea, idc.FUNCATTR_START)
            name = idc.GetFunctionName(ea)
            if len(name) > 0 and name.startswith('zmu_') == False:
                idc.MakeName(ea, 'zmu_' + name)

        return 1
示例#11
0
    def saveReport(self):
        fileName = str(idaapi.get_root_filename() + "_" +
                       self.FunctionName[:15] + ".html")
        dir = idc.AskFile(1, fileName, "Save as")
        dir = dir[:-len(fileName)]

        if not os.path.exists(dir + str(idaapi.get_root_filename() + "_" +
                                        self.FunctionName[:15])):
            os.makedirs(dir + str(idaapi.get_root_filename() + "_" +
                                  self.FunctionName[:15]))
        dir = dir + str(idaapi.get_root_filename() + "_" +
                        self.FunctionName[:15]) + "\\"
        report = htmlReport()

        fileOutput = open(dir + fileName, "wb")
        fileOutput.write(
            report.generateReport(idaapi.get_root_filename(), self.CurrentMD5,
                                  self.FunctionName,
                                  self.generateStatisticsTable()))
        fileOutput.close()

        for graph in self.statsFigures.keys():
            self.statsFigures[graph].set_figheight(2.500)
            self.statsFigures[graph].set_figwidth(6.000)
            self.statsFigures[graph].set_dpi(10)
            self.statsFigures[graph].savefig(dir + graph + ".png")
    def OnPopupMenu(self, menu_id):
        if menu_id == self.menu_toggledata:
            self.showData = not self.showData
            self.refresh()

        elif menu_id == self.menu_toggleret:
            self.showRet = not self.showRet
            self.refresh()

        elif menu_id == self.menu_populatestrings:
            self.popStrings = not self.popStrings
            if self.popStrings:
                self.strBase = idc.AskLong(self.strBase,
                                           "Base displacement to use?")
            self.refresh()

        elif menu_id == self.menu_savetofile:
            fileName = idc.AskFile(1, "*.*", "Export ROP Disasembly view")
            if fileName and self.save_to_file(fileName):
                print "disasm saved to %s" % fileName

        else:
            return False

        return True
示例#13
0
    def run(self):
        try:
            logger.debug("Starting up")
            dbFile = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'shellcode_hashes', 'sc_hashes.db'))
            logger.debug('Trying default db path: %s', dbFile)
            if not os.path.exists(dbFile):
                if using_ida7api:
                    dbFile = idc.AskFile(0, "*.db", "Select shellcode hash database")
                else:
                    dbFile = idaapi.ask_file(False, "*.db", "Select shellcode hash database")

                if (dbFile is None) or (not os.path.isfile(dbFile)):
                    logger.debug("No file select. Stopping now")
                    return
            self.dbstore = DbStore(dbFile)
            logger.debug("Loaded db file: %s", dbFile)
            if QT_AVAILABLE:
                self.launchGuiInput()
            else:
                self.launchManualPrompts() 
            searcher = ShellcodeHashSearcher(self.dbstore, self.params)
            logger.debug('Starting to run the searcher now')
            searcher.run()
            logger.debug("Done")
        except RejectionException:
            logger.info('User canceled action')
        except Exception, err:
            logger.exception("Exception caught: %s", str(err))
示例#14
0
def main():
    disas_path = idc.AskFile(1, '*.disas', 'Save basic blocks')
    do_exit = False

    if not disas_path:
        basename = idc.GetInputFile()
        disas_path = '%s.disas' % basename
        idc.GenerateFile(idc.OFILE_ASM, '%s.asm' % basename, 0, idc.BADADDR, 0)
        idc.GenerateFile(idc.OFILE_LST, '%s.lst' % basename, 0, idc.BADADDR, 0)
        do_exit = True

    # Get basic blocks
    bbs = _get_basic_blocks()

    # Get the module's base address
    base_addr = idaapi.get_imagebase()

    # Get the module's end address
    segs = sorted(idautils.Segments())
    end_addr = idc.SegEnd(segs[-1])

    disas_info = {
        'bbs': bbs,
        'base_addr': base_addr,
        'end_addr': end_addr,
    }

    with open(disas_path, 'w') as disas_file:
        json.dump(disas_info, disas_file)

    if do_exit:
        idc.Exit(0)
示例#15
0
 def activate(self, ctx):
     fname = idc.AskFile(1, '*.riz', 'Save signature file as')
     if fname:
         if '.' not in fname:
             fname += ".riz"
         RizzoBuild(fname)
     return 0
示例#16
0
 def on_export(self):
     Warning("This export option generates an .ivz file that you have to distribute manually.\nIDASynergy won't automatically synchronize unless a local repository is synched\nto a versioning server and the 'IDASynergy SVN Commit' menu option is used.")
     exp_file = idc.AskFile(1, "*.ivz", "Exported data filename")
     print time.time()
     self.remove_hooks()
     self.data_io.export_to_file(exp_file)
     self.insert_hooks()
     return 1
 def start(self):
     self.setSafeGuard()
     if not os.path.isfile(self.modulePath):
         self.modulePath = idc.AskFile(0,"*.*","Please select the right Path of the module/executable loaded in IDA")
         idc.SetInputFilePath(self.modulePath)
     LoadDebugger("win32", 0) # load win32 as default
     if (StartDebugger(self.modulePath, self.moduleArgs, self.sourceDir) == -1):
         self.log(1, "Error! Failed to launch debugger!")
     GetDebuggerEvent(WFNE_ANY, -1) # handle first event
def prepare(metrics_used):
    fname = idc.AskFile(0, ".out", "Choose a trace file")
    if fname == None:
        print "You need to specify trace to get dynamic metrics"
        return 0
    print "Start trace analysis"

    metrics_dynamic = Metrics_dynamic()
    metrics_dynamic.get_dynamic_metrics(fname, metrics_used)
示例#19
0
def load_methods():
    sigfile = idc.AskFile(0, "*.json", "Select json signature file")
    log("loading signature file: %s", sigfile)

    with open(sigfile, 'r') as f:
        infos = json.load(f)

    log("loaded %d methods from JSON", len(infos))
    return infos
示例#20
0
def getInputFilepath():
    '''Returns None if the uesr cancels. Updates the filepath in the idb on success'''
    filePath = idc.GetInputFilePath()
    if not os.path.exists(filePath):
        print 'IDB input file not found. Prompting for new one: %s' % filePath
        filePath = idc.AskFile(False, '*.*', 'Enter path to idb input file')
        if filePath is not None:
            idc.SetInputFilePath(filePath)
    return filePath
示例#21
0
 def rizzo_produce(self, arg):
     fname = idc.AskFile(1,
                         idc.GetInputFile() + ".riz",
                         "Save signature file as")
     if fname:
         if '.' not in fname:
             fname += ".riz"
         RizzoBuild(fname)
     return None
示例#22
0
 def run(self, arg):
     if self.view:
         self.Close()
     fn = idc.AskFile(0, "*.asm", "Select ASM file to view")
     if not fn:
         return
     self.view = asmview_t()
     if not self.view.Create(fn):
         return
     self.view.Show()
示例#23
0
    def OneProfMakeFuncs(self):
        fname = idc.AskFile(0, '*.*', 'Select profile file, plz')
        prof = open(fname, 'rb')
        binprofile = prof.read().split('\n\n')

        binprof = self.kern.analyze_callgr_profile(binprofile)
        idaapi.msg("Tryind add funcs...\n")
        num = self.kern.make_funcs_from_prof(binprof)
        idc.Warning("%d funcs was added" % num)
        return True
示例#24
0
    def doImport(self, filename=None):
        self.initialize()

        if filename is None:
            f = idc.AskFile(0, "*.sqlite", "Select database to import")
        else:
            f = filename

        if f:
            self.openDatabase(f)
            self.searchAll()
示例#25
0
def main():


    filename = idc.AskFile( 0,
        '*.txt',
        'Select filename with intermodular calls dump')

    f = file(filename, 'rt')
    for line in f.readlines():
        process_line(line)
    f.close()
示例#26
0
def main():
    fnlistfile = idc.AskFile(0, '*.*', 'Choose file')
    if fnlistfile is None: return

    with open(fnlistfile, 'rU') as f:
        while True:
            fn = f.readline()
            if fn == '':
                break
            else:
                make_fn_non_library_fn(fn.strip())
示例#27
0
    def _addMazeLog(self):
        maze_file = idc.AskFile(0, '*.json', 'Select the Maze...')
        if maze_file is not None:
            with open(maze_file, 'r') as fd:
                maze = fd.read()
                self._store_maze_in_idb(maze)
                self.filter_qbox.clear()

                self.execution_tree.init_maze(json.loads(maze)[0])
                for tag in self.execution_tree.tags:
                    self.filter_qbox.addItem(tag)
def main(argv):
    filename = idc.AskFile(forsave=False,
                           mask='Text files (*.txt)|*.txt|All files (*.*)|*.*',
                           prompt='Choose an input file')
    if filename is not None:
        with open(filename, 'r') as file:
            info = crashinfo.parse_crashinfo(file)
            print('Call stack:')
            for address, module in info.get_call_stack():
                name = idc.GetFunctionName(address)
                if name:
                    print('  %x in %s!%s' % (address, module.filename, name))
示例#29
0
    def Run(self, fileName=''):
        # Ask the user for a file if needed
        if fileName == '' or fileName == None:
            fileName = idc.AskFile(0, "*.*", "Select a PT dump file...")

        # Run the engine and get the base start address:
        qwStartEa = self.ParseFileAndGetStartAddr(fileName)
        if (qwStartEa == 0):
            print "Error! The specified dump file is not valid!"
            return False
        #print "Obtained %s has start virtual address." % hex(qwStartEa)
        return self.StartPtAnalysis(qwStartEa)
示例#30
0
def main():
    f = open(
        idc.AskFile(0, '*.json',
                    'Where is the JSON report you want to load ?'), 'r')
    c = idc.AskStr('black', 'Which color do you want ?').lower()
    report = json.load(f)
    for i in report['basic_blocks_info']['list']:
        print '%x' % i['address'],
        try:
            color(i['address'], i['nbins'], c)
            print 'ok'
        except Exception, e:
            print 'fail: %s' % str(e)