Beispiel #1
0
    def execute(self):
        """Execute the alignment of data following specified field
        """
        if self.data is None:
            raise TypeError("Data cannot be None")
        if self.field is None:
            raise TypeError("Field cannot be None")

        # Aligned messages are stored in a MatrixList for better display
        result = MatrixList()

        # We retrieve all the leaf fields of the root of the provided field
        rootLeafFields = self.__root._getLeafFields(depth=self.depth)

        # if self.__root != self.field:
        #     targetedFieldLeafFields = self.field._getLeafFields(depth=self.depth)
        # else:
        targetedFieldLeafFields = rootLeafFields

        result.headers = [str(field.name) for field in targetedFieldLeafFields]
        from netzob.Common.Models.Vocabulary.Domain.Parser.MessageParser import MessageParser
        for d in self.data:
            mp = MessageParser()
            # alignedMsg = mp.parseRaw(TypeConverter.convert(d, HexaString, Raw), targetedFieldLeafFields)
            alignedMsg = mp.parseRaw(d, targetedFieldLeafFields)

            alignedEncodedMsg = []
            for ifield, currentField in enumerate(targetedFieldLeafFields):

                # now we apply encoding and mathematic functions
                fieldValue = alignedMsg[ifield]

                if self.encoded and len(
                        currentField.encodingFunctions.values()) > 0:
                    for encodingFunction in currentField.encodingFunctions.values(
                    ):
                        fieldValue = encodingFunction.encode(fieldValue)
                else:
                    fieldValue = TypeConverter.convert(fieldValue, BitArray,
                                                       Raw)

                if currentField in self.field._getLeafFields(depth=self.depth):
                    alignedEncodedMsg.append(fieldValue)

            result.append(alignedEncodedMsg)

        return result
Beispiel #2
0
    def execute(self):
        """Execute the alignment of data following specified field
        """
        if self.data is None:
            raise TypeError("Data cannot be None")
        if self.field is None:
            raise TypeError("Field cannot be None")

        # Aligned messages are stored in a MatrixList for better display
        result = MatrixList()        

        # We retrieve all the leaf fields of the root of the provided field
        rootLeafFields = self.__root._getLeafFields(depth=self.depth)
            
        # if self.__root != self.field:
        #     targetedFieldLeafFields = self.field._getLeafFields(depth=self.depth)
        # else:
        targetedFieldLeafFields = rootLeafFields

        result.headers = [str(field.name) for field in targetedFieldLeafFields]
        from netzob.Common.Models.Vocabulary.Domain.Parser.MessageParser import MessageParser
        for d in self.data:
            mp = MessageParser()
            # alignedMsg = mp.parseRaw(TypeConverter.convert(d, HexaString, Raw), targetedFieldLeafFields)
            alignedMsg = mp.parseRaw(d, targetedFieldLeafFields)            

            alignedEncodedMsg = []
            for ifield, currentField in enumerate(targetedFieldLeafFields):

                # now we apply encoding and mathematic functions
                fieldValue = alignedMsg[ifield]
            
                if self.encoded and len(currentField.encodingFunctions.values()) > 0:
                    for encodingFunction in currentField.encodingFunctions.values():
                        fieldValue = encodingFunction.encode(fieldValue)
                else:
                    fieldValue = TypeConverter.convert(fieldValue, BitArray, Raw)

                if currentField in self.field._getLeafFields(depth=self.depth):
                    alignedEncodedMsg.append(fieldValue)

            result.append(alignedEncodedMsg)

        return result
Beispiel #3
0
 def __init__(self, channel, symbols):
     self.channel = channel
     self.symbols = symbols
     self.memory = Memory()
     self.specializer = MessageSpecializer(memory = self.memory)
     self.parser = MessageParser(memory = self.memory)
Beispiel #4
0
class AbstractionLayer(object):
    """An abstraction layer specializes a symbol into a message before
    emitting it and on the other way, abstracts a received message
    into a symbol.

    >>> from netzob.all import *
    >>> symbol = Symbol([Field("Hello Zoby !")], name = "Symbol_Hello")

    >>> channelIn = UDPServer(localIP="127.0.0.1", localPort=8889)
    >>> abstractionLayerIn = AbstractionLayer(channelIn, [symbol])
    >>> abstractionLayerIn.openChannel()

    >>> channelOut = UDPClient(remoteIP="127.0.0.1", remotePort=8889)
    >>> abstractionLayerOut = AbstractionLayer(channelOut, [symbol])
    >>> abstractionLayerOut.openChannel()

    >>> abstractionLayerOut.writeSymbol(symbol)
    >>> (receivedSymbol, receivedMessage) = abstractionLayerIn.readSymbol()
    >>> print receivedSymbol.name
    Symbol_Hello
    >>> print receivedMessage
    Hello Zoby !

    """

    def __init__(self, channel, symbols):
        self.channel = channel
        self.symbols = symbols
        self.memory = Memory()
        self.specializer = MessageSpecializer(memory = self.memory)
        self.parser = MessageParser(memory = self.memory)

    @typeCheck(Symbol)
    def writeSymbol(self, symbol):
        """Write the specified symbol on the communication channel
        after specializing it into a contextualized message.

        :param symbol: the symbol to write on the channel
        :type symbol: :class:`netzob.Common.Models.Vocabulary.Symbol.Symbol`
        :raise TypeError if parameter is not valid and Exception if an exception occurs.
        """
        if symbol is None:
            raise TypeError("The symbol to write on the channel cannot be None")

        self._logger.info("Going to specialize symbol: '{0}' (id={1}).".format(symbol.name, symbol.id))
        
        dataBin = self.specializer.specializeSymbol(symbol).generatedContent

        self.memory = self.specializer.memory
        self.parser.memory = self.memory
        data = TypeConverter.convert(dataBin, BitArray, Raw)
        symbol.messages.append(RawMessage(data))

        self._logger.info("Data generated from symbol '{0}':\n{1}.".format(symbol.name, symbol))
        
        self._logger.info("Going to write to communication channel...")
        self.channel.write(data)
        self._logger.info("Writing to commnunication channel donne..")

    @typeCheck(int)
    def readSymbol(self, timeout=EmptySymbol.defaultReceptionTimeout()):
        """Read from the abstraction layer a message and abstract it
        into a message.
        The timeout parameter represents the amount of time (in millisecond) above which
        no reception of a message triggers the reception of an  :class:`netzob.Common.Models.Vocabulary.EmptySymbol.EmptySymbol`. If timeout set to None
        or to a negative value means it always wait for the reception of a message.

        :keyword timeout: the time above which no reception of message triggers the reception of an :class:`netzob.Common.Models.Vocabulary.EmptySymbol.EmptySymbol`
        :type timeout: :class:`int`
        :raise TypeError if the parameter is not valid and Exception if an error occurs.
        """
        self._logger.info("Going to read from communication channel...")
        data = self.channel.read(timeout = timeout)
        self._logger.info("Received : {}".format(repr(data)))
        symbol = None
        
        for potential in self.symbols:
            try:
                self.parser.parseMessage(RawMessage(data), potential)
                symbol = potential
                self.memory = self.parser.memory
                self.specializer.memory = self.memory
                break
            except Exception, e:
                symbol = None

                
        if symbol is None and len(data) > 0:
            symbol = UnknownSymbol()
        elif symbol is None and len(data) == 0:
            symbol = EmptySymbol()

        symbol.messages.append(RawMessage(data))

        self._logger.info("Received a message abstracted with symbol '{}' on communication channel:\n{}".format(symbol.name, symbol))
        return (symbol, data)