def applySession(self, session):
        # retrieve the automata
        automata = self.project.getGrammar().getAutomata()

        self.log.debug("automata: %s" % automata.getDotCode())

        if automata is None:
            self.log.warn("Cannot apply a session on the current automata because it doesn't exist")
            return None

        difference = None

        # Configure the role-play environment
        # with :
        #  - a memory
        memory = Memory()
        # memory = Memory(None)
        #  - an abstraction layer
        abstractionLayer = AbstractionLayer(None, self.project.getVocabulary(), memory, None, None)

        currentState = automata.getInitialState()
        # We execute the opening transition
        if len(currentState.getTransitions()) == 1 and currentState.getTransitions()[0].getType() == OpenChannelTransition.TYPE:
            currentState = currentState.getTransitions()[0].getOutputState()

        isInput = True
        for message in session.getMessages():
            self.log.debug("Inject message: %s" % (message.getData()))
            # we abstract the message
            symbol = abstractionLayer.abstract(TypeConvertor.netzobRawToBitArray(str(message.getData())))
            if isInput:
                # We simulate the reception of the message
                #  - verify its a valid input symbol
                #  - find out the associated transition
                currentTransition = None
                for transition in currentState.getTransitions():
                    if transition.getInputSymbol() == symbol:
                        currentTransition = transition
                        break
                if currentTransition is None:
                    self.log.warn("Input symbol %s doesn't match any existing transition in current state %s" % (symbol.getName(), currentState.getName()))
                    self.log.warn("We forget this message.")
                else:
                    self.log.debug("Input symbol %s matchs the transition %s from state %s" % (symbol.getName(), currentTransition.getName(), currentState.getName()))
                    isInput = False
            else:
                # We simulate emiting the message
                #  - we just verify the symbol matches available output message in current transition
                found = False
                for (outputSymbol, probability, time) in currentTransition.getOutputSymbols():
                    if symbol.getID() == outputSymbol.getID():
                        found = True
                        isInput = True
                        currentState = currentTransition.getOutputState()
                        break

                if not found:
                    self.log.info("A difference has been found, symbol %s is not an output symbol of transition %s" % (symbol.getName(), currentTransition.getName()))
                    return (currentTransition, symbol)
        return difference
    def displaySession(self, session):
        memory = Memory(None)
        #  - an abstraction layer
        abstractionLayer = AbstractionLayer(None, self.project.getVocabulary(), memory, None, None)
        symbols = []
        for message in session.getMessages():
            symbols.append(abstractionLayer.abstract(TypeConvertor.netzobRawToBitArray(str(message.getData()))))

        for symbol in symbols:
            self.log.debug("- %s" % symbol.getName())
Ejemplo n.º 3
0
    def getOutputTrace(self, state, symbols):
        communicationLayer = SimpleCommunicationLayer(symbols, [], self.vocabulary, Memory(self.vocabulary.getVariables()))
        abstractionLayer = AbstractionLayer(communicationLayer, self.vocabulary, Memory(self.vocabulary.getVariables()))
        for i in range(0, len(symbols)):
            if state != None:
                state = state.executeAsClient(abstractionLayer)
        outputMessages = abstractionLayer.getOutputMessages()
        generatedSymbols = []
        for (sendingTime, strMessage, symbol) in outputMessages:
            generatedSymbols.append(symbol)

        return (generatedSymbols, state)
    def displaySession(self, session):
        memory = Memory()
        # memory = Memory(None)
        #  - an abstraction layer
        abstractionLayer = AbstractionLayer(None, self.project.getVocabulary(),
                                            memory, None, None)
        symbols = []
        for message in session.getMessages():
            symbols.append(
                abstractionLayer.abstract(
                    TypeConvertor.netzobRawToBitArray(str(message.getData()))))

        for symbol in symbols:
            self.log.debug("- %s" % symbol.getName())
Ejemplo n.º 5
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")
Ejemplo n.º 6
0
    def getOutputTrace(self, state, symbols):
        communicationLayer = SimpleCommunicationLayer(uuid.uuid4(), symbols,
                                                      [], self.vocabulary,
                                                      Memory())
        abstractionLayer = AbstractionLayer(communicationLayer,
                                            self.vocabulary, Memory())
        # communicationLayer = SimpleCommunicationLayer(symbols, [], self.vocabulary, Memory(self.vocabulary.getVariables()))
        # abstractionLayer = AbstractionLayer(communicationLayer, self.vocabulary, Memory(self.vocabulary.getVariables()))
        for i in range(0, len(symbols)):
            if state is not None:
                state = state.executeAsClient(abstractionLayer)
        outputMessages = abstractionLayer.getOutputMessages()
        generatedSymbols = []
        for (sendingTime, strMessage, symbol) in outputMessages:
            generatedSymbols.append(symbol)

        return (generatedSymbols, state)
Ejemplo n.º 7
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")
Ejemplo n.º 8
0
    def loadFromXML(xmlRoot, namespace, version, automata, vocabulary):
        if version == "0.1":

            id = xmlRoot.get('id')
            name = xmlRoot.get('name')
            initiator = TypeConvertor.str2bool(xmlRoot.get('initiator'))

            abstractionLayer = None
            if xmlRoot.find("{" + namespace + "}abstractionLayer") is not None:
                abstractionLayer = AbstractionLayer.loadFromXML(xmlRoot.find("{" + namespace + "}abstractionLayer"), namespace, version, vocabulary)

            return MMSTDVisitor(id, name, automata, initiator, abstractionLayer)

        return None
Ejemplo n.º 9
0
    def loadFromXML(xmlRoot, namespace, version, automata, vocabulary):
        if version == "0.1":

            id = xmlRoot.get('id')
            name = xmlRoot.get('name')
            initiator = TypeConvertor.str2bool(xmlRoot.get('initiator'))

            abstractionLayer = None
            if xmlRoot.find("{" + namespace + "}abstractionLayer") is not None:
                abstractionLayer = AbstractionLayer.loadFromXML(
                    xmlRoot.find("{" + namespace + "}abstractionLayer"),
                    namespace, version, vocabulary)

            return MMSTDVisitor(id, name, automata, initiator,
                                abstractionLayer)

        return None
Ejemplo n.º 10
0
    def run(self):
        self.log.info("Start the network oracle based on given MMSTD")

        # Create a new and clean memory
        memory = Memory()
        # memory = Memory(self.mmstd.getVocabulary().getVariables())
        memory.createMemory()
        # Create the abstraction layer for this connection
        abstractionLayer = AbstractionLayer(self.communicationChannel,
                                            self.mmstd.getVocabulary(), memory)

        # And we create an MMSTD visitor for this
        anID = str(uuid.uuid4())
        self.oracle = MMSTDVisitor(anID, "MMSTD-NetworkOracle", self.mmstd,
                                   self.isMaster, abstractionLayer)
        self.oracle.start()

        while (self.oracle.isAlive()):
            time.sleep(0.01)

        self.log.warn("The network ORACLE has finished")
    def applySession(self, session):
        # retrieve the automata
        automata = self.project.getGrammar().getAutomata()

        self.log.debug("automata: %s" % automata.getDotCode())

        if automata is None:
            self.log.warn(
                "Cannot apply a session on the current automata because it doesn't exist"
            )
            return None

        difference = None

        # Configure the role-play environment
        # with :
        #  - a memory
        memory = Memory()
        # memory = Memory(None)
        #  - an abstraction layer
        abstractionLayer = AbstractionLayer(None, self.project.getVocabulary(),
                                            memory, None, None)

        currentState = automata.getInitialState()
        # We execute the opening transition
        if len(currentState.getTransitions()
               ) == 1 and currentState.getTransitions()[0].getType(
               ) == OpenChannelTransition.TYPE:
            currentState = currentState.getTransitions()[0].getOutputState()

        isInput = True
        for message in session.getMessages():
            self.log.debug("Inject message: %s" % (message.getData()))
            # we abstract the message
            symbol = abstractionLayer.abstract(
                TypeConvertor.netzobRawToBitArray(str(message.getData())))
            if isInput:
                # We simulate the reception of the message
                #  - verify its a valid input symbol
                #  - find out the associated transition
                currentTransition = None
                for transition in currentState.getTransitions():
                    if transition.getInputSymbol() == symbol:
                        currentTransition = transition
                        break
                if currentTransition is None:
                    self.log.warn(
                        "Input symbol %s doesn't match any existing transition in current state %s"
                        % (symbol.getName(), currentState.getName()))
                    self.log.warn("We forget this message.")
                else:
                    self.log.debug(
                        "Input symbol %s matchs the transition %s from state %s"
                        % (symbol.getName(), currentTransition.getName(),
                           currentState.getName()))
                    isInput = False
            else:
                # We simulate emiting the message
                #  - we just verify the symbol matches available output message in current transition
                found = False
                for (outputSymbol, probability,
                     time) in currentTransition.getOutputSymbols():
                    if symbol.getID() == outputSymbol.getID():
                        found = True
                        isInput = True
                        currentState = currentTransition.getOutputState()
                        break

                if not found:
                    self.log.info(
                        "A difference has been found, symbol %s is not an output symbol of transition %s"
                        % (symbol.getName(), currentTransition.getName()))
                    return (currentTransition, symbol)
        return difference
    def createButton_clicked_cb(self, event):
        """callback executed when the user clicks on the create button"""

        actorName = self._view.nameEntry.get_text()
        if actorName is None or len(actorName) == 0:
            errorMessage = _("Give a name to the actor")
            self.displayErrorMessage(errorMessage)
            return

        # verify the name is unique
        found = False
        for actor in self.simulatorController.getCurrentProject().getSimulator(
        ).getActors():
            if actor.getName() == actorName:
                found = True
                break

        if found:
            errorMessage = _("An actor already has this name.")
            self.displayErrorMessage(errorMessage)
            return

        # initiator
        initiator = self._view.initiatorCheckButton.get_active()

        # Create the Channel

        # retrieve the type (SERVER or CLIENT)
        typeActorStr = self._view.typeComboBoxText.get_active_text()
        if typeActorStr is None:
            errorMessage = _("Specify the type of the actor.")
            self.displayErrorMessage(errorMessage)
            return

        actorIsClient = False
        if typeActorStr == _("CLIENT"):
            actorIsClient = True

        # retrieve the L4 protocol
        l4Protocol = self._view.l4ProtocolComboBoxText.get_active_text()
        if l4Protocol is None or (l4Protocol != "TCP" and l4Protocol != "UDP"):
            errorMessage = _(
                "Only UDP and TCP layer 4 protocols are supported.")
            self.displayErrorMessage(errorMessage)
            return

        # retrieve IP and Ports
        bindIP = self._view.bindIPEntry.get_text()
        bindPort = self._view.bindPortEntry.get_text()
        if bindPort is not None and len(bindPort) > 0:
            try:
                bindPort = int(bindPort)
            except:
                bindPort = -1

            if bindPort <= 0:
                errorMessage = _("Specify a valid bind port (int>0)")
                self.displayErrorMessage(errorMessage)
                return
        else:
            bindPort = None

        targetIP = self._view.targetIPEntry.get_text()
        targetPort = self._view.targetPortEntry.get_text()
        if targetPort is not None and len(targetPort) > 0:
            try:
                targetPort = int(targetPort)
            except:
                targetPort = -1

            if targetPort <= 0:
                errorMessage = _("Specify a valid target port (int>0)")
                self.displayErrorMessage(errorMessage)
                return
        else:
            targetPort = None

        communicationChannel = None
        idChannel = str(uuid.uuid4())

        # Initialize a memory with communication channels variables
        memory = Memory()

        if actorIsClient:
            # Create a Client Network Actor
            # target IP and target Port must be specified !
            if targetIP is None or len(targetIP) == 0:
                errorMessage = _("A network client requires a target IP.")
                self.displayErrorMessage(errorMessage)
                return

            if targetPort is None:
                errorMessage = _("A network client requires a target port.")
                self.displayErrorMessage(errorMessage)
                return

            communicationChannel = NetworkClient(idChannel, memory, l4Protocol,
                                                 bindIP, bindPort, targetIP,
                                                 targetPort)
        else:
            # Create a Server Network Actor
            # bind IP and bind Port must be specified !
            if bindIP is None or len(bindIP) == 0:
                errorMessage = _("A network server requires a bind IP.")
                self.displayErrorMessage(errorMessage)
                return

            if bindPort is None:
                errorMessage = _("A network server requires a bind port.")
                self.displayErrorMessage(errorMessage)
                return

            communicationChannel = NetworkServer(idChannel, memory, l4Protocol,
                                                 bindIP, bindPort, targetIP,
                                                 targetPort)

        if communicationChannel is not None and memory is not None:
            vocabulary = self.simulatorController.getCurrentProject(
            ).getVocabulary()
            grammar = self.simulatorController.getCurrentProject().getGrammar()

            # Create the abstraction layer
            abstractionLayer = AbstractionLayer(communicationChannel,
                                                vocabulary, memory)

            # Create the MMSTD Visitor
            actor = MMSTDVisitor(self.idActor, actorName,
                                 grammar.getAutomata(), initiator,
                                 abstractionLayer)

            # Register the new actor
            self.simulatorController.getCurrentProject().getSimulator(
            ).addActor(actor)

        self._view.destroy()
        self.simulatorController.restart()