예제 #1
0
    def getExpectedTemplate(self,
                            tpl,
                            versionIp=None,
                            sourceIp=None,
                            destinationIp=None,
                            sourcePort=None,
                            destinationPort=None):
        """
		Return an expected template with ip and udp layers
		"""
        # prepare layers
        defaultVer = "%s" % self.cfg['sock-family']
        if versionIp is not None:
            defaultVer = versionIp
        layer_ip = AdapterIP.ip(source=sourceIp,
                                destination=destinationIp,
                                version=defaultVer)
        layer_udp = templates.udp(source=sourcePort,
                                  destination=destinationPort)
        layer_udp.addMore(more=tpl)

        # prepare template
        if self.cfg['agent-support']:
            layer_agent = TestTemplatesLib.TemplateLayer('AGENT')
            layer_agent.addKey(name='name', data=self.cfg['agent']['name'])
            layer_agent.addKey(name='type', data=self.cfg['agent']['type'])

        tpl = TestTemplatesLib.TemplateMessage()
        if self.cfg['agent-support']:
            tpl.addLayer(layer=layer_agent)
        tpl.addLayer(layer=layer_ip)
        tpl.addLayer(layer=layer_udp)
        return tpl
예제 #2
0
    def getExpectedTemplate(self,
                            tpl,
                            versionIp=None,
                            sourceIp=None,
                            destinationIp=None,
                            sourcePort=None,
                            destinationPort=None):
        """
		Return an expected template with ip and udp layers
		"""
        # prepare layers
        defaultVer = self.cfg['sock-family']
        if versionIp is not None:
            defaultVer = versionIp
        layer_ip = AdapterIP.ip(source=sourceIp,
                                destination=destinationIp,
                                version=defaultVer)
        layer_udp = templates.udp(source=sourcePort,
                                  destination=destinationPort)
        layer_udp.addMore(more=tpl)

        # prepare template
        tpl = TestTemplatesLib.TemplateMessage()
        tpl.addLayer(layer=layer_ip)
        tpl.addLayer(layer=layer_udp)
        return tpl
예제 #3
0
    def encapsule(self, ip_event, udp_event, src_ip=None, src_port=None):
        """
		"""
        # prepare layers
        src = self.sourceIp
        dst = self.cfg['dst-ip']
        srcP = self.sourcePort
        dstP = self.cfg['dst-port']
        if src_ip is not None:
            src = src_ip
            dst = self.sourceIp
        if src_port is not None:
            srcP = src_port
            dstP = self.sourcePort
        layer_ip = AdapterIP.ip(source=src,
                                destination=dst,
                                version="%s" % self.cfg['sock-family'],
                                more=ip_event)
        layer_udp = templates.udp(source=srcP, destination=dstP)
        layer_udp.addMore(more=udp_event)

        # prepare template
        if self.cfg['agent-support']:
            layer_agent = TestTemplatesLib.TemplateLayer('AGENT')
            layer_agent.addKey(name='name', data=self.cfg['agent']['name'])
            layer_agent.addKey(name='type', data=self.cfg['agent']['type'])

        tpl = TestTemplatesLib.TemplateMessage()
        if self.cfg['agent-support']:
            tpl.addLayer(layer=layer_agent)
        tpl.addLayer(layer=layer_ip)
        tpl.addLayer(layer=layer_udp)
        return tpl
예제 #4
0
	def onInactivityTimeout(self):
		"""
		"""
		tpl = TestTemplatesLib.TemplateMessage()
		tpl.addLayer( layer=AdapterIP.ip( more=AdapterIP.received() ) )
		tpl.addLayer( layer=templates.udp( more=templates.received() ) )
		self.onInactivity(lower=tpl)
예제 #5
0
    def encapsule(self, ip_event, udp_event, src_ip=None, src_port=None):
        """
		"""
        # prepare layers
        src = self.sourceIp
        srcP = self.sourcePort
        dst = ''
        dstP = ''
        if src_ip is not None:
            src = src_ip
            dst = self.sourceIp
        if src_port is not None:
            srcP = src_port
            dstP = self.sourcePort
        layer_ip = AdapterIP.ip(source=src,
                                destination=dst,
                                version=self.cfg['sock-family'],
                                more=ip_event)
        layer_udp = templates.udp(source=srcP, destination=dstP)
        layer_udp.addMore(more=udp_event)

        # prepare template
        tpl = TestTemplatesLib.TemplateMessage()
        tpl.addLayer(layer=layer_ip)
        tpl.addLayer(layer=layer_udp)
        return tpl
예제 #6
0
    def hasReceivedIcmpError(self, timeout=1.0):
        """
		Waits to receive "icmp error" event until the end of the timeout
		
		@param timeout: time max to wait to receive event in second (default=1s)
		@type timeout: float
		
		@return: an event matching with the template or None otherwise
		@rtype: templatemessage
		"""
        TestAdapterLib.check_timeout(caller=TestAdapterLib.caller(),
                                     timeout=timeout)

        # prepare the expected template
        expected = TestTemplatesLib.TemplateMessage()

        if self.cfg['agent-support']:
            layer_agent = TestTemplatesLib.TemplateLayer('AGENT')
            layer_agent.addKey(name='name', data=self.cfg['agent']['name'])
            layer_agent.addKey(name='type', data=self.cfg['agent']['type'])
            expected.addLayer(layer_agent)

        expected.addLayer(layer=templates.udp(more=templates.icmp_error()))

        # wait
        evt = self.received(expected=expected, timeout=timeout)
        if evt is None:
            return None
        return evt
예제 #7
0
    def onIcmpError(self, error):
        """
		"""
        ## TODO: version IP
        icmp = error.get('ICMP4')
        icmp_type = icmp.get('type')
        icmp_type_str = icmp_type.get('string')
        if icmp_type_str is None:
            icmp_type_str = 'Unknown'

        icmp_code = icmp.get('code')
        icmp_code_str = icmp_code.get('string')
        if icmp_code_str is None:
            icmp_code_str = 'Unknown'

        icmp_data = icmp.get('data')
        if isinstance(icmp_data, TestTemplatesLib.TemplateLayer):
            icmp_data = icmp_data.getName()

        # check if the response is for me ?
        if icmp_data[:64] == self.ip.getLast64bSent():
            tpl = TestTemplatesLib.TemplateMessage()
            tpl.addLayer(layer=templates.udp(more=templates.icmp_error(
                error=icmp_type_str, details=icmp_code_str)))
            if self.logEventReceived:
                self.logRecvEvent(shortEvt='icmp error', tplEvt=tpl)
예제 #8
0
    def hasReceivedIcmpError(self, timeout=1.0):
        """
		Waits to receive "icmp error" event until the end of the timeout
		
		@param timeout: time max to wait to receive event in second (default=1s)
		@type timeout: float
		
		@return: an event matching with the template or None otherwise
		@rtype: templatemessage
		"""
        if not (isinstance(timeout, int)
                or isinstance(timeout, float)) or isinstance(timeout, bool):
            raise TestAdapterLib.ValueException(
                TestAdapterLib.caller(),
                "timeout argument is not a float or integer (%s)" %
                type(timeout))

        # prepare the expected template
        expected = TestTemplatesLib.TemplateMessage()

        if self.cfg['agent-support']:
            layer_agent = TestTemplatesLib.TemplateLayer('AGENT')
            layer_agent.addKey(name='name', data=self.cfg['agent']['name'])
            layer_agent.addKey(name='type', data=self.cfg['agent']['type'])
            expected.addLayer(layer_agent)

        expected.addLayer(layer=templates.udp(more=templates.icmp_error()))

        # wait
        evt = self.received(expected=expected, timeout=timeout)
        if evt is None:
            return None
        return evt
예제 #9
0
    def decode(self, udp, ipSrc, ipDst):
        """
		"""
        udp_hdr = struct.unpack('!4H', udp[:UDP_LEN])

        ## source:  2 bytes
        src_port = udp_hdr[0]

        ## destination:  2 bytes
        dst_port = udp_hdr[1]

        ## length:  2 bytes
        lgth = udp_hdr[2]

        ## checksum:  2 bytes
        udp_sum = udp_hdr[3]
        udp_sum_hex = "0x%0.4X" % udp_sum

        ## extract data
        data_upper = udp[UDP_LEN:]

        # checksum is correct ?	optional for udp
        #		An all zero  transmitted checksum  value means that the transmitter  generated  no checksum  (for
        #		debugging or for higher level protocols that don't care).
        if udp_sum != 0:
            speudo_hdr = self.speudoHeader(ipSrc=ipSrc,
                                           ipDst=ipDst,
                                           udpLength=lgth)

            sum_computed = self.checksum.compute(
                data=''.join([speudo_hdr, udp]),
                checksum_offset=OFFSET_CHECKSUM_WITH_SPEUDO_HDR)
            sum_status = 'incorrect, should be 0x%0.4X' % sum_computed

            if udp_sum == sum_computed:
                sum_status = 'correct'
            self.debug('udp checksum computed')
        else:
            sum_status = "don't care"

        # Decode OK, create template
        udp_tpl = templates.udp(source=str(src_port),
                                destination=str(dst_port),
                                length=str(lgth),
                                sum=udp_sum_hex,
                                sum_status=sum_status,
                                sum_int=str(udp_sum),
                                data=data_upper,
                                data_size=len(data_upper))
        # add the raw data  to the layer
        udp_tpl.addRaw(udp[:UDP_LEN])

        # set summary
        summary = 'Port=%s>%s, Len=%s' % (src_port, dst_port, len(data_upper))
        #		if dst_port == self.srcPort:
        #			summary = 'Port=%s<%s, Len=%s' % (dst_port, src_port, len(data_upper))

        return udp_tpl, summary, data_upper
예제 #10
0
    def hasReceivedData(self,
                        timeout=1.0,
                        dstIp=None,
                        srcIp=None,
                        srcPort=None,
                        dstPort=None,
                        data=None):
        """
		Waits to receive "data" event until the end of the timeout
		
		@param timeout: time max to wait to receive event in second (default=1s)
		@type timeout: float
		
		@param dstIp: destination ip
		@type dstIp: none/string/operators
		
		@param srcIp: source ip
		@type srcIp: none/string/operators
		
		@param srcPort: source port
		@type srcPort: none/integer/operators

		@param dstPort: destination port
		@type dstPort: none/integer/operators
		
		@param data: upper data
		@type data: none/string/operators

		@return: an event matching with the template or None otherwise
		@rtype: templatemessage
		"""
        if not (isinstance(timeout, int)
                or isinstance(timeout, float)) or isinstance(timeout, bool):
            raise TestAdapterLib.ValueException(
                TestAdapterLib.caller(),
                "timeout argument is not a float or integer (%s)" %
                type(timeout))

        # prepare the expected template
        ether_tpl = AdapterEthernet.ethernet()
        expected = self.encapsule(layer=ether_tpl)

        ip_tpl = AdapterIP.ip(source=srcIp, destination=dstIp)
        expected.addLayer(ip_tpl)

        udp_tpl = templates.udp(source=srcPort, destination=dstPort, data=None)
        expected.addLayer(udp_tpl)
        # wait
        evt = self.received(expected=expected, timeout=timeout)
        if evt is None:
            return None
        return evt
예제 #11
0
    def sendData(self,
                 data,
                 destIp=None,
                 destPort=0,
                 srcPort=0,
                 totalLength=None,
                 checksum=None,
                 destMac=None):
        """
		Send data to the ip/port passed as argument
		
		@param data: data to send over udp
		@type data: string
		
		@param destIp: destination ip address
		@type destIp: none/integer
		
		@param destMac: destination mac address
		@type destMac: none/integer
		
		@param destPort: destination port
		@type destPort: integer
		
		@param srcPort: source port
		@type srcPort: integer
		
		@param totalLength: total length, auto computed if not provided
		@type totalLength: none/integer
		
		@param checksum: checksum, auto computed if not provided 
		@type checksum: integer
		"""
        try:
            if self.port2sniff == codec.ALL:
                src_port = int(srcPort)
            else:
                src_port = int(self.port2sniff)

            # add the separator
            data = self.addSeparator(data=data)

            layer_udp = templates.udp(source=src_port,
                                      destination=int(destPort),
                                      length=totalLength,
                                      sum=checksum,
                                      data=data)
        except Exception as e:
            raise TestAdapterLib.AdapterException(
                TestAdapterLib.caller(),
                'Cannot prepare udp template: %s' % str(e))
        else:
            # encode the template udp
            try:
                udp_pkt, summary = self.udpCodec.encode(
                    udp_tpl=layer_udp,
                    ipSrc=self.ip.getSourceIP(),
                    ipDst=destIp)
            except Exception as e:
                raise TestAdapterLib.AdapterException(
                    TestAdapterLib.caller(),
                    "Cannot encode udp data: %s" % str(e))
            else:
                # Send packet
                try:
                    lower = self.ip.sendDatagram(dstMac=destMac,
                                                 dstIp=destIp,
                                                 data=udp_pkt,
                                                 protocol=AdapterIP.UDP)
                except Exception as e:
                    raise TestAdapterLib.AdapterException(
                        TestAdapterLib.caller(),
                        "Unable to send udp data: %s" % str(e))
                else:
                    lower.addLayer(layer_udp)
                    if self.logEventSent:
                        layer_udp.addRaw(raw=udp_pkt)
                    else:
                        layer_udp.addRaw(raw=udp_pkt[:codec.UDP_LEN])
                    if self.logEventSent:
                        self.logSentEvent(shortEvt=summary, tplEvt=lower)

        return lower
예제 #12
0
    def onReceiving(self, data, fromAddr, toAddr, lower):
        """
		Function to overwrite
		Called on incoming data

		@param data: data received
		@type data: string
		
		@param lower: template data received
		@type lower: templatemessage
		"""
        # extract transport info
        self.lastActivity = time.time()
        srcIp, srcPort = fromAddr
        dstIp, dstPort = toAddr

        # the separator feature is disabled, to nothing
        if self.cfg['sep-disabled']:
            try:
                self.handleIncomingData(data=data, lower=lower)
            except Exception as e:
                self.error(
                    "on handle incoming udp data, upper layer problem: %s" %
                    str(e))
        else:
            # bufferize data
            if self.buf.has_key(fromAddr):
                self.buf[fromAddr] = ''.join([self.buf[fromAddr], data])
            else:
                self.buf[fromAddr] = data

            # split data with the separator
            datas = self.buf[fromAddr].split(self.cfg['sep-in'])
            for d in datas[:-1]:
                udp_data = d + self.cfg['sep-in']
                udp_data_size = len(udp_data)

                # construct high template and log it
                tpl = TestTemplatesLib.TemplateMessage()
                tpl.addLayer(
                    layer=AdapterIP.ip(source=srcIp,
                                       destination=dstIp,
                                       more=AdapterIP.received(),
                                       version=self.cfg['ip-version']))
                if self.logEventReceived:
                    udp_layer = templates.udp(
                        source=srcPort,
                        destination=dstPort,
                        more=templates.received(
                            data=udp_data, data_length=str(udp_data_size)))
                else:
                    udp_layer = templates.udp(
                        source=srcPort,
                        destination=dstPort,
                        more=templates.received(
                            data_length=str(udp_data_size)))
                tpl.addLayer(layer=udp_layer)

                if self.logEventReceived:
                    tpl.addRaw(raw=udp_data)
                    self.logRecvEvent(shortEvt='data reassembled', tplEvt=tpl)

                # handle data
                self.handleIncomingData(udp_data, lower=tpl)
            self.buf[fromAddr] = datas[-1]