Exemple #1
0
    def update(self, vocabulary):
        """update the definition of the automata
        and searched for deprecated symbols"""
        deprecatedTransitions = []

        for transition in self.transitions:
            if transition.getType() == SemiStochasticTransition.TYPE:
                symbols = []
                symbols.append(transition.getInputSymbol())
                for (s, p, ti) in transition.getOutputSymbols():
                    if s.getType() == Symbol.TYPE:
                        symbols.append(s)

                error = False
                for symbol in symbols:
                    found = False
                    vocaSymbols = [EmptySymbol(), UnknownSymbol()]
                    vocaSymbols.extend(vocabulary.getSymbols())
                    for s in vocaSymbols:
                        if str(s.getID()) == str(symbol.getID()):
                            found = True
                            break
                    if not found:
                        self.log.warning(
                            "Symbol {0} has not been found in vocabulary".
                            format(symbol.getName()))
                        error = True
                        break
                if error:
                    deprecatedTransitions.append(transition)
        for transiton in deprecatedTransitions:
            self.removeTransition(transition)
Exemple #2
0
    def startInference(self, button):
        # We retrieve the specified value
        actorType = self.targetOfInferenceCombo.get_active_text()
        actorIP = self.IPEntry.get_text()
        actorNetworkProtocol = self.combo_protocolOfNetworkActor.get_active_text(
        )
        ourPort = int(self.ourPortEntry.get_text())
        targetPort = int(self.targetPortEntry.get_text())
        scriptFilename = self.scriptEntry.get_text()
        maxNumberOfState = int(self.MaxStatesEntry.get_text())

        inputDictionary = []
        for symbol in self.project.getVocabulary().getSymbols():
            #            if symbol.getName() == "LOGIN" or symbol.getName() == "EXECUTE" or symbol.getName() == "LOGOUT" or symbol.getName() == "DOWNLOAD":
            inputDictionary.append(symbol)
        inputDictionary.append(UnknownSymbol())
        # Close the current dialog
        self.dialog.destroy()

        anID = str(uuid.uuid4())
        memory = Memory()
        if actorType == "CLIENT":
            # Lets create a simple network oracle
            oracleCommunicationChannel = NetworkServer(anID, memory,
                                                       actorNetworkProtocol,
                                                       "127.0.0.1", ourPort,
                                                       actorIP, targetPort)
        else:
            # Lets create a simple network oracle
            oracleCommunicationChannel = NetworkClient(anID, memory,
                                                       actorNetworkProtocol,
                                                       "127.0.0.1", ourPort,
                                                       actorIP, targetPort)

        # Lets create an equivalence oracle
        equivalenceOracle = WMethodNetworkEquivalenceOracle(
            oracleCommunicationChannel, maxNumberOfState, scriptFilename)

        # Lets create the automatic inferer
        self.inferer = GrammarInferer(self.project.getVocabulary(),
                                      inputDictionary,
                                      oracleCommunicationChannel,
                                      equivalenceOracle, scriptFilename,
                                      self.callback_submitedQuery,
                                      self.callback_hypotheticalAutomaton)

        # Open the new dialog which shows the status of the inferring process
        self.createInferringStatusView()

        # Start the progress bar
        GObject.timeout_add(200, self.do_pulse)

        # Start the inferer
        self.job = Job(self.startInferer())
Exemple #3
0
 def getSymbol(self, symbolID):
     for symbol in self.symbols:
         if symbol.getID() == symbolID:
             return symbol
     # Exceptions : if ID = "EmptySymbol", we return an EmptySymbol
     if symbolID == str("EmptySymbol"):
         return EmptySymbol()
     # Exceptions : if ID = "UnknownSymbol", we return an UnknownSymbol
     if symbolID == str("UnknownSymbol"):
         return UnknownSymbol()
     return None
Exemple #4
0
 def getSymbolByName(self, symbolName):
     for symbol in self.symbols:
         if symbol.getName() == symbolName:
             return symbol
         # Exceptions : if name = "EmptySymbol", we return an EmptySymbol
         if symbolName == EmptySymbol.TYPE:
             return EmptySymbol()
         # Exceptions : if name = "UnkownSymbol", we return an UnknownSymbol
         if symbolName == UnknownSymbol.TYPE:
             return UnknownSymbol()
     return None
    def abstract(self, message):
        """abstract:
                Searches in the vocabulary the symbol which abstract the received message.

                @type message: netzob.Common.Models.AbstractMessage
                @param message: the message that is being read/compare/learn.
                @rtype: netzob.Common.Symbol
                @return: the symbol which content matches the message.
        """
        self.log.debug("We abstract the received message : " +
                       TypeConvertor.bin2strhex(message))
        # we search in the vocabulary an entry which match the message
        for symbol in self.vocabulary.getSymbols():
            self.log.debug("Try to abstract message through : {0}.".format(
                symbol.getName()))
            readingToken = VariableReadingToken(
                False, self.vocabulary, self.memory,
                TypeConvertor.strBitarray2Bitarray(message), 0)
            symbol.getRoot().read(readingToken)

            logging.debug(
                "ReadingToken: isOk: {0}, index: {1}, len(value): {2}".format(
                    str(readingToken.isOk()), str(readingToken.getIndex()),
                    str(len(readingToken.getValue()))))
            # The message matches if the read is ok and the whole entry was read.
            if readingToken.isOk() and readingToken.getIndex() == len(
                    readingToken.getValue()):
                self.log.debug("The message matches symbol {0}.".format(
                    symbol.getName()))
                # It matches so we learn from it if it's possible
                return symbol
            else:
                self.log.debug("The message doesn't match symbol {0}.".format(
                    symbol.getName()))
            # This is now managed in the variables modules.
            #===================================================================
            #    self.memory.createMemory()
            #    self.log.debug("We memorize the symbol " + str(symbol.getRoot()))
            #    readingToken = VariableReadingToken(False, self.vocabulary, self.memory, TypeConvertor.strBitarray2Bitarray(message), 0)
            #    symbol.getRoot().learn(readingToken)
            #    self.memory.persistMemory()
            #    return symbol
            # else:
            #    self.log.debug("Entry " + str(symbol.getID()) + " doesn't match")
            #    # we first restore a possibly learned value
            #    self.log.debug("Restore possibly learned value")
            #    processingToken = AbstractVariableProcessingToken(False, self.vocabulary, self.memory)
            #    symbol.getRoot().restore(processingToken)
            #===================================================================
        return UnknownSymbol()
    def __init__(self, grammarController, currentTransition):
        self.grammarController = grammarController
        self.currentTransition = currentTransition
        if self.currentTransition is None:
            self.idTransition = str(uuid.uuid4())
        else:
            self.idTransition = self.currentTransition.getID()
        self._view = CreateSemiStochasticTransitionView(
            self, self.idTransition)
        self.log = logging.getLogger(__name__)

        if self.currentTransition is not None:
            self.view.idSemiStochasticTransitionEntry.set_text(
                self.idTransition)
            self.view.nameSemiStochasticTransitionEntry.set_text(
                self.currentTransition.getName())

            # Retrieves the list of states and of input symbols
            states = []
            inputSymbols = [EmptySymbol(), UnknownSymbol()]
            currentProject = self.grammarController.getCurrentProject()
            if currentProject is not None:
                automata = currentProject.getGrammar().getAutomata()
                if automata is not None:
                    states.extend(automata.getStates())
                vocabulary = currentProject.getVocabulary()
                if vocabulary is not None:
                    inputSymbols.extend(vocabulary.getSymbols())

            # Set the start state
            i = 0
            for state in states:
                if str(state.getID()) == self.currentTransition.getInputState(
                ).getID():
                    self.view.startStateSemiStochasticTransitionComboBox.set_active(
                        i)
                    break
                i += 1

            # Set the end state
            i = 0
            for state in states:
                if str(state.getID()) == self.currentTransition.getOutputState(
                ).getID():
                    self.view.endStateSemiStochasticTransitionComboBox.set_active(
                        i)
                    break
                i += 1

            # Set the input symbol
            i = 0
            for symbol in inputSymbols:
                if str(symbol.getID()
                       ) == self.currentTransition.getInputSymbol().getID():
                    self.view.inputSymbolSemiStochasticTransitionComboBox.set_active(
                        i)
                    break
                i += 1

            # Set the output symbols
            outputSymbols = self.currentTransition.getOutputSymbols()
            for outputSymbolTupple in outputSymbols:
                (outputSymbol, probabilityOutput,
                 timeOutput) = outputSymbolTupple
                i = self.view.outputSymbolsListStore.append()
                self.view.outputSymbolsListStore.set(i, 0,
                                                     str(outputSymbol.getID()))
                self.view.outputSymbolsListStore.set(i, 1,
                                                     outputSymbol.getName())
                self.view.outputSymbolsListStore.set(i, 2, probabilityOutput)
                self.view.outputSymbolsListStore.set(i, 3, timeOutput)
    def addOutputSymbolSemiStochasticTransitionButton_clicked_cb(self, event):
        symbols = [EmptySymbol(), UnknownSymbol()]
        currentProject = self.grammarController.getCurrentProject()
        if currentProject is not None:
            vocabulary = currentProject.getVocabulary()
            if vocabulary is not None:
                symbols.extend(vocabulary.getSymbols())

        # Retrieve the output symbol
        active_iter = self._view.outputSymbolSemiStochasticTransitionComboBox.get_active_iter(
        )
        if active_iter is None:
            errorMessage = _("Select an output Symbol before adding it.")
            self.displayErrorMessage(errorMessage)
            return

        idSymbol = self._view.outputSymbolSemiStochasticTransitionComboBox.get_model(
        )[active_iter][0]
        outputSymbol = None
        for symbol in symbols:
            if str(symbol.getID()) == str(idSymbol):
                outputSymbol = symbol
                break

        if outputSymbol is None:
            errorMessage = _(
                "An error occured and prevented to retrieved the output symbol."
            )
            self.displayErrorMessage(errorMessage)
            return

        # Retrieve the probability of the symbol
        probabilityOutputSymbol = float(0.0)
        try:
            probabilityOutputSymbol = float(
                self._view.outputSymbolProbabilitySemiStochasticTransitionEntry
                .get_text())
        except:
            errorMessage = _(
                "Specify a valid probability defined over 100 (float)")
            self.displayErrorMessage(errorMessage)
            return

        if probabilityOutputSymbol < 0 or probabilityOutputSymbol > 100:
            errorMessage = _(
                "Specify a valid probability (0.0<=probability<=100.0)")
            self.displayErrorMessage(errorMessage)
            return

        # Retrieve the time of the output symbol
        timeOutputSymbol = 0
        try:
            timeOutputSymbol = int(
                self._view.outputSymbolTimeSemiStochasticTransitionEntry.
                get_text())
        except:
            errorMessage = _(
                "Specify a valid time defined in millisecond (int)")
            self.displayErrorMessage(errorMessage)
            return

        if timeOutputSymbol < 0:
            errorMessage = _("Specify a valid time (0<=time)")
            self.displayErrorMessage(errorMessage)
            return

        # Now we verify its the first time this symbol is considered as an output symbol
        found = False
        sumProba = probabilityOutputSymbol
        for row in self._view.outputSymbolsListStore:
            if str(row[0]) == str(outputSymbol.getID()):
                found = True
                break
            sumProba += row[2]
        if found:
            errorMessage = _(
                "You cannot add multiple time the same output symbol.")
            self.displayErrorMessage(errorMessage)
            return

        # We verify the sum of probabilities is under 100
        if sumProba > 100:
            errorMessage = _(
                "The sum of probabilities is above 100, please adapt the provided value."
            )
            self.displayErrorMessage(errorMessage)
            return

        i = self._view.outputSymbolsListStore.append()
        self._view.outputSymbolsListStore.set(i, 0, str(outputSymbol.getID()))
        self._view.outputSymbolsListStore.set(i, 1, outputSymbol.getName())
        self._view.outputSymbolsListStore.set(i, 2, probabilityOutputSymbol)
        self._view.outputSymbolsListStore.set(i, 3, timeOutputSymbol)

        self.displayErrorMessage(None)
    def createSemiStochasticTransitionButton_clicked_cb(self, event):
        """callback executed when the user requests
        the creation of the transition"""
        currentProject = self.grammarController.getCurrentProject()

        # Remove old transition
        if currentProject is not None:
            automata = currentProject.getGrammar().getAutomata()
            if self.currentTransition is not None:
                automata.removeTransition(self.currentTransition)

        # Retrieve the states and symbols of the current project
        states = []
        symbols = [EmptySymbol(), UnknownSymbol()]
        if currentProject is not None:
            automata = currentProject.getGrammar().getAutomata()
            if automata is not None:
                states.extend(automata.getStates())
            vocabulary = currentProject.getVocabulary()
            if vocabulary is not None:
                symbols.extend(vocabulary.getSymbols())

        # Name of the transition
        nameTransition = self._view.nameSemiStochasticTransitionEntry.get_text(
        )
        if nameTransition is None or len(nameTransition) == 0:
            errorMessage = _("Give a name to the transition.")
            self.displayErrorMessage(errorMessage)
            return

        # Start and End state of the transition
        startState_iter = self._view.startStateSemiStochasticTransitionComboBox.get_active_iter(
        )
        endState_iter = self._view.endStateSemiStochasticTransitionComboBox.get_active_iter(
        )
        if startState_iter is None:
            errorMessage = _("Select a start state.")
            self.displayErrorMessage(errorMessage)
            return
        if endState_iter is None:
            errorMessage = _("Select an end state")
            self.displayErrorMessage(errorMessage)
            return

        idStartState = self._view.startStateSemiStochasticTransitionComboBox.get_model(
        )[startState_iter][0]
        idEndState = self._view.endStateSemiStochasticTransitionComboBox.get_model(
        )[endState_iter][0]
        startState = None
        endState = None
        for state in states:
            if str(state.getID()) == str(idStartState):
                startState = state
            if str(state.getID()) == str(idEndState):
                endState = state
            if startState is not None and endState is not None:
                break
        if startState is None:
            errorMessage = _(
                "An error occurred and prevented to retrieve the provided start state."
            )
            self.displayErrorMessage(errorMessage)
            return
        if endState is None:
            errorMesssage = _(
                "An error occurred and prevented to retrieve the provided end state."
            )
            self.displayErrorMessage(errorMessage)
            return

        # Input Symbol
        inputSymbolIter = self._view.inputSymbolSemiStochasticTransitionComboBox.get_active_iter(
        )
        if inputSymbolIter is None:
            errorMessage = _("Select an input Symbol.")
            self.displayErrorMessage(errorMessage)
            return

        idInputSymbol = self._view.inputSymbolSemiStochasticTransitionComboBox.get_model(
        )[inputSymbolIter][0]
        inputSymbol = None
        for symbol in symbols:
            if str(symbol.getID()) == str(idInputSymbol):
                inputSymbol = symbol
                break
        if inputSymbol is None:
            errorMessage = _(
                "An error occurred and prevented to retrieve the provided input symbol"
            )
            self.displayErrorMessage(errorMessage)
            return

        # Verify the start state doesn't have a transition which has the same input symbol
        found = False
        for startStateTransition in startState.getTransitions():
            if startStateTransition.getType() == SemiStochasticTransition.TYPE:
                if str(startStateTransition.getInputSymbol().getID()) == str(
                        inputSymbol.getID()):
                    found = True
                    break
        if found:
            errorMessage = _(
                "The specified start state already has a transition with the same input symbol."
            )
            self.displayErrorMessage(errorMessage)
            return

        if len(self._view.outputSymbolsListStore) == 0:
            errorMessage = _(
                "Provide at least 1 output symbol (even an EmptySymbol).")
            self.displayErrorMessage(errorMessage)
            return

        # Create the transition
        transition = SemiStochasticTransition(self.idTransition,
                                              nameTransition, startState,
                                              endState, inputSymbol)

        # Now we add all the output symbols
        for row in self._view.outputSymbolsListStore:
            idOutputSymbol = row[0]
            probaOutputSymbol = row[2]
            timeOutputSymbol = row[3]

            outputSymbol = None
            for symbol in symbols:
                if str(symbol.getID()) == str(idOutputSymbol):
                    outputSymbol = symbol
                    break
            if outputSymbol is None:
                errorMessage = _(
                    "An error occurred and prevented to retrieve the output symbols"
                )
                self.displayErrorMessage(errorMessage)
                return

            transition.addOutputSymbol(outputSymbol, probaOutputSymbol,
                                       timeOutputSymbol)

        # Add the transition
        startState.registerTransition(transition)

        # attach the transition to the grammar
        self.grammarController.getCurrentProject().getGrammar().getAutomata(
        ).addTransition(transition)
        self._view.destroy()
        self.grammarController.restart()
    def __init__(self, controller, idTransition):
        '''
        Constructor
        '''
        self.builder = Gtk.Builder()
        self.builder.add_from_file(
            os.path.join(ResourcesConfiguration.getStaticResources(), "ui",
                         "grammar",
                         "createSemiStochasticTransitionDialogs.glade"))

        self._getObjects(self.builder, [
            "createSemiStochasticTransitionDialog",
            "createSemiStochasticTransitionButton",
            "cancelSemiStochasticTransitionButton",
            "idSemiStochasticTransitionEntry",
            "nameSemiStochasticTransitionEntry",
            "startStateSemiStochasticTransitionComboBox",
            "endStateSemiStochasticTransitionComboBox",
            "inputSymbolSemiStochasticTransitionComboBox",
            "errorSemiStochasticTransitionImage",
            "errorSemiStochasticTransitionLabel", "symbolListStore",
            "stateListStore", "outputSymbolListStore",
            "outputSymbolsListStore",
            "outputSymbolsSemiStochasticTransitionTreeview",
            "outputSymbolSemiStochasticTransitionComboBox",
            "outputSymbolsSemiStochasticTransitionComboBox",
            "outputSymbolProbabilitySemiStochasticTransitionEntry",
            "outputSymbolTimeSemiStochasticTransitionEntry",
            "removeOutputSymbolSemiStochasticTransitionButton",
            "addOutputSymbolSemiStochasticTransitionButton"
        ])
        self.controller = controller
        self.builder.connect_signals(self.controller)

        # Configure the current id of the new transition
        self.idSemiStochasticTransitionEntry.set_text(str(idTransition))
        self.idSemiStochasticTransitionEntry.set_sensitive(False)

        # Retrieves the list of states and of input symbols
        states = []
        inputSymbols = [EmptySymbol(), UnknownSymbol()]
        currentProject = self.controller.grammarController.getCurrentProject()
        if currentProject is not None:
            automata = currentProject.getGrammar().getAutomata()
            if automata is not None:
                states.extend(automata.getStates())
            vocabulary = currentProject.getVocabulary()
            if vocabulary is not None:
                inputSymbols.extend(vocabulary.getSymbols())

        self.stateListStore.clear()
        # Configure the list of states
        for state in states:
            i = self.stateListStore.append()
            self.stateListStore.set(i, 0, str(state.getID()))
            self.stateListStore.set(i, 1, state.getName())

        self.symbolListStore.clear()
        # Configure the list of input symbols
        for symbol in inputSymbols:
            i = self.symbolListStore.append()
            self.symbolListStore.set(i, 0, str(symbol.getID()))
            self.symbolListStore.set(i, 1, symbol.getName())