Example #1
0
    def __init__(self,
                 updateTime,
                 errorLog,
                 bufferLog,
                 updateInterfaceFunctions,
                 updateCounterMax=[0, 0, 0, 0]):

        self.updateTime = updateTime

        self.data = Data()
        self.dataFile = File()
        # self.lapTimeFile = File()
        self.lastBuffers = bufferLog
        self.errorLog = errorLog

        # Dicionario de funcoes: permite chamar funcoes fazendo updateInterfaceFunctions[key], onde key é 1,2,3 ou 4
        self.updateInterfaceFunctions = updateInterfaceFunctions

        self.packIndexes = [1, 2, 3, 4]
        self.packSizes = self.data.pSizes

        self.updateCounterMax = updateCounterMax  # numero de pacotes recebidos at atualizar a interface
        self.updateCounter = [0, 0, 0, 0]
        self.updateInterfaceEnabled = True
Example #2
0
    def generateWithType(self, urf, params):
        file = File()

        # Coherence test
        for param in params:
            if (isinstance(param, Sanitize) and param.constraintType != ""):
                for param2 in params:
                    if (isinstance(param2, Construction) and
                        (param.constraintType != param2.constraintType)):
                        return
            if (isinstance(param, Sanitize) and param.constraintField != ""):
                for param2 in params:
                    if (isinstance(param2, Construction) and
                        (param.constraintField != param2.constraintField)):
                        return

        # retreve parameters for safety test
        safe = None
        for param in params:
            if isinstance(param, Construction):
                for param2 in params:
                    if isinstance(param2, Sanitize):
                        safe = self.testSafety(param, param2, urf + "_URF")

        flawCwe = {"CWE_601": "Open_Redirect"}

        # Creates folder tree and sample files if they don't exists
        file.addPath("PHPTestSuite_" + self.date)
        file.addPath("URF")
        file.addPath(urf)

        # sort by safe/unsafe
        file.addPath("safe" if safe else "unsafe")

        file.setName(self.generateFileName(params, urf))

        file.addContent("<?php\n")
        #file.addContent("/*\n")

        # Adds comments
        file.addContent("/* \n" +
                        ("Safe sample\n" if safe else "Unsafe sample\n"))

        for param in params:
            file.addContent(param.comment + "\n")
        file.addContent("*/\n\n")

        # Gets copyright header from file
        header = open("./rights_PHP.txt", "r")
        copyright = header.readlines()
        header.close()

        # Writes copyright statement in the sample file
        file.addContent("\n\n")
        for line in copyright:
            file.addContent(line)

        # Writes the code in the sample file
        file.addContent("\n\n")
        for param in params:
            if not safe and isinstance(param, Construction):
                file.addContent("//flaw\n")  #add this comment if not safe
            for line in param.code:
                file.addContent(line)
            file.addContent("\n\n")

        #if injection != "eval" and injection != "include_require":
        #    #Gets query execution code
        #    footer = open("./execQuery_" + injection + ".txt", "r")
        #    execQuery = footer.readlines()
        #    footer.close()

        #    #Adds the code for query execution
        #    for line in execQuery:
        #        file.addContent(line)

        file.addContent("\n\n?>")

        FileManager.createFile(file)

        flawLine = 0 if safe else self.findFlaw(file.getPath() + "/" +
                                                file.getName())

        for param in params:
            if isinstance(param, InputSample):
                self.manifest.beginTestCase(param.inputType)
                break

        self.manifest.addFileToTestCase(file.getPath() + "/" + file.getName(),
                                        flawLine)
        self.manifest.endTestCase()
        return file
Example #3
0
    def generateWithType(self, sm, params):
        file = File()

        # test if the samples need to be generated
        if self.revelancyTest(params) == 0:
            return None

        # retrieve parameters for safety test
        safe = None
        for param in params:
            if isinstance(param, Construction):
                for param2 in params:
                    if isinstance(param2, Sanitize):
                        safe = self.testSafety(param, param2, sm + "_SM")

        # Creates folder tree and sample files if they don't exists
        file.addPath("generation_" + self.date)
        file.addPath("SM")
        file.addPath(sm)

        # sort by safe/unsafe
        file.addPath("safe" if safe else "unsafe")

        file.setName(self.generateFileName(params, sm))

        file.addContent("<?php\n")

        # Adds comments
        file.addContent("/* \n" +
                        ("Safe sample\n" if safe else "Unsafe sample\n"))

        for param in params:
            file.addContent(param.comment + "\n")
        file.addContent("*/\n\n")

        # Gets copyright header from file
        header = open("./rights_PHP.txt", "r")
        copyright = header.readlines()
        header.close()

        # Writes copyright statement in the sample file
        file.addContent("\n\n")
        for line in copyright:
            file.addContent(line)

        # Writes the code in the sample file
        file.addContent("\n\n")
        for param in params:
            for line in param.code:
                file.addContent(line)
            file.addContent("\n\n")

        file.addContent("\n\n?>")

        FileManager.createFile(file)

        flawLine = 0 if safe else self.findFlaw(file.getPath() + "/" +
                                                file.getName())

        self.manifest.beginTestCase("Error_message")

        self.manifest.addFileToTestCase(file.getPath() + "/" + file.getName(),
                                        flawLine)
        self.manifest.endTestCase()
        return file
Example #4
0
def f_decorator(params, decorators, i):
    loop_alert = 0
    global function_cpt
    global class_cpt
    global file_cpt
    global postOp
    previous = None
    previous_var = ""
    # print(decorators)
    for d in reversed(decorators[i]):
        if d.get("type") == "if":
            types = [Construction, Sanitize, InputSample]
            if type(params[i]) not in types:
                continue
            # XSS construction sample codes can't use this decorator
            if isinstance(params[i], Construction) and "CWE_79_XSS" in params[i].flaws:
                continue
            if "function" in params[i].code or "class" in params[i].code:
                continue
            params[i].code[0] = params[i].code[0].replace("\n", "\n\t")
            params[i].code[0] = "if(True){\n\t" + params[i].code[0] + "\n}\n"
        elif d.get("type") == "loop":
            types = [Construction, Sanitize, InputSample]
            if type(params[i]) not in types:
                continue
            # XSS construction code can't use this decorator
            if isinstance(params[i], Construction) and "CWE_79_XSS" in params[i].flaws:
                continue
            if "function" in params[i].code or "class" in params[i].code:
                continue
            if d.get("kind") == "while":
                params[i].code[0] = params[i].code[0].replace("\n", "\n\t")
                params[i].code[0] = "\n$loop_cpt=0;\nwhile($loop_cpt++<10){\n\t" + params[i].code[0]
                params[i].code[-1] += "\n}\n"
            elif d.get("kind") == "for":
                params[i].code[0] = params[i].code[0].replace("\n", "\n\t")
                params[i].code[0] = "\nfor($loop_cpt=0;$loop_cpt<10;$loop_cpt++){\n\t" + params[i].code[0]
                params[i].code[-1] += "\n}\n"
            else:
                if loop_alert == 0:
                    print("loop type not specified so it will be ignored for " + str(
                        type(params[i])) + " (possible options: for,while)")
                    loop_alert = 1
        elif d.get("type") == "function":
            types = [Construction, Sanitize, InputSample]
            if type(params[i]) not in types:
                continue
            if isinstance(params[i], Construction) and "CWE_79_XSS" in params[i].flaws:
                continue
            if previous is not None and previous.get("type") in ["function", "class"]:
                print("you can't instantiate function in loop/conditional/function/class structures")
                exit(1)
            else:
                var = re.findall("(\$[a-zA-Z_]+) ?= ?.*", params[i].code[0], re.I)
                params[i].code[0] = params[i].code[0].replace("\n", "\n\t")
                name = ""
                for param in params:
                    if isinstance(param, Construction):
                        for param2 in params:
                            if isinstance(param2, Sanitize):
                                for value in set(param.flaws).intersection(param2.flaws):
                                    name = value
                name += "__"
                for param in params:
                    for dir in param.path:
                        name += dir
                if len(var) > 0:
                    var = var[-1]
                    params[i].code[-1] += "\n\treturn " + str(var) + ";\n}\n" + str(
                        var) + " = " + name + "_function" + str(
                        function_cpt) + "($tainted);\n"
                else:
                    if previous is not None and previous.get("type") == "file" and previous_var != "":
                        params[i].code[-1] += "\n\treturn " + str(previous_var) + ";\n}\n" + str(
                            previous_var) + " = " + name + "_function" + str(
                            function_cpt) + "($tainted);\n"
                        previous_var = ""
                    else:
                        params[i].code[-1] += "\n}\n" + "$f_function_var = " + name + "_function" + str(
                            function_cpt) + "($tainted);\n"
                params[i].code[0] = "\nfunction " + name + "_function" + str(function_cpt) + "($tainted){\n\t" + \
                                    params[i].code[0]
                function_cpt += 1
        elif d.get("type") == "class":
            types = [Construction, Sanitize, InputSample]
            if type(params[i]) not in types:
                continue
            if isinstance(params[i], Construction) and "CWE_79_XSS" in params[i].flaws:
                continue
            if previous is not None and previous.get("type") in ["loop", "if", "function", "class"]:
                print("you can't instantiate class in loop/conditional/function/class structures")
                exit(1)
            else:
                var = re.findall("(\$[a-zA-Z_]+) ?= ?.*", params[i].code[0], re.I)
                params[i].code[0] = params[i].code[0].replace("\n", "\n\t\t")
                name = ""
                for param in params:
                    if isinstance(param, Construction):
                        for param2 in params:
                            if isinstance(param2, Sanitize):
                                for value in set(param.flaws).intersection(param2.flaws):
                                    name = value
                name += "__"
                for param in params:
                    for dir in param.path:
                        name += dir
                params[i].code[0] = "\nclass " + name + "_class" + str(class_cpt) + "{" + \
                                    "\n\tprivate $_data;" + \
                                    "\n\tpublic function __construct($data){" + \
                                    "\n\t\t$this->setData($data);" + \
                                    "\n\t}" + \
                                    "\n\tpublic function setData($data){" + \
                                    "\n\t\t$this->_data = $data;" + \
                                    "\n\t}" + \
                                    "\n\tpublic function a(){" + \
                                    "\n\t\t$tainted = $this->_data;" + \
                                    "\n\t\t" + params[i].code[0]
                if len(var) > 0:
                    var = var[-1]
                    params[i].code[-1] += "\n\t\treturn " + str(
                        var) + ";\n\t}\n}\n" + "$a = new " + name + "_class" + str(
                        class_cpt) + "($tainted);\n" + str(var) + " = $a->a();\n"
                else:
                    if previous is not None and previous.get("type") == "file" and previous_var != "":
                        params[i].code[-1] += "\n\t\treturn " + str(
                            previous_var) + ";\n\t}\n}\n" + "$a = new " + name + "_class" + str(
                            class_cpt) + "($tainted);\n" + str(previous_var) + " = $a->a();\n"
                        previous_var = ""
                    else:
                        params[i].code[-1] += "\n\t}\n}\n" + "$f_class_var = new " + name + "_class" + str(
                            class_cpt) + "($tainted);\n$f_class_var = $f_class_var->a();\n"
                class_cpt += 1
        elif d.get("type") == "file":
            types = [Construction, Sanitize, InputSample]
            if type(params[i]) not in types:
                continue
            if isinstance(params[i], Construction) and "CWE_79_XSS" in params[i].flaws:
                continue
            else:
                file = File()
                file.addContent("<?php\n")
                header = open("./rights_PHP.txt", "r")
                copyright = header.readlines()
                for line in copyright:
                    file.addContent(line)
                var = re.findall("(\$[a-zA-Z_]+) ?= ?.*", params[i].code[0], re.I)
                if len(var) > 0:
                    previous_var = var[-1]
                file.addContent(params[i].code[0])
                file.addContent("\n?>")
                name = ""
                for param in params:
                    if isinstance(param, Construction):
                        for param2 in params:
                            if isinstance(param2, Sanitize):
                                for value in set(param.flaws).intersection(param2.flaws):
                                    name = value
                for param in params:
                    name += "__"
                    for dir in param.path:
                        name += dir + "-"
                    name = name[:-1]
                type_param = ""
                if isinstance(params[i], InputSample):
                    type_param = "input"
                elif isinstance(params[i], Sanitize):
                    type_param = "sanitize"
                elif isinstance(params[i], Construction):
                    type_param = "construction"
                file.setName(name + "__" + type_param + "_" + str(file_cpt))
                params[i].code[0] = "\ninclude_once(\"" + file.getName() + "\");\n"
                postOp.append(file)
                file_cpt += 1
        previous = d
    def generateWithType(self, urf, params):
        file = File()

        # Coherence test
        for param in params:
            if (isinstance(param, Sanitize) and param.constraintType != ""):
                for param2 in params:
                    if (isinstance(param2, Construction) and (param.constraintType != param2.constraintType)):
                        return
            if (isinstance(param, Sanitize) and param.constraintField != ""):
                for param2 in params:
                    if (isinstance(param2, Construction) and (param.constraintField != param2.constraintField)):
                        return

        # retreve parameters for safety test
        safe = None
        for param in params:
            if isinstance(param, Construction):
                for param2 in params:
                    if isinstance(param2, Sanitize):
                        safe = self.testSafety(param, param2, urf + "_URF")

        flawCwe = {"CWE_601": "Open_Redirect"
        }

        # Creates folder tree and sample files if they don't exists
        file.addPath("PHPTestSuite_"+self.date)
        file.addPath("URF")
        file.addPath(urf)

        # sort by safe/unsafe
        file.addPath("safe" if safe else "unsafe")

        file.setName(self.generateFileName(params, urf))

        file.addContent("<?php\n")
        #file.addContent("/*\n")

        # Adds comments
        file.addContent("/* \n" + ("Safe sample\n" if safe else "Unsafe sample\n"))

        for param in params:
            file.addContent(param.comment + "\n")
        file.addContent("*/\n\n")

        # Gets copyright header from file
        header = open("./rights_PHP.txt", "r")
        copyright = header.readlines()
        header.close()

        # Writes copyright statement in the sample file
        file.addContent("\n\n")
        for line in copyright:
            file.addContent(line)

        # Writes the code in the sample file
        file.addContent("\n\n")
        for param in params:
            if not safe and isinstance(param, Construction) :
                file.addContent("//flaw\n") #add this comment if not safe
            for line in param.code:
                file.addContent(line)
            file.addContent("\n\n")

        #if injection != "eval" and injection != "include_require":
        #    #Gets query execution code
        #    footer = open("./execQuery_" + injection + ".txt", "r")
        #    execQuery = footer.readlines()
        #    footer.close()

        #    #Adds the code for query execution
        #    for line in execQuery:
        #        file.addContent(line)

        file.addContent("\n\n?>")

        FileManager.createFile(file)

        flawLine = 0 if safe else self.findFlaw(file.getPath() + "/" + file.getName())

        for param in params:
            if isinstance(param, InputSample):
                self.manifest.beginTestCase(param.inputType)
                break

        self.manifest.addFileToTestCase(file.getPath() + "/" + file.getName(), flawLine)
        self.manifest.endTestCase()
        return file
Example #6
0
    def generateWithType(self, IDOR, params):
        file = File()

        #Build constraints
        safe = None
        for param in params:
            if isinstance(param, Construction):
                for param2 in params:
                    if isinstance(param2, Sanitize):
                        safe = self.testSafety(param, param2, IDOR + "_IDOR")  # 1 : safe ,0 : unsafe

        flawCwe = {"CWE_862_SQL": "SQL",
                   "CWE_862_Fopen": "fopen",
                   "CWE_862_XPath": "XPath"
        }

        #Creates folder tree and sample files if they don't exists
        file.addPath("PHPTestSuite_"+self.date)
        file.addPath("IDOR")
        file.addPath(IDOR)

        #sort by safe/unsafe
        file.addPath("safe" if safe else "unsafe")

        file.setName(self.generateFileName(params, IDOR))

        file.addContent("<?php\n")
        file.addContent("/*\n")

        #Adds comments
        file.addContent("/* \n" + ("Safe sample\n" if safe else "Unsafe sample\n"))

        for param in params:
            file.addContent(param.comment + "\n")
        file.addContent("*/\n\n")

        # Gets copyright header from file
        header = open("./rights_PHP.txt", "r")
        copyright = header.readlines()
        header.close()

        #Writes copyright statement in the sample file
        file.addContent("\n\n")
        for line in copyright:
            file.addContent(line)

        #Writes the code in the sample file
        file.addContent("\n\n")
        for param in params:
            for line in param.code:
                file.addContent(line)
            file.addContent("\n\n")

        if flawCwe[IDOR] != "fopen":
            for param in params:
                if isinstance(param, Construction):
                    if param.prepared == 0 or flawCwe[IDOR] == "XPath":
                        fileQuery = open("./execQuery_" + flawCwe[IDOR] + ".txt", "r")
                        execQuery = fileQuery.readlines()
                        fileQuery.close()
                        for line in execQuery:
                            file.addContent(line)
                    else:
                        fileQuery = open("./execQuery_" + flawCwe[IDOR] + "_prepared.txt", "r")
                        execQueryPrepared = fileQuery.readlines()
                        fileQuery.close()
                        for line in execQueryPrepared:
                            file.addContent(line)

        file.addContent("\n ?>")
        FileManager.createFile(file)

        flawLine = 0 if safe else self.findFlaw(file.getPath() + "/" + file.getName())

        for param in params:
            if isinstance(param, InputSample):
                self.manifest.beginTestCase(param.inputType)
                break

        self.manifest.addFileToTestCase(file.getPath() + "/" + file.getName(), flawLine)
        self.manifest.endTestCase()
        return file
Example #7
0
    def generate(self, params):
        file = File()

        # retrieve parameters for safety test
        safe = None
        for param in params:
            if isinstance(param, Construction):
                for param2 in params:
                    if isinstance(param2, Sanitize):
                        safe = self.testSafety(param, param2, "CWE_79_XSS")

        # Creates folder tree and sample files if they don't exists
        file.addPath("PHPTestSuite_" + self.date)
        file.addPath("XSS")
        file.addPath("CWE_79")
        file.addPath("safe" if safe else "unsafe")

        file.setName(self.generateFileName(params, "CWE_79"))

        # Adds comments
        file.addContent("<!-- \n" +
                        ("Safe sample\n" if safe else "Unsafe sample\n"))

        for param in params:
            file.addContent(param.comment + "\n")
        file.addContent("-->\n\n")

        # Writes copyright statement in the sample file
        for line in copyright:
            file.addContent(line)

        # Writes the code in the sample file
        file.addContent("\n\n")

        out = ""
        tmp = ""
        for param in params:
            if isinstance(param, Construction):
                for line in open(param.code[0], "r").readlines():
                    tmp += line
                out = tmp + out
                tmp = ""
                if not safe and isinstance(param, Construction):
                    tmp = "//flaw"  #add this comment if not safe
                for line in open(param.code[1], "r").readlines():
                    tmp += line
            else:
                for line in param.code:
                    out += line
                out += "\n\n"
            #file.addContent("\n\n")
        file.addContent(out + tmp)
        FileManager.createFile(file)

        flawLine = 0 if safe else self.findFlaw(file.getPath() + "/" +
                                                file.getName())

        for param in params:
            if isinstance(param, InputSample):
                self.manifest.beginTestCase(param.inputType)
                break

        self.manifest.addFileToTestCase(file.getPath() + "/" + file.getName(),
                                        flawLine)
        self.manifest.endTestCase()
        return file
    def generateWithType(self, injection, params):
        file = File()

        # test if the samples need to be generated
        if self.revelancyTest(params) == 0:
            return None

        # Coherence test
        for param in params:
            if (isinstance(param, Sanitize) and param.constraintType != ""):
                for param2 in params:
                    if (isinstance(param2, Construction) and
                        (param.constraintType != param2.constraintType)):
                        return
            if (isinstance(param, Sanitize) and param.constraintField != ""):
                for param2 in params:
                    if (isinstance(param2, Construction) and
                        (param.constraintField != param2.constraintField)):
                        return

        # retreve parameters for safety test
        safe = None
        for param in params:
            if isinstance(param, Construction):
                for param2 in params:
                    if isinstance(param2, Sanitize):
                        safe = self.testSafety(param, param2,
                                               injection + "_Injection")

        flawCwe = {
            "CWE_78": "OSCommand",
            "CWE_91": "XPath",
            "CWE_90": "LDAP",
            "CWE_89": "SQL",
            "CWE_95": "eval",
            "CWE_98": "include_require"
        }

        # Creates folder tree and sample files if they don't exists
        file.addPath("generation_" + self.date)
        file.addPath("Injection")
        file.addPath(injection)

        # sort by safe/unsafe
        file.addPath("safe" if safe else "unsafe")

        file.setName(self.generateFileName(params, injection))

        file.addContent("<?php\n")

        # Adds comments
        file.addContent("/* \n" +
                        ("Safe sample\n" if safe else "Unsafe sample\n"))

        for param in params:
            file.addContent(param.comment + "\n")
        file.addContent("*/\n\n")

        # Gets copyright header from file
        header = open("./rights_PHP.txt", "r")
        copyright = header.readlines()
        header.close()

        # Writes copyright statement in the sample file
        file.addContent("\n\n")
        for line in copyright:
            file.addContent(line)

        # Writes the code in the sample file
        file.addContent("\n\n")
        for param in params:
            for line in param.code:
                file.addContent(line)
            file.addContent("\n\n")

        if injection != "CWE_98":
            #Gets query execution code
            footer = open("./execQuery_" + flawCwe[injection] + ".txt", "r")
            execQuery = footer.readlines()
            footer.close()

            #Adds the code for query execution
            for line in execQuery:
                file.addContent(line)

        file.addContent("\n\n?>")

        FileManager.createFile(file)

        flawLine = 0 if safe else self.findFlaw(file.getPath() + "/" +
                                                file.getName())

        for param in params:
            if isinstance(param, InputSample):
                self.manifest.beginTestCase(param.inputType)
                break

        self.manifest.addFileToTestCase(file.getPath() + "/" + file.getName(),
                                        flawLine)
        self.manifest.endTestCase()
        return file
    def generate(self, params):
        file = File()

        # retrieve parameters for safety test
        safe = None
        for param in params:
            if isinstance(param, Construction):
                for param2 in params:
                    if isinstance(param2, Sanitize):
                        safe = self.testSafety(param, param2, "CWE_79_XSS")

        # Creates folder tree and sample files if they don't exists
        file.addPath("PHPTestSuite_"+self.date)
        file.addPath("XSS")
        file.addPath("CWE_79")
        file.addPath("safe" if safe else "unsafe")

        file.setName(self.generateFileName(params, "CWE_79"))

        # Adds comments
        file.addContent("<!-- \n" + ("Safe sample\n" if safe else "Unsafe sample\n"))

        for param in params:
            file.addContent(param.comment + "\n")
        file.addContent("-->\n\n")

        # Writes copyright statement in the sample file
        for line in copyright:
            file.addContent(line)

        # Writes the code in the sample file
        file.addContent("\n\n")

        out = ""
        tmp = ""
        for param in params:
            if isinstance(param, Construction):
                for line in open(param.code[0], "r").readlines():
                    tmp += line
                out = tmp + out
                tmp = ""
                if not safe and isinstance(param, Construction) :
                    tmp = "//flaw" #add this comment if not safe
                for line in open(param.code[1], "r").readlines():
                    tmp += line
            else:
                for line in param.code:
                    out += line
                out += "\n\n"
            #file.addContent("\n\n")
        file.addContent(out + tmp)
        FileManager.createFile(file)

        flawLine = 0 if safe else self.findFlaw(file.getPath() + "/" + file.getName())

        for param in params:
            if isinstance(param, InputSample):
                self.manifest.beginTestCase(param.inputType)
                break

        self.manifest.addFileToTestCase(file.getPath() + "/" + file.getName(), flawLine)
        self.manifest.endTestCase()
        return file
    def generateWithType(self, sde, params):
        file = File()

        # test if the samples need to be generated
        if self.revelancyTest(params) == 0:
            return None

        # retreve parameters for safety test
        safe = None
        for param in params:
            if isinstance(param, Construction):
                for param2 in params:
                    if isinstance(param2, Sanitize):
                        safe = self.testSafety(param, param2, sde + "_SDE")

        # Creates folder tree and sample files if they don't exists
        file.addPath("generation_" + self.date)
        file.addPath("SDE")
        file.addPath(sde)

        # sort by safe/unsafe
        file.addPath("safe" if safe else "unsafe")

        file.setName(self.generateFileName(params, sde))

        file.addContent("<?php\n")
        #file.addContent("/*\n")

        # Adds comments
        file.addContent("/* \n" +
                        ("Safe sample\n" if safe else "Unsafe sample\n"))

        for param in params:
            file.addContent(param.comment + "\n")
        file.addContent("*/\n\n")

        # Gets copyright header from file
        header = open("./rights_PHP.txt", "r")
        copyright = header.readlines()
        header.close()

        # Writes copyright statement in the sample file
        file.addContent("\n\n")
        for line in copyright:
            file.addContent(line)

        # Writes the code in the sample file
        file.addContent("\n\n")
        for param in params:
            for line in param.code:
                file.addContent(line)
            file.addContent("\n\n")

        #if injection != "eval" and injection != "include_require":
        #    #Gets query execution code
        #    footer = open("./execQuery_" + injection + ".txt", "r")
        #    execQuery = footer.readlines()
        #    footer.close()

        #    #Adds the code for query execution
        #    for line in execQuery:
        #        file.addContent(line)

        file.addContent("\n\n?>")

        FileManager.createFile(file)

        flawLine = 0 if safe else self.findFlaw(file.getPath() + "/" +
                                                file.getName())

        #for param in params:
        #    if isinstance(param, InputSample):
        #        self.manifest.beginTestCase(param.inputType)
        #        break
        self.manifest.beginTestCase("Sensitive_data")

        self.manifest.addFileToTestCase(file.getPath() + "/" + file.getName(),
                                        flawLine)
        self.manifest.endTestCase()
        return file
    def generateWithType(self, IDOR, params):
        file = File()

        #Build constraints
        safe = None
        for param in params:
            if isinstance(param, Construction):
                for param2 in params:
                    if isinstance(param2, Sanitize):
                        safe = self.testSafety(param, param2, IDOR + "_IDOR")  # 1 : safe ,0 : unsafe

        flawCwe = {"CWE_862_SQL": "SQL",
                   "CWE_862_Fopen": "fopen",
                   "CWE_862_XPath": "XPath"
        }

        #Creates folder tree and sample files if they don't exists
        file.addPath("PHPTestSuite_"+self.date)
        file.addPath("IDOR")
        file.addPath(IDOR)

        #sort by safe/unsafe
        file.addPath("safe" if safe else "unsafe")

        file.setName(self.generateFileName(params, IDOR))

        file.addContent("<?php\n")
        file.addContent("/*\n")

        #Adds comments
        file.addContent("/* \n" + ("Safe sample\n" if safe else "Unsafe sample\n"))

        for param in params:
            file.addContent(param.comment + "\n")
        file.addContent("*/\n\n")

        # Gets copyright header from file
        header = open("./rights_PHP.txt", "r")
        copyright = header.readlines()
        header.close()

        #Writes copyright statement in the sample file
        file.addContent("\n\n")
        for line in copyright:
            file.addContent(line)

        #Writes the code in the sample file
        file.addContent("\n\n")
        for param in params:
            if not safe  and isinstance(param, Construction) :
                file.addContent("//flaw\n") #add this comment if not safe
            for line in param.code:
                file.addContent(line)
            file.addContent("\n\n")

        if flawCwe[IDOR] != "fopen":
            for param in params:
                if isinstance(param, Construction):
                    if param.prepared == 0 or flawCwe[IDOR] == "XPath":
                        fileQuery = open("./execQuery_" + flawCwe[IDOR] + ".txt", "r")
                        execQuery = fileQuery.readlines()
                        fileQuery.close()
                        for line in execQuery:
                            file.addContent(line)
                    else:
                        fileQuery = open("./execQuery_" + flawCwe[IDOR] + "_prepared.txt", "r")
                        execQueryPrepared = fileQuery.readlines()
                        fileQuery.close()
                        for line in execQueryPrepared:
                            file.addContent(line)

        file.addContent("\n ?>")
        FileManager.createFile(file)

        flawLine = 0 if safe else self.findFlaw(file.getPath() + "/" + file.getName())

        for param in params:
            if isinstance(param, InputSample):
                self.manifest.beginTestCase(param.inputType)
                break

        self.manifest.addFileToTestCase(file.getPath() + "/" + file.getName(), flawLine)
        self.manifest.endTestCase()
        return file
Example #12
0
class Program():
    def __init__(self,
                 updateTime,
                 errorLog,
                 bufferLog,
                 updateInterfaceFunctions,
                 updateCounterMax=[0, 0, 0, 0]):

        self.updateTime = updateTime

        self.data = Data()
        self.dataFile = File()
        # self.lapTimeFile = File()
        self.lastBuffers = bufferLog
        self.errorLog = errorLog

        # Dicionario de funcoes: permite chamar funcoes fazendo updateInterfaceFunctions[key], onde key é 1,2,3 ou 4
        self.updateInterfaceFunctions = updateInterfaceFunctions

        self.packIndexes = [1, 2, 3, 4]
        self.packSizes = self.data.pSizes

        self.updateCounterMax = updateCounterMax  # numero de pacotes recebidos at atualizar a interface
        self.updateCounter = [0, 0, 0, 0]
        self.updateInterfaceEnabled = True

    def openSerialPort(self, port, baudrate, timeout):
        self.porta = serial.Serial()
        self.porta.baudrate = baudrate
        self.porta.port = port
        self.porta.timeout = timeout
        self.porta.open()

    def stopProgram(self):
        self.stop = 1  # atualiza o valor da variavel stop, a qual é usada para verificar o funcionamento da interface
        # self.lapTimeFile.stopDataSave()
        # Fecha arquivo file e porta serial
        self.dataFile.stopDataSave()
        if self.porta.isOpen():
            self.porta.flushInput()
            self.porta.close()
        else:
            pass

    # program() roda em loop
    def program(self):
        if (self.stop == 0):
            # Le dados da porta serial

            self.buffer = self.readFromSerialPort(self.packSizes,
                                                  self.packIndexes)
            if len(self.buffer) != 0:
                # chamada da função updateDataAndInterface para analisar os dados recebidos atualizar os mostradores da interface
                self.updateData(self.buffer, int(self.buffer[0]))
                if self.dataFile.save == 1:
                    self.saveLine(self.buffer, int(self.buffer[0]))
                if self.updateInterfaceEnabled:
                    self.updateInterface(self.buffer, int(self.buffer[0]))

            # Apos updateTime segundos, chama funcao program() novamente
            QtCore.QTimer.singleShot(self.updateTime, lambda: self.program())

    def updateData(self, buffer, packID):
        # Atualiza dados em Data e atualiza campos respectivos na interface
        if (self.data.updateDataFunctions[packID](buffer) == 0):
            self.errorLog.writeLog(" updateData: Pacote " + str(packID) +
                                   "com tamanho diferente do configurado")

        # Desloca vetores e chama funcao de atualizar graficos da interface
        if packID == 2 or packID == 3:
            self.data.rollArrays()

    def updateInterface(self, buffer, packID):

        # Chama funcao updatePxInterface, atribuida no dicionario updateInterfaceFunctions, para a chave x = packID
        if self.updateCounter[packID - 1] >= self.updateCounterMax[packID - 1]:
            self.updateInterfaceFunctions[packID](self.data)
            self.updateCounter[packID - 1] = 0
        else:
            self.updateCounter[packID - 1] += 1

        # Atualiza o mostrador textBrowser_Buffer com as ultimas listas de dados recebidas.
        self.lastBuffers.writeLog(vectorToString(buffer, ' ',
                                                 addNewLine=False))

    def saveLine(self, buffer, packID):
        # Grava linha buffer no arquivo

        string = self.data.createPackString(packID)
        self.dataFile.writeRow(string)

    # Le buffer da porta serial. bufferSize é uma lista com os tamanhos dos pacotes e firstByteValues
    # é uma lista com os numeros dos pacotes (1,2,3,4)
    def readFromSerialPort(self, bufferSize, firstByteValues):
        while True:
            # Espera receber algo na porta serial
            while (self.porta.inWaiting() == 0):
                pass
            read_buffer = b''
            # Le primeiro e segundo bytes
            firstByte = self.porta.read()

            if int.from_bytes(firstByte, byteorder='big') in firstByteValues:
                read_buffer += firstByte
                # Le o segundo byte de inicio
                a = self.porta.read()
                if int.from_bytes(a, byteorder='big') == 5:
                    read_buffer += a
                    break
                else:
                    self.errorLog.writeLog(
                        "Leitura: segundo byte com valor inesperado. Leu-se " +
                        str(firstByte) + ", esperava-se 5")
            # Se o byte lido nao for 1, 2 3 ou 4,, quer dizer que perdeu algum dado.
            else:
                self.errorLog.writeLog(
                    "Leitura: primeiro byte com valor inesperado. Leu-se " +
                    str(firstByte) + ", esperava-se de 1 a 4")
        while True:
            # Le resto do buffer
            index = int.from_bytes(firstByte, byteorder='big') - 1
            byte = self.porta.read(size=int(bufferSize[index] - 2))
            read_buffer += byte

            if (len(read_buffer) == bufferSize[index]):
                if int(read_buffer[bufferSize[index] - 2]) == 9:
                    # Chegou no fim do pacote
                    if int(read_buffer[bufferSize[index] - 1]) == 10:
                        break
                    else:
                        self.errorLog.writeLog(
                            "Leitura: ultimo dado diferente de byte 10" +
                            str(read_buffer))
                        return []
                else:
                    self.errorLog.writeLog(
                        "Leitura: penultimo dado diferente de byte 9")
                    return []
        return read_buffer