Example #1
0
 def _print_ast(self, page, indice):
     ret = ''
     i = 0
     #print prettyText("[*] Start for %s" % str(indice),'red')
     if page != None:
         if isinstance(page,list):
             #print prettyText("[**] List %s" % str(page),'yellow')
             for l in page:
                 cur = list(indice)
                 cur.append(i)
                 i = i + 1
                 ret = ret + self._print_ast(l, cur)
         elif isinstance(page, phply.phpast.Node):
             #print prettyText("[**]\t Node %s" % str(page), 'blue')
             ret = prettyText(str(indice),'red') + '\t' * len(indice) + prettyText(str(type(page)),'green') + '\n'
             j = 0
             for k in page.__dict__.keys():
                 if k != 'lineno':
                     l = page.__dict__[k]
                     cur = list(indice)
                     cur.append(j)
                     j = j + 1
                     #print prettyText("[**]\t Node cur : %s || j : %s" % (str(cur), str(j-1)), ['blue', 'bold'])
                     ret = ret + self._print_ast(l,cur)
         else:
             #print prettyText("[**] Other %s" % str(page), 'white')
             ret = prettyText(str(indice),'red') + '\t' * len(indice) + prettyText(str(type(page)),'blue') + prettyText(':','cyan') + str(page) + '\n'
     return ret
Example #2
0
def parseFound(found, params):
    output = ''
    for k in found.keys():
        for l in found[k]:
            output = output + prettyText(k,'magenta') + prettyText(':','cyan') + prettyText(l.lineno, 'green') + prettyText(': ','cyan') + prettyText(l, 'white') + prettyText(str(params),'red') + '\n'

    return output
Example #3
0
def parseFound(found, params):
    output = ''
    for k in found.keys():
        for l in found[k]:
            output = output + prettyText(k,'magenta') + prettyText(':','cyan') + prettyText(l.lineno, 'green') + prettyText(': ','cyan') + prettyText(l, 'white') + prettyText(str(params),'red') + '\n'

    return output
Example #4
0
def getSolution(reprs,offset,his):

    debugListHex(reprs,"reprs:",2)
    debugListHex(offset,"offset:",2)
    sol = dict()
    sol2 = dict()
    for rg in range(len(reprs)):
        r = reprs[rg]
        of = offset[rg]
        #print prettyText("searching for 0x%02x <= 0x%02x" % (r,of),"red")
        tPath = Tree(name=r)
        tPath.add_features(value=r)
        for h in his[:-1]:
            #print prettyText("in H","red")
            for leaf in tPath.get_leaves():
                r = leaf.value
                #print prettyText("leaves: %s" % str(tPath.get_leaves()),"cyan")
                for line in h.history:
                    res, alph, past, method = line[0], line[1], line[2], line[3].func_name
                    #debug("0x%02x = 0x%02x %s. (0x%02x)" % (res,alph,method,past),2)
                    #print prettyText("comparing res=0x%02x ?= r=0x%02x" % (res,r),"yellow")
                    if res == r:
                        n = leaf.add_child(name=alph)
                        n.add_features(function=method,value=past)
        #print tPath.get_ascii(attributes=['name','function','value'])
        lf = tPath.get_leaves()[0]
        anc = lf.get_ancestors()[:-1]
        llf = [lf,]
        llf.extend(anc)
        vls = [c.name for c in llf]
        sol[rg] = llf
    for i in sol:
        vls = [(c.name, c.function) for c in sol[i]]
        sol2["method"] = []
        for j in range(len(vls)):
            sol2["method"].append(sol[i][0].function)
            if sol2.has_key(j):
                sol2[j].append(vls[j][0])
            else:
                sol2[j] = []
                sol2[j].append(vls[j][0])
    print prettyText("Solution:","red")
    info("PUSH\t\t0x%02x%02x%02x%02x" % (offset[0],offset[1],offset[2],offset[3]))

    test = []
    test.append(offset[0] * 0x01000000 + offset[1] * 0x00010000 + offset[2] * 0x00000100 + offset[3] * 0x00000001)

    for m in range(len(sol2["method"])):


        test.append(sol2[m][0] * 0x01000000 + sol2[m][1] * 0x00010000 + sol2[m][2] * 0x00000100 + sol2[m][3] * 0x00000001)

        info("%s\t\t\t0x%02x%02x%02x%02x" % (sol2["method"][m],sol2[m][0],sol2[m][1],sol2[m][2],sol2[m][3]))


    info("RESULT\t\t0x%08x" % (reprs[0] * 0x01000000 + reprs[1] * 0x00010000 + reprs[2] * 0x00000100 + reprs[3] * 0x00000001))
    testResult(test,(reprs[0] * 0x01000000 + reprs[1] * 0x00010000 + reprs[2] * 0x00000100 + reprs[3] * 0x00000001))
Example #5
0
 def printCode(self,printlineno=True):
     if printlineno:
         codes = self.file_content.split('\n')
         lineno = 1
         for l in codes:
             print prettyText(lineno,'green') + prettyText(': ','cyan') + prettyText(l,'white')
             lineno += 1
     else:
         print self.file_content
Example #6
0
def analyse(path):
    print prettyText("[*] Parsing Project at %s ..." % path,'blue')
    p = parser.PHPProject(path)
    print prettyText("[*] Parsing Completed !",'blue')

    print prettyText("[*] Searching for dangerous methods",'blue')
    for category in vulndb.A_F_ALL.keys():
        print prettyText("[**] Category: %s" % category,['yellow','bold'])
        for method in vulndb.A_F_ALL[category].keys():
            print prettyText("[***] Method: %s" % str(method),['yellow'])
            found = search(p,functionClassFilter,method)
            print parseFound(found,vulndb.A_F_ALL[category][method])
Example #7
0
def analyse(path):
    print prettyText("[*] Parsing Project at %s ..." % path, 'blue')
    p = parser.PHPProject(path)
    print prettyText("[*] Parsing Completed !", 'blue')

    print prettyText("[*] Searching for dangerous methods", 'blue')
    for category in vulndb.A_F_ALL.keys():
        print prettyText("[**] Category: %s" % category, ['yellow', 'bold'])
        for method in vulndb.A_F_ALL[category].keys():
            print prettyText("[***] Method: %s" % str(method), ['yellow'])
            found = search(p, functionClassFilter, method)
            print parseFound(found, vulndb.A_F_ALL[category][method])
Example #8
0
    def addAssignment(self,blob):
        #print prettyText("[GTST] Assign: '%s' = '%s'" % (str(blob.node), str(blob.expr)),'blue')
        nodes = core.search.search(blob.node,core.filters.classFilter,vulndb.T_VARS)
        exprs = core.search.search(blob.expr,core.filters.classFilter,vulndb.T_VARS)

        #TODO: still need to implement function assignment
        #functions = core.search.search(blob.expr,core.filters.classFilter,phply.phpast.FunctionCall)
        #print prettyText("==+==",'red')
        #print "Nodes: %s" % str(nodes)
        #print "Exprs: %s" % str(exprs)

        if nodes != None and exprs != None:
            for v in nodes:
                for e in exprs:
                    try:
                        #if v in symbol table, else do nothing
                        if self.inSymbolTable(v):
                            v2 = self.inSymbolTable(v)
                            #if e in symbol table, propagate tain
                            if self.inSymbolTable(e):
                                e2 = self.inSymbolTable(e)
                                #propagate direct taint
                                self.symbolTable[v2] += self.symbolTable[e2]
                                #propagate taint for elements of array
                                if isinstance(v, phply.phpast.ArrayOffset):
                                    if self.inSymbolTable(v.node):
                                        v3 = self.inSymbolTable(v.node)
                                        self.symbolTable[v3] += self.symbolTable[v2]

                            elif isinstance(e, phply.phpast.ArrayOffset):
                                if self.inSymbolTable(e.node):
                                    e2 = self.inSymbolTable(e.node)
                                    self.symbolTable[v2] += self.symbolTable[e2]
                                    if isinstance(v, phply.phpast.ArrayOffset):
                                        if self.inSymbolTable(v.node):
                                            v3 = self.inSymbolTable(v.node)
                                            self.symbolTable[v3] += self.symbolTable[v2]

                            else:
                                
                                print prettyText("Case 3", 'red')
                                print self
                            
                    except KeyError, e:
                        ###TODO correct this !!!
                        #print "[GTST] v: %s |||| v.node: %s" % (str(v),str(v.node))
                        print prettyText("[-] Key Error (Unexpected error, Bug) :%s" % str(e),['red','bold'])
Example #9
0
 def __str__(self):
     a = ''
     for v in self.symbolTable:
         
         if self.symbolTable[v] == 0:
             hilight_color = ['red']
         else:
             hilight_color = ['red', 'bold']
         
         #variables
         if isinstance(v, phply.phpast.Variable):
             try:
                 name = v.name
                 a += prettyText("[*] " + str(name) + " (Variable): ",['cyan'])+prettyText(str(self.symbolTable[v]) + "\n",hilight_color)
             except AttributeError:
                 #weir variables
                 name = v
                 a += prettyText("[*] " + str(name) ,['cyan']) + prettyText(" (Variable_complex): ",['yellow'])+prettyText(str(self.symbolTable[v]) + "\n",hilight_color)
         
         #arrays
         elif isinstance(v, phply.phpast.ArrayOffset):
             try:
                 name = v.node.name
                 a += prettyText("[*] " + str(name) + "[" + str(v.expr) + "] (ArrayOffset): ",['cyan','bold'])+prettyText(str(self.symbolTable[v]) + "\n",hilight_color)
             except AttributeError:
                 #complicated arrays
                 name = v
                 a += prettyText("[*] " + str(name),['cyan','bold']) + prettyText(" (ArrayOffset_Complex): ",['yellow','bold']) + prettyText(str(self.symbolTable[v]) + "\n",hilight_color)
     return a
Example #10
0
def searchMethod(path,method):
    print prettyText("[*] Parsing Project at %s ..." % path,'blue')
    p = parser.PHPProject(path)
    print prettyText("[*] Parsing Completed !",'blue')
    print prettyText("[***] Method: %s" % str(method),['yellow'])
    found = search(p,functionClassFilter,method)
    print parseFound(found,"Custom")
Example #11
0
def searchMethod(path, method):
    print prettyText("[*] Parsing Project at %s ..." % path, 'blue')
    p = parser.PHPProject(path)
    print prettyText("[*] Parsing Completed !", 'blue')
    print prettyText("[***] Method: %s" % str(method), ['yellow'])
    found = search(p, functionClassFilter, method)
    print parseFound(found, "Custom")
def analyse(path, method):
    print prettyText("[*] Parsing Project at %s ..." % path, 'blue')
    p = parser.PHPProject(path)
    print prettyText("[*] Parsing Completed !", 'blue')

    print prettyText("[*] Searching for calls to %s" % method, 'blue')
    found = search(p, functionMethodFilter, method)
    print parseFound(found)
Example #13
0
 def __init__(self,file_name):
     self.file_name = file_name
     try:
         o = open(file_name,'r')
         self.file_content = o.read()
         #o.close()
         try:
             lexer = phplex.lexer.clone()
             self.parsed_content = parser.parse(self.file_content, lexer=lexer)
             resolve_magic_constants(self.parsed_content)
             print prettyText("[+] SUCCESS parsing %s" % self.file_name,'green')
         except Exception, err:
             print prettyText("[-] ERROR parsing %s (%s)" % (self.file_name, str(err)),'red')
             self.parsed_content = []
     except Exception, err:
         print prettyText("[-] ERROR openning file: %s (%s)" % (self.file_name, str(err)),'yellow')
def debug(description, level=1):
    if debugMode and level >= debugLevel:
        print prettyText("[D] %s" % description, "green")
def info(description):
    print prettyText("[*] %s" % description, "blue")
def usage():

    print prettyText(
        "%s --alphabet <alphabet_word_file> --word <word_hex> --list <function_list>"
        % sys.argv[0], "green")
    print prettyText("--alphabet, -a : TODO", "green")
    print prettyText("--word, -w : TODO", "green")
    print prettyText("--list, -l : TODO", "green")
    print prettyText("--offset, -o : TODO", "green")
    print prettyText("--mutation, -m : TODO", "green")
    print prettyText("--help, -h : this help", "green")
    print prettyText(
        "example: %s --alphabet alphabet.txt --word 12131415 --list add,sub" %
        sys.argv[0], "green")
def debugListHex(pos, description, level=1):
    if debugMode and level >= debugLevel:
        print prettyText(
            "[D] %s %s" % (description, str([hex(c) for c in pos])), "green")
Example #18
0
def resolveInclude(project, page):
    """
    This function returns all pages that are included in page, search is done in project
    """
    #extract include and require statements
    listInc = core.search.search(page, core.filters.classFilter,
                                 [phply.phpast.Include, phply.phpast.Require])

    currentPageName = page.file_name.replace(project.folder_name, '')
    currentDirName = os.path.dirname(currentPageName)

    # return page list
    incPageList = []

    for blob in listInc:
        fileName = blob.expr

        if type(fileName) is str:

            if fileName.startswith('.'):
                fileName = fileName[1:]

            if not fileName.startswith('/'):
                fileName = '/' + fileName

            realFileName = os.path.join(currentDirName,
                                        fileName.split('/')[-1])

            if realFileName in project.pages.keys():
                print prettyText(
                    "[+] Found %s (%s)" % (fileName, realFileName), 'green')
                incPageList.append(project.pages[realFileName])
            elif fileName in project.pages.keys():
                print prettyText(
                    "[+] Found II %s (%s)" % (fileName, realFileName),
                    ['green', 'bold'])
                incPageList.append(project.pages[fileName])
            else:
                '''
                #searching for filename only, might return false positives
                
                lstSimilars = utils.mostSimilar(fileName, project.pages.keys())
                found = False
                
                for l in lstSimilars:
                    print "[***] FOUND %s === %s (%s)" % (fileName, l, currentDirName)
                    incPageList.append(project.pages[l])
                    found = True
                
                if not found:
                    print prettyText("[-] Not found %s (%s)" % (fileName, currentDirName), 'red')
                '''
                print prettyText(
                    "[-] Not found %s (%s)" % (fileName, realFileName), 'red')
        else:

            #incStrs = core.search.search(fileName, core.filters.classFilter, str)

            print prettyText(
                "[-] Resolving this Include is not implemented yet !",
                'yellow')
            print prettyText("[-] Blob: ", 'yellow') + prettyText(
                "%s" % str(blob), 'blue')
            #print prettyText("[-] str: ", 'yellow') + prettyText("%s" % str(incStrs), 'blue')

    return incPageList
    except:
        error("ete2 not installed")
        error(
            "try: easy_install -U ete2 or apt-get install python-ete2 to install ete2"
        )
        exit(1)

    debug("Parsing options ...")

    try:
        opts, args = getopt.getopt(sys.argv[1:], "ha:w:l:d:o:m:", [
            "help", "alphabet=", "word=", "list=", "debug=", "offset=",
            "mutation="
        ])
    except getopt.GetoptError, err:
        print prettyText(str(err), "red")
        sys.exit(2)

    initialAlphabet = []
    word = []  #word to search ['\x12','\x13','\x14','\x15']
    funcList = []
    offset = [0x00, 0x00, 0x00, 0x00]
    mutationLimit = 0
    representation = []  #list of word representation to search for
    debug(opts)

    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-a", "--alphabet"):
Example #20
0
def analyse(path):
    print prettyText("[*] Parsing Project at %s ..." % path,'blue')
    p = parser.PHPProject(path)
    print prettyText("[*] Parsing Completed !",'blue')

    '''
    print prettyText("[*] Searching for dangerous methods",'blue')
    for category in vulndb.A_F_ALL.keys():
        print prettyText("[**] Category: %s" % category,['yellow','bold'])
        for method in vulndb.A_F_ALL[category].keys():
            print prettyText("[***] Method: %s" % str(method),['yellow'])
            found = search(p,functionClassFilter,method)
            print parseFound(found,vulndb.A_F_ALL[category][method])
    '''    
    print prettyText("[*] Searching for dangerous methods inheritence",'blue')
    files = search(p,classFilter, phply.phpast.Function) 
    for name in files:
        print prettyText('[*] File: %s' % name,['yellow','bold'])
        functions = files[name]
        #print functions
        for l in functions:
            paramsList = search(l,classFilter, phply.phpast.FormalParameter)
            functionInputParams = dict()
            for p in paramsList:
                functionInputParams[p] = "ANY"
                
            #print functionInputParams
            tst = generateTST(l,functionInputParams)
            #print tst
            
            #search a method and propagate taint
            for kcat in vulndb.A_F_ALL.keys():
                cat = vulndb.A_F_ALL[kcat]
                #print prettyText('[*] Category: %s' % kcat,'red')
                for e in cat:
                    #print prettyText('[*] Method: %s' % str(e),'blue')
                    functions = search(l, functionFilter, e)
                    #print '-'*5
                    for f in functions:
                        for pos in cat[e]:
                            try:
                                #print prettyText('[*] FOUND : ' + str(f.params[pos].node) + ':' + str(tst.getTaint(f.params[pos].node)), 'green')
                                if tst.getTaint(f.params[pos].node) > 0:
                                    print '-'*5
                                    print prettyText('[*] Category: %s' % kcat,'red')
                                    print prettyText('[*] Method: %s' % str(e),'blue')
                                    print prettyText("[+] FOUND: %s" % str(l.name), 'green')
                                    print '-'*5
                            except IndexError, AttributeError:
                                print prettyText('[!] ERROR: %s' % str(f), 'red')
Example #21
0
    found = search(p, functionClassFilter, method)
    print parseFound(found, "Custom")


def parseFound(found, params):
    output = ''
    for k in found.keys():
        for l in found[k]:
            output = output + prettyText(k, 'magenta') + prettyText(
                ':', 'cyan') + prettyText(l.lineno, 'green') + prettyText(
                    ': ', 'cyan') + prettyText(l, 'white') + prettyText(
                        str(params), 'red') + '\n'

    return output


def usage():
    u = "%s <PHP_Project_Path>" % sys.argv[0]
    u += "<PHP_Project_Path> <Method_Name>"
    return u


if __name__ == '__main__':
    if len(sys.argv) < 3:
        print prettyText(usage(), 'blue')
    else:
        #analyse(sys.argv[1])
        project = sys.argv[1]
        method = sys.argv[2]
        searchMethod(project, method)
Example #22
0
    p = parser.PHPProject(path)
    print prettyText("[*] Parsing Completed !",'blue')
    print prettyText("[***] Method: %s" % str(method),['yellow'])
    found = search(p,functionClassFilter,method)
    print parseFound(found,"Custom")


def parseFound(found, params):
    output = ''
    for k in found.keys():
        for l in found[k]:
            output = output + prettyText(k,'magenta') + prettyText(':','cyan') + prettyText(l.lineno, 'green') + prettyText(': ','cyan') + prettyText(l, 'white') + prettyText(str(params),'red') + '\n'

    return output


def usage():
    u =  "%s <PHP_Project_Path>" % sys.argv[0]
    u += "<PHP_Project_Path> <Method_Name>"
    return u


if __name__ == '__main__':
    if len(sys.argv) < 3:
        print prettyText(usage(),'blue')
    else:
        #analyse(sys.argv[1])
        project = sys.argv[1]
        method = sys.argv[2]
        searchMethod(project, method)
Example #23
0
def analyse(path):
    print prettyText("[*] Parsing Project at %s ..." % path, 'blue')
    p = parser.PHPProject(path)
    print prettyText("[*] Parsing Completed !", 'blue')
    '''
    print prettyText("[*] Searching for dangerous methods",'blue')
    for category in vulndb.A_F_ALL.keys():
        print prettyText("[**] Category: %s" % category,['yellow','bold'])
        for method in vulndb.A_F_ALL[category].keys():
            print prettyText("[***] Method: %s" % str(method),['yellow'])
            found = search(p,functionClassFilter,method)
            print parseFound(found,vulndb.A_F_ALL[category][method])
    '''
    print prettyText("[*] Searching for dangerous methods inheritence", 'blue')
    files = search(p, classFilter, phply.phpast.Function)
    for name in files:
        print prettyText('[*] File: %s' % name, ['yellow', 'bold'])
        functions = files[name]
        #print functions
        for l in functions:
            paramsList = search(l, classFilter, phply.phpast.FormalParameter)
            functionInputParams = dict()
            for p in paramsList:
                functionInputParams[p] = "ANY"

            #print functionInputParams
            tst = generateTST(l, functionInputParams)
            #print tst

            #search a method and propagate taint
            for kcat in vulndb.A_F_ALL.keys():
                cat = vulndb.A_F_ALL[kcat]
                #print prettyText('[*] Category: %s' % kcat,'red')
                for e in cat:
                    #print prettyText('[*] Method: %s' % str(e),'blue')
                    functions = search(l, functionFilter, e)
                    #print '-'*5
                    for f in functions:
                        for pos in cat[e]:
                            try:
                                #print prettyText('[*] FOUND : ' + str(f.params[pos].node) + ':' + str(tst.getTaint(f.params[pos].node)), 'green')
                                if tst.getTaint(f.params[pos].node) > 0:
                                    print '-' * 5
                                    print prettyText('[*] Category: %s' % kcat,
                                                     'red')
                                    print prettyText('[*] Method: %s' % str(e),
                                                     'blue')
                                    print prettyText(
                                        "[+] FOUND: %s" % str(l.name), 'green')
                                    print '-' * 5
                            except IndexError, AttributeError:
                                print prettyText('[!] ERROR: %s' % str(f),
                                                 'red')
def error(description):
    print prettyText("[-] %s" % description, "red")
Example #25
0
def resolveInclude(project,page):
    """
    This function returns all pages that are included in page, search is done in project
    """
    #extract include and require statements
    listInc = core.search.search(page,core.filters.classFilter,[phply.phpast.Include,phply.phpast.Require])

    currentPageName = page.file_name.replace(project.folder_name,'')
    currentDirName = os.path.dirname(currentPageName)

    # return page list
    incPageList = []

    for blob in listInc:
        fileName = blob.expr

        if type(fileName) is str:
            
            if fileName.startswith('.'):
                fileName = fileName[1:]
    
            if not fileName.startswith('/'):
                fileName = '/' + fileName
             
            realFileName = os.path.join( currentDirName, fileName.split('/')[-1])
            
            if realFileName in project.pages.keys():
                print prettyText("[+] Found %s (%s)" % (fileName, realFileName), 'green')
                incPageList.append(project.pages[realFileName])
            elif fileName in project.pages.keys():
                print prettyText("[+] Found II %s (%s)" % (fileName, realFileName), ['green','bold'])
                incPageList.append(project.pages[fileName])
            else:
                '''
                #searching for filename only, might return false positives
                
                lstSimilars = utils.mostSimilar(fileName, project.pages.keys())
                found = False
                
                for l in lstSimilars:
                    print "[***] FOUND %s === %s (%s)" % (fileName, l, currentDirName)
                    incPageList.append(project.pages[l])
                    found = True
                
                if not found:
                    print prettyText("[-] Not found %s (%s)" % (fileName, currentDirName), 'red')
                '''
                print prettyText("[-] Not found %s (%s)" % (fileName, realFileName), 'red')
        else:
            
            #incStrs = core.search.search(fileName, core.filters.classFilter, str)
            
            print prettyText("[-] Resolving this Include is not implemented yet !", 'yellow')
            print prettyText("[-] Blob: ", 'yellow') + prettyText("%s" % str(blob), 'blue')
            #print prettyText("[-] str: ", 'yellow') + prettyText("%s" % str(incStrs), 'blue')
            
    return incPageList
Example #26
0
def usage():

    print prettyText("%s --alphabet <alphabet_word_file> --word <word_hex> --list <function_list>" % sys.argv[0],"green")
    print prettyText("--alphabet : TODO","green")
    print prettyText("--word : TODO","green")
    print prettyText("--list : TODO","green")
    print prettyText("--offset : TODO","green")
    print prettyText("example: %s --alphabet alphabet.txt --word 12131415 --list add,sub" % sys.argv[0],"green")