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
class NetworkOracle(threading.Thread):

    def __init__(self, communicationChannel, isMaster):
        threading.Thread.__init__(self)
        # create logger with the given configuration
        self.log = logging.getLogger('netzob.Inference.Grammar.Oracle.NetworkOracle.py')
        self.communicationChannel = communicationChannel
        self.isMaster = isMaster

    def setMMSTD(self, mmstd):
        self.mmstd = mmstd

    def run(self):
        self.log.info("Start the network oracle based on given MMSTD")

        # Create a new and clean 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
        self.oracle = MMSTDVisitor("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 stop(self):
        self.log.info("Stop the network oracle")
        self.oracle.stop()

    def hasFinish(self):
        return not self.oracle.isActive()

    def getGeneratedInputSymbols(self):
        symbols = []
        abstractionLayer = self.oracle.getAbstractionLayer()
        for i in abstractionLayer.getGeneratedInputSymbols():
            symbols.append(DictionarySymbol(i))
        return symbols

    def getGeneratedOutputSymbols(self):
        symbols = []
        abstractionLayer = self.oracle.getAbstractionLayer()
        for o in abstractionLayer.getGeneratedOutputSymbols():
            symbols.append(DictionarySymbol(o))
        return symbols

    def getResults(self):
        symbols = []
        # Retrieve all the IO from the abstraction layer
        abstractionLayer = self.oracle.getAbstractionLayer()
        print "Abstraction layer = " + str(abstractionLayer)
        for io in abstractionLayer.getGeneratedInputAndOutputsSymbols():
            symbols.append(DictionarySymbol(io))
        return symbols
Example #4
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")
Example #5
0
 def test_SimpleDynamic(self):
     actorGrammar = "simple_dynamic.xml"
     actorIP = "localhost"
     actorPort = random.randint(9000, 9999)
     actorNetworkProtocol = "TCP"
     
     isMaster = False
     
     serverName = "Server"
     clientName = "Client"
     
     # Create a network server
     grammar_directory = ConfigurationParser().get("automata", "path") 
     xmlFile = os.path.join(grammar_directory, actorGrammar)
     tree = ElementTree.ElementTree()
     tree.parse(xmlFile)
     # Load the automata based on its XML definition
     automata = MMSTDXmlParser.MMSTDXmlParser.loadFromXML(tree.getroot())
         
     # Create the network layer
     communicationChannel = NetworkServer.NetworkServer(actorIP, actorNetworkProtocol, actorPort)
     
     # Create the abstraction layer for this connection
     abstractionLayer = AbstractionLayer(communicationChannel, automata.getDictionary())
     
     # And we create an MMSTD visitor for this
     server = MMSTDVisitor(serverName, automata, isMaster, abstractionLayer) 
     server.run()     
     
     time.sleep(3)
     
     # CREATE CLIENT 1
     
     # Now we execute a client
     automataClient = MMSTDXmlParser.MMSTDXmlParser.loadFromXML(tree.getroot())
         
     # Create the network layer
     communicationChannelClient = NetworkClient.NetworkClient(actorIP, actorNetworkProtocol, actorPort)
     
     # Create the abstraction layer for this connection
     abstractionLayerClient = AbstractionLayer(communicationChannelClient, automataClient.getDictionary())
     
     # And we create an MMSTD visitor for this
     client = MMSTDVisitor(clientName, automataClient, not isMaster, abstractionLayerClient) 
     client.run()     
        
     time.sleep(20)
     
     server.stop()
Example #6
0
class TCPConnectionHandler(SocketServer.BaseRequestHandler):

    def __init__(self, request, client_address, server):
        server.allow_reuse_address = True
        SocketServer.BaseRequestHandler.__init__(self, request, client_address, server)
        self.subVisitor = None

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

        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)

        # We create an instantiated network server
        instanciatedNetworkServer = InstanciatedNetworkServer(self.request)

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

        # And we create an MMSTD visitor for this
        self.subVisitor = MMSTDVisitor("Instance-" + str(uuid.uuid4()), 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 #7
0
    def handle(self):

        self.server.notifyAClientIsConnected()

        self.log = logging.getLogger('netzob.Common.MMSTD.Actors.Network.NetworkServer_ConnectionHandler.py')
        self.log.info("A client has just initiated a connection on the server.")

        # Create the input and output abstraction layer
        abstractionLayer = AbstractionLayer(self.rfile, self.wfile, self.server.getModel().getVocabulary(), Memory(self.server.getModel().getVocabulary().getVariables()), self.server.getCBInputSymbol(), self.server.getCBOutputSymbol())

        # Initialize a dedicated automata and creates a visitor
        modelVisitor = MMSTDVisitor(self.server.getModel(), self.server.isMaster(), abstractionLayer)
        self.log.info("An MMSTDVistor has been instantiated and assigned to the current network client.")
        modelVisitor.start()

        # save it
        self.server.addGeneratedInstance(modelVisitor)

        while (modelVisitor.isAlive()):
            ready = select.select([self.request], [], [], 1)
            time.sleep(0.1)

        self.server.notifyAClientIsDisconnected()
Example #8
0
    def run(self):
        self.log.info("Start the network oracle based on given MMSTD")

        # Create a new and clean 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
        self.oracle = MMSTDVisitor("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")
Example #9
0
    def loadSimulator(xmlRoot, namespace, version, automata, vocabulary):
        if version == "0.1":
            simulator = None
            actors = []

            if xmlRoot.find("{" + namespace + "}actors") is not None:
                xmlActors = xmlRoot.find("{" + namespace + "}actors")
                for xmlActor in xmlActors.findall("{" + namespace + "}actor"):
                    actor = MMSTDVisitor.loadFromXML(xmlActor, namespace, version, automata, vocabulary)
                    if actor is None:
                        logging.warn("An error occurred and prevented to load the actor.")
                    else:
                        actors.append(actor)

            simulator = Simulator()
            simulator.setActors(actors)
            return simulator
        return None
Example #10
0
class NetworkOracle(threading.Thread):
    def __init__(self, communicationChannel, isMaster):
        threading.Thread.__init__(self)
        # create logger with the given configuration
        self.log = logging.getLogger(
            'netzob.Inference.Grammar.Oracle.NetworkOracle.py')
        self.communicationChannel = communicationChannel
        self.isMaster = isMaster

    def setMMSTD(self, mmstd):
        self.mmstd = mmstd

    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 stop(self):
        self.log.info("Stop the network oracle")
        self.oracle.stop()

    def hasFinish(self):
        return not self.oracle.isActive()

    def getGeneratedInputSymbols(self):
        symbols = []
        abstractionLayer = self.oracle.getAbstractionLayer()
        for i in abstractionLayer.getGeneratedInputSymbols():
            symbols.append(DictionarySymbol(i))
        return symbols

    def getGeneratedOutputSymbols(self):
        symbols = []
        abstractionLayer = self.oracle.getAbstractionLayer()
        for o in abstractionLayer.getGeneratedOutputSymbols():
            symbols.append(DictionarySymbol(o))
        return symbols

    def getResults(self):
        symbols = []
        # Retrieve all the IO from the abstraction layer
        abstractionLayer = self.oracle.getAbstractionLayer()
        print "Abstraction layer = " + str(abstractionLayer)
        for io in abstractionLayer.getGeneratedInputAndOutputsSymbols():
            symbols.append(DictionarySymbol(io))
        return symbols
    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()