Example #1
0
    def handle(self):

        self.server.notifyAClientIsConnected()

        self.log = logging.getLogger('netzob.Common.MMSTD.Actors.Network.NetworkServer_ConnectionHandler.py')

        if not self.server.isMultipleConnectionAllowed() and len(self.server.getGeneratedInstances()) > 0:
            return
        self.log.info("A client has just initiated a connection on the server.")
        self.server.notifyAClientIsConnected()

        initialState = self.server.getInitialState()
        vocabulary = self.server.getVocabulary()
        isMaster = self.server.isMaster()

        # we create a sub automata
        automata = MMSTD(initialState, vocabulary)

        # and duplicate the memory for this instance
        duplicatedMemory = self.server.getMemory().duplicate()

        # set client IP and Port source as the target IP:Port through memory
        targetIP = self.client_address[0]
        targetPort = self.client_address[1]
        self.server.setTargetIP(targetIP)
        self.server.setTargetPort(targetPort)

        # We create an instantiated network server
        instanciatedNetworkServer = InstanciatedNetworkServer(uuid.uuid4(), duplicatedMemory, "UDP", self.request, self.server.getBindIP(), self.server.getBindPort(), self.server.getTargetIP(), self.server.getTargetPort())

        # Create the input and output abstraction layer
        abstractionLayer = AbstractionLayer(instanciatedNetworkServer, vocabulary, Memory(), self.server.getCBInputSymbol(), self.server.getCBOutputSymbol())
        # abstractionLayer = AbstractionLayer(instanciatedNetworkServer, vocabulary, Memory(vocabulary.getVariables()), self.server.getCBInputSymbol(), self.server.getCBOutputSymbol())

        # And we create an MMSTD visitor for this
        anID = str(uuid.uuid4())
        self.subVisitor = MMSTDVisitor(anID, "Instance-" + anID, automata, isMaster, abstractionLayer)

        self.log.info("An MMSTDVistor has been instantiated and assigned to the current network client.")
        self.subVisitor.start()

        # save it
        self.server.addGeneratedInstance(self.subVisitor)

        finish = not self.subVisitor.isAlive()

        while (not finish):
            try:
                ready = select.select([self.request[1]], [], [], 1)
                time.sleep(0.1)
                finish = not self.subVisitor.isAlive()
            except:
                self.log.warn("The socket is not opened anymore!")
                finish = True

        self.subVisitor.join(None)

        self.server.notifyAClientIsDisconnected()

        self.log.warn("End of the execution of the UDP Connection handler")
Example #2
0
    def handle(self):
        self.log = logging.getLogger(__name__)

        if not self.server.isMultipleConnectionAllowed() and len(self.server.getGeneratedInstances()) > 0:
#            self.log.warn("We do not adress this client, another one already connected")
            return
        self.log.info("A client has just initiated a connection on the server.")
        self.server.notifyAClientIsConnected()

        initialState = self.server.getInitialState()
        vocabulary = self.server.getVocabulary()
        isMaster = self.server.isMaster()

        # we create a sub automata
        automata = MMSTD(initialState, vocabulary)

        # and duplicate the memory for this instance
        duplicatedMemory = self.server.getMemory().duplicate()

        # We create an instantiated network server
        instanciatedNetworkServer = InstanciatedNetworkServer(uuid.uuid4(), duplicatedMemory, "TCP", self.request, self.server.getBindIP(), self.server.getBindPort(), self.server.getTargetIP(), self.server.getTargetPort())

        # Create the input and output abstraction layer
        abstractionLayer = AbstractionLayer(instanciatedNetworkServer, vocabulary, Memory(), self.server.getCBInputSymbol(), self.server.getCBOutputSymbol())
        # abstractionLayer = AbstractionLayer(instanciatedNetworkServer, vocabulary, Memory(vocabulary.getVariables()), self.server.getCBInputSymbol(), self.server.getCBOutputSymbol())

        # And we create an MMSTD visitor for this
        anID = str(uuid.uuid4())
        self.subVisitor = MMSTDVisitor(anID, "Instance-" + anID, automata, isMaster, abstractionLayer)

        self.log.info("An MMSTDVistor has been instantiated and assigned to the current network client.")
        self.subVisitor.start()

        # save it
        self.server.addGeneratedInstance(self.subVisitor)

        finish = not self.subVisitor.isAlive()

        while (not finish):
            try:
                ready = select.select([self.request], [], [], 1)
                time.sleep(0.1)
                finish = not self.subVisitor.isAlive()
            except:
                self.log.warn("The socket is not anymore opened !")
                finish = True
#        instanciatedNetworkServer.close()

        self.subVisitor.join(None)

        self.server.notifyAClientIsDisconnected()
#        self.server.shutdown_request(self.request)
#        self.server.close_request(self.request)
#        self.server.shutdown()

        self.log.warn("End of the execution of the TCP Connection handler")
Example #3
0
    def toMMSTD(self, dictionary, isMaster):
        # We create an MMSTD which will submit the following symbols
        generatedStates = []

        # Create the transition which opens the connection
        rootState = NormalState(0, "State 0")
        generatedStates.append(rootState)
        initialState = NormalState(1, "State 1")
        generatedStates.append(initialState)
        openingTransition = OpenChannelTransition(0, "Connection", rootState,
                                                  initialState, 15000, 3)
        rootState.registerTransition(openingTransition)
        previousState = initialState
        idState = 2

        for symbol in self.symbols:
            # we create the current state
            currentState = NormalState(idState, "State " + str(idState))
            generatedStates.append(currentState)
            # we create a normal transition between it and the previous state
            idTransition = idState - 1
            transition = SimpleTransition(idTransition,
                                          "Transition " + str(idTransition),
                                          previousState, currentState, 1000,
                                          symbol)
            previousState.registerTransition(transition)
            idState = idState + 1
            previousState = currentState

        if not isMaster:
            # We create the opening transition to listen for the first entry
            currentState = NormalState(idState, "State " + str(idState))
            generatedStates.append(currentState)
            transition = SimpleTransition(idState - 1,
                                          "Transition " + str(idState - 1),
                                          previousState, currentState, 1000,
                                          EmptySymbol())
            previousState.registerTransition(transition)
            previousState = currentState
            idState += 1

        # Create the transition which close the connection
        endState = NormalState(idState, "State " + str(idState))
        generatedStates.append(endState)
        closingTransition = CloseChannelTransition(idState - 1,
                                                   "Disconnection",
                                                   currentState, endState,
                                                   1000)
        currentState.registerTransition(closingTransition)

        mmstd = MMSTD(rootState, dictionary)
        for state in generatedStates:
            mmstd.addState(state)
        return mmstd
    def createButton_clicked_cb(self, event):
        currentProject = self.grammarController.getCurrentProject()

        """callback executed when the user clicks on the create button"""
        initialState = self._view.initialStateCheckButton.get_active()
        stateName = self._view.nameEntry.get_text()

        automata = currentProject.getGrammar().getAutomata()

        errorMessage = None
        # verify initialState is valid
        if not initialState and automata is None:
            errorMessage = _("The first created state must be an initial state")
            self.displayErrorMessage(errorMessage)
            return

        # verify the name of the state is unique
        found = False
        if automata is not None:
            for state in automata.getStates():
                if state.getName() == stateName:
                    found = True
                    break

        if found:
            errorMessage = _("A state already has this name, please specify another one")
            self.displayErrorMessage(errorMessage)
            return

        newState = NormalState(self.idState, stateName)
        if automata is None:
            automata = MMSTD(newState, currentProject.getVocabulary())
            currentProject.getGrammar().setAutomata(automata)

        automata.addState(newState)
        self._view.destroy()
        self.grammarController.restart()
Example #5
0
    def computeAutomata(self):
        wordAndStates = []
        startState = None
        idState = 0
        idTransition = 0
        states = []

        self.log.info("Compute the automata...")

        # Create the states of the automata
        uniqueRowsInS = self.getUniqueRowsInS()
        for (w, r) in uniqueRowsInS:
            self.log.info("The row with word {0} is unique !".format(str(w)))
            # We create a State for each unique row
            nameState = self.appendValuesInRow(r)
            self.log.info("Create state: {0}".format(nameState))
            currentState = NormalState(idState, nameState)
            states.append(currentState)
            wordAndStates.append((w, currentState))
            # Is it the starting state (wordS = [EmptySymbol])
            if startState is None and w == MembershipQuery([EmptySymbol()]):
                startState = currentState
                self.log.info("Its the starting state")

            idState = idState + 1

        self.log.debug("Create the transition of the automata")
        # Create the transitions of the automata
        for (word, state) in wordAndStates:
            self.log.debug("Working on state: {0}".format(str(state.getName())))

            for symbol in self.initialD:
                # retrieve the value:
                dicValue = self.observationTable[symbol]
                value = dicValue[word]
                # search for the output state
                mq = word.getMQSuffixedWithMQ(symbol)
                self.log.debug("> What happen when we send " + str(symbol) + " after " + str(word))
                self.log.debug(">> " + str(mq))

                for wordSandSA in self.getSandSAWords():
                    self.log.info("IS " + str(wordSandSA) + " eq " + str(mq))
                    if wordSandSA == mq:
                        self.log.info("YES its equal")
                        rowOutputState = self.getRowOfObservationTable(wordSandSA)
                        outputStateName = self.appendValuesInRow(rowOutputState)
                        self.log.debug("rowOutputState = " + str(rowOutputState))
                        self.log.debug("outputStateName = " + str(outputStateName))

                        # search for the state having this name:
                        outputState = None
                        self.log.info("Search for the output state: {0}".format(outputStateName))
                        for (w2, s2) in wordAndStates:
                            if s2.getName() == outputStateName:
                                outputState = s2
                                self.log.info("  == " + str(s2.getName()))
                            else:
                                self.log.info("   != " + str(s2.getName()))

                        if outputState is not None:
                            inputSymbol = symbol.getSymbolsWhichAreNotEmpty()[0]

                            self.log.info("We create a transition from " + str(state.getName()) + "=>" + str(outputState.getName()))
                            self.log.info(" input: {0}".format(str(inputSymbol)))
                            self.log.info(" output: {0}".format(str(value)))

                            transition = SemiStochasticTransition(idTransition, "Transition " + str(idTransition), state, outputState, inputSymbol)
                            transition.addOutputSymbol(value, 100, 1000)
                            state.registerTransition(transition)

                            idTransition = idTransition + 1

                        else:
                            self.log.error("<!!> Impossible to retrieve the output state named " + str(s2.getName()))

        if startState is not None:
            self.log.info("An infered automata has been computed.")

            self.inferedAutomata = MMSTD(startState, self.dictionary)
            for state in states:
                self.inferedAutomata.addState(state)
            self.log.info(self.inferedAutomata.getDotCode())