Ejemplo n.º 1
0
def main():
    '''
    Main function that implements main algorithm
    
    '''
    # a file where some log will be created which says how many functions are discovered etc.
    logFile=raw_input("Enter the name of log file")
    # this is provided as an extra file which is a pickled file comtains a list of functions
    # that are found to be BOP. Its main purpose is: if you want to use these functions for some
    # other analysis, just load this file and viola!!!
    fileBOP=raw_input("Enter the file name (full path) to store (Pickled) BOP function's name: ")
    
    interestingFuncs={} # dictionary of interesting functions
    interestingFuncsLOC={} # dictionary of LOC in interesting functions

    binNaviProxy = StandAlone.getPluginInterface()
    
    ################## place to set database connectivity parameter ######### 
    binNaviProxy.databaseManager.addDatabase("","org.postgresql.Driver","localhost","DataBase_name","user","password",False,False)
    ########################################################################
    db=binNaviProxy.databaseManager.databases[0]
    db.connect()
    db.load()
    mods=db.getModules()

    ### initiate dialogBox to setect the module that should be used.

    ######################################################


    frame = JFrame('BinNavi Module Selector',layout=BorderLayout(),
                defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
                size = (500, 500)
            )
    frame2 = JFrame('Function Selector',layout=BorderLayout(),
                defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
                size = (30, 30)
            )


    #convert the module list into the string to be used in the TextBox.
    ## This gives a very ugly box to select the required function (yes, I am bit lazy to learn Java Swing!!). 
    textTemp = map((lambda x,y:"[%d]%s"%(x,y)),range(len(mods)),mods)
    textStr=''.join(textTemp)

    tx=JTextArea(textStr)
    tx.setLineWrap(True);
    tx.setWrapStyleWord(True);
    frame.add(tx,BorderLayout.PAGE_START)
    frame.visible = True
    modInd = JOptionPane.showInputDialog(frame2, "Enter the index of the chosen module",
             "Module selector");

    #Open the module returned by the index
    bfname=mods[int(modInd)] # this modules correxponds to the chosen module
    bfname.load()
    funcViews=bfname.views

    frame2.setVisible(False)
    dispose(frame2)

 ######################################################
    analyzedFunctions = 0
    totalDiscoveredLoops=0
    totalInterestingLoops=0
    time.clock()
    for funcInd in range(1,len(funcViews)):
        
        BBnum=funcViews[funcInd].getNodeCount()
        
        if BBnum <4:
            print "skipped"
            continue #do not analyse function if num of BB less than 4
        
        print 'analyzing %s'%funcViews[funcInd].getName()

        dominatingSets={}#dictionary to keep dominating nodes of a node

        bffunc=bfname.views[int(funcInd)] #this is the view of the buildfname function
        bffunc.load()
        try:
            bfReil=bffunc.getReilCode() # this is the REIL code of the function
        except:
            print "error in getReilCode()"
            bffunc.close()
            gc.collect()
            continue

        bfReilGraph=bfReil.getGraph()
        try:
            #dominatorTree = GraphAlgorithms.getDominatorTree(bfReilGraph, findRoot(bfReilGraph.getNodes())) #only for BinNavi v 3.0
            dominatorTree = GraphAlgorithms.getDominatorTree(bfReilGraph, findRoot(bfReilGraph.getNodes()),None)
        except:
            print "dominator tree problem.. continue with the next function"
            bffunc.close()
            gc.collect()
            continue

        fillDominatingSets(dominatorTree.getRootNode(), dominatingSets, None)

        # let us find loops in this function
        finalLoops=findLoops(bfReilGraph,dominatingSets)
        if finalLoops ==None:
            bffunc.close()
            gc.collect()
            continue
        analyzedFunctions = analyzedFunctions +1
        totalDiscoveredLoops = totalDiscoveredLoops + len(finalLoops)
        # check if the loops are potential candidates for being interesting.
        # this is done by checking if there are atleast 2 STM statements in each loop.
        #print "privious length", len(finalLoops)
        if len(finalLoops)== 0:
            bffunc.close()
            gc.collect()
            continue
        for lp in finalLoops.keys():
            countSTM=0
            for lpn in finalLoops[lp]:
                inst=lpn.getInstructions()
                for i in inst:

                    if i.getMnemonic() == 'stm':
                        countSTM=countSTM+1
                if countSTM >0:
                    break


            if countSTM <= 0:
                del finalLoops[lp]

        #print "latest length", len(finalLoops)

        if len(finalLoops)== 0:
            bffunc.close()
            gc.collect()
            continue


        instGraph = InstructionGraph.create(bfReilGraph)
        
        interestingFuncs[funcViews[funcInd].getName()]=[]
        
        for k in finalLoops.keys():
            print 'analysing loop at %s-%s'%(k[0],k[1])
            if k[0] == k[1]:
                print "skipping this loop as src= dest"
                continue
            #check to skip very big loops i.e. loops having 100 BB
            if len(finalLoops[k]) > 100:
                print "very big loop, skipping!"
                continue
            if isInteresting(finalLoops[k],instGraph) ==True:
                totalInterestingLoops = totalInterestingLoops + 1
                interestingFuncs[funcViews[funcInd].getName()].append(k)
                interestingFuncsLOC[str(funcViews[funcInd].getName())]=sum([len(x.getInstructions()) for x in (getCodeNodes(bffunc.getGraph()))])
                print 'loop at %s IS interesting.'%k[0]
            else:
                print 'loop at %s is NOT interesting.'%k[0]

        #finally close the view of the function
        bffunc.close()
        gc.collect()
        #print bffunc.isLoaded()
        #junky=raw_input("function closed. enter any charater")
    totalTime=time.clock()

# remove the function entries that do not have any interesting loops
    for ky in interestingFuncs.keys():
        if len(interestingFuncs[ky]) == 0:
            del interestingFuncs[ky]

    # write the results in a file
    #


    outFile=open(logFile,'w')
    outFile.write('########## Global Results ###########\n')
    outFile.write('Total Functions in the module: ')
    outFile.write(str(len(funcViews)))
    outFile.write('\nTotal Analyzed Functions in the module: ')
    outFile.write(str(analyzedFunctions))
    outFile.write('\nTotal Interesting Functions in the module: ')
    outFile.write(str(len(interestingFuncs)))
    outFile.write('\nTotal loops discovered in the module: ')
    outFile.write(str(totalDiscoveredLoops))
    outFile.write('\nTotal INTERESTING loops discovered in the module: ')
    outFile.write(str(totalInterestingLoops))
    outFile.write('\nTotal Time: ')
    outFile.write(str(totalTime))
    outFile.write('\n')
    outFile.write('########## Global Results ###########\n')
    for k in interestingFuncs.keys():
        outFile.write("%s: %s: %d"%(str(k), "LOC", interestingFuncsLOC[k]))
        outFile.write('\n')
        for l in interestingFuncs[k]:
            outFile.write('\t')
            outFile.write(str(l))
            outFile.write('\n')
    outFile.close()
    # before we save these BOPS, we include few widely known BOPs which are given int eh following list

    knownBOPs = ['strcpy', 'strncpy', 'memcpy','wcscpy']
    for fn in knownBOPs:
        interestingFuncs[fn] = []


    # save the function name as pickled objects
    fileBOPFd=open(fileBOP+'.pkl', 'w')
    pickle.dump(interestingFuncs.keys(), fileBOPFd)
    fileBOPFd.close()
    print "[*] Pickled in the file %s"%fileBOP+'.pkl'
    print "Done! Closing the module selector window"
    frame.setVisible(False)
    dispose(frame)
Ejemplo n.º 2
0
def main():
	
	binNaviProxy = StandAlone.getPluginInterface()
	binNaviProxy.databaseManager.addDatabase("","com.mysql.jdbc.Driver","localhost","BINNAVI1","binnavi","binnavi",False,False)
	db=binNaviProxy.databaseManager.databases[0]
	db.connect()
	db.load()
	mods=db.getModules()
	
	### initiate dialogBox to setect the module that should be used.
	
	######################################################
	
	
	frame = JFrame('BinNavi Module Selector',layout=BorderLayout(),		
				defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
				size = (1500, 800)
			)
	frame2 = JFrame('Function Selector',layout=BorderLayout(),		
				defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
				size = (30, 30)
			)
			
	frame2.setFocusableWindowState(False)
	frame2.setFocusable(False)
	frame2.setAlwaysOnTop(False)
	#convert the module list into the string to be used in the TextBox.
	textTemp = map((lambda x,y:"[%d]%s"%(x,y)),range(len(mods)),mods) 
	textStr=''.join(textTemp)

	tx=JTextArea(textStr)
	tx.setLineWrap(True);
	tx.setWrapStyleWord(True);
	frame.add(tx,BorderLayout.PAGE_START)
	frame.visible = True
	modInd = JOptionPane.showInputDialog(frame2, "Enter the index of the chosen module", 
			 "Module selector");
	
	#Open the module returned by the index 
	bfname=mods[int(modInd)] # this modules correxponds to the chosen module
	bfname.load()
	funcViews=bfname.views
	#textTemp2 = ["[%d]%s"%(i,j) for i in range(len(funcViews)) for j in funcViews]
	textTemp2=map((lambda x,y:"[%d]%s"%(x,y.toString()[5:18])),range(len(funcViews)),funcViews)
	textStr1=''.join(textTemp2)
	## remove the older text from the frame view
	frame.remove(tx)
	frame.update(frame.getGraphics())
	frame.visible = False
	## create a new textArea with the string made from all the functions' name
	txStr=JTextArea(textStr1)
	#tx.setsrcollOffset(20)
	txStr.setLineWrap(True);
	txStr.setWrapStyleWord(True);
	frame.add(txStr,BorderLayout.PAGE_START)
	frame.update(frame.getGraphics())
	frame.visible = True
	funcInd = JOptionPane.showInputDialog(frame2, "Enter the index of the function", 
			 "Function selector");
   
 ######################################################
	
	
	bffunc=bfname.views[int(funcInd)] #this is the view of the buildfname function
	bffunc.load()
	
	frame2.setVisible(False)
	dispose(frame2)
	
	bfReil=bffunc.getReilCode() # this is the REIL code of the function
	bfReilGraph=bfReil.getGraph()
			
	instGraph = InstructionGraph.create(bfReilGraph)
	time.clock()
	results=doAnalysis(instGraph)
	totalTime=time.clock()
	#print "resultsLen", len([r for r in results])
			
	print "**** printing results *******\n"
	print "Total time:", totalTime, '\n'
	numNode=0
	for n in instGraph:
		numNode+=numNode
		
		nIn=list(results.getState(n).inVal)
		nIn.sort(key=itemgetter(0))
		nOut=list(results.getState(n).out)
		nOut.sort(key=itemgetter(0))
		print '@@ ',n.getInstruction(),'\n'
		print '\t In', nIn, '\n'
		print '\t OUT', nOut, '\n'
		print '\t memory: ',results.getState(n).memoryWritten, '\n'
	print "++++ Total instructions: %d +++++\n"%numNode		 
	#finally close the view of the function
	bffunc.close()
	#print bffunc.isLoaded()
	#junky=raw_input("function closed. enter any charater")
	


	print "Done! Closing the module selector window"
	frame.setVisible(False)
	dispose(frame)
Ejemplo n.º 3
0
	txStr.setLineWrap(True);
	txStr.setWrapStyleWord(True);
	frame.add(txStr,BorderLayout.PAGE_START)
	frame.update(frame.getGraphics())
	frame.visible = True
	funcInd = JOptionPane.showInputDialog(frame2, "Enter the index of the function", 
			 "Function selector");
   
 ######################################################
	
	
	bffunc=bfname.views[int(funcInd)] #this is the view of the buildfname function
	bffunc.load()
	
	frame2.setVisible(False)
	dispose(frame2)
	
	bfReil=bffunc.getReilCode() # this is the REIL code of the function
	bfReilGraph=bfReil.getGraph()
			
	instGraph = InstructionGraph.create(bfReilGraph)
	time.clock()
	results=doAnalysis(instGraph)
	totalTime=time.clock()
	#print "resultsLen", len([r for r in results])
			
	print "**** printing results *******\n"
	print "Total time:", totalTime, '\n'
	numNode=0
	for n in instGraph:
		numNode+=numNode