示例#1
0
    def test_unpackMultiplePackets(self):
        sequencenum = 1011
        mypcap = pcap.Pcap("inetx_test.pcap")  # Read the pcap file
        mypcap.readGlobalHeader()
        while True:
            # Loop through the pcap file reading one packet at a time
            try:
                mypcaprecord = mypcap.readAPacket()
            except IOError:
                # End of file reached
                break

            ethpacket = SimpleEthernet.Ethernet()  # Create an Ethernet object
            ethpacket.unpack(mypcaprecord.packet
                             )  # Unpack the pcap record into the eth object
            ippacket = SimpleEthernet.IP()  # Create an IP packet
            ippacket.unpack(ethpacket.payload
                            )  # Unpack the ethernet payload into the IP packet
            udppacket = SimpleEthernet.UDP()  # Create a UDP packet
            udppacket.unpack(
                ippacket.payload)  # Unpack the IP payload into the UDP packet
            inetxpacket = inetx.iNetX()  # Create an iNetx object
            inetxpacket.unpack(
                udppacket.payload
            )  # Unpack the UDP payload into this iNetX object
            #print "INETX: StreamID ={:08X} Sequence = {:8d} PTP Seconds = {}".format(inetxpacket.streamid,inetxpacket.sequence,inetxpacket.ptptimeseconds)
            self.assertEquals(inetxpacket.sequence, sequencenum)
            sequencenum += 1
    def test_readFirstMPEGTS(self):
        '''
        Very simple test that reads a pcap file with mpegts packets.
        Takes the first packet in there and decoms the mpegts blocks
        Verifies each block in that first packet
        '''
        p = pcap.Pcap("mpegts_input.pcap")
        p.readGlobalHeader()
        mypcaprecord = p.readAPacket()

        ethpacket = SimpleEthernet.Ethernet()   # Create an Ethernet object
        ethpacket.unpack(mypcaprecord.packet)   # Unpack the pcap record into the eth object
        ippacket =  SimpleEthernet.IP()         # Create an IP packet
        ippacket.unpack(ethpacket.payload)      # Unpack the ethernet payload into the IP packet
        udppacket = SimpleEthernet.UDP()        # Create a UDP packet
        udppacket.unpack(ippacket.payload)      # Unpack the IP payload into the UDP packet
        inetxpacket = inetx.iNetX()             # Create an iNetx object
        inetxpacket.unpack(udppacket.payload)   # Unpack the UDP payload into this iNetX object

        mpegts = MPEGTS.MPEGTS()
        mpegts.unpack(inetxpacket.payload)
        self.assertEqual(mpegts.NumberOfBlocks(),7)
        self.assertFalse(mpegts.contunityerror)
        for packet_index in (range(7)):
            if packet_index == 0:
                self.assertEqual(mpegts.blocks[packet_index].pid,0)
                self.assertEqual(mpegts.blocks[packet_index].syncbyte,0x47)
            elif packet_index == 1:
                self.assertEqual(mpegts.blocks[packet_index].pid,4096)
                self.assertEqual(mpegts.blocks[packet_index].syncbyte,0x47)
            else:
                self.assertEqual(mpegts.blocks[packet_index].pid,256)
                self.assertEqual(mpegts.blocks[packet_index].syncbyte,0x47)
        p.close()
    def test_readAllMPEGTS(self):
        '''
        Reads the same mpeg ts file as previously but reads all the data
        in the file and checks for any continuity errors
        :return:
        '''
        p = pcap.Pcap("mpegts_input.pcap")
        p.readGlobalHeader()
        while True:
            # Loop through the pcap file reading one packet at a time
            try:
                mypcaprecord = p.readAPacket()
            except IOError:
                # End of file reached
                break

            ethpacket = SimpleEthernet.Ethernet()   # Create an Ethernet object
            ethpacket.unpack(mypcaprecord.packet)   # Unpack the pcap record into the eth object
            ippacket =  SimpleEthernet.IP()         # Create an IP packet
            ippacket.unpack(ethpacket.payload)      # Unpack the ethernet payload into the IP packet
            udppacket = SimpleEthernet.UDP()        # Create a UDP packet
            udppacket.unpack(ippacket.payload)      # Unpack the IP payload into the UDP packet
            inetxpacket = inetx.iNetX()             # Create an iNetx object
            inetxpacket.unpack(udppacket.payload)   # Unpack the UDP payload into this iNetX object
            mpegts = MPEGTS.MPEGTS()
            mpegts.unpack(inetxpacket.payload)
            self.assertEqual(mpegts.NumberOfBlocks(),7)
            self.assertFalse(mpegts.contunityerror)

        p.close()
示例#4
0
    def test_readFirstMPEGTS(self):
        '''
        Very simple test that reads a pcap file with mpegts packets.
        Takes the first packet in there and decoms the mpegts blocks
        Verifies each block in that first packet
        '''
        p = pcap.Pcap(os.path.join(THIS_DIR, "mpegts_input.pcap"))
        p._read_global_header()
        mypcaprecord = p[0]

        ethpacket = SimpleEthernet.Ethernet()   # Create an Ethernet object
        ethpacket.unpack(mypcaprecord.packet)   # Unpack the pcap record into the eth object
        ippacket =  SimpleEthernet.IP()         # Create an IP packet
        ippacket.unpack(ethpacket.payload)      # Unpack the ethernet _payload into the IP packet
        udppacket = SimpleEthernet.UDP()        # Create a UDP packet
        udppacket.unpack(ippacket.payload)      # Unpack the IP _payload into the UDP packet
        inetxpacket = inetx.iNetX()             # Create an iNetx object
        inetxpacket.unpack(udppacket.payload)   # Unpack the UDP _payload into this iNetX object

        mpegts = MPEGTS.MPEGTS()
        mpegts.unpack(inetxpacket.payload)
        self.assertEqual(mpegts.NumberOfBlocks(),7)
        self.assertFalse(mpegts.contunityerror)
        for packet_index in (list(range(7))):
            if packet_index == 0:
                self.assertEqual(mpegts.blocks[packet_index].pid,0)
                self.assertEqual(mpegts.blocks[packet_index].syncbyte,0x47)
            elif packet_index == 1:
                self.assertEqual(mpegts.blocks[packet_index].pid,4096)
                self.assertEqual(mpegts.blocks[packet_index].syncbyte,0x47)
            else:
                self.assertEqual(mpegts.blocks[packet_index].pid,256)
                self.assertEqual(mpegts.blocks[packet_index].syncbyte,0x47)
        p.close()
def pcap_to_ts(pcapfile,ts_file,udp_port=8010):
    '''
    Convert a pcap file to a TS file by extracting all data from a specified port
    :param mpegfile: str
    :param ts_file: str
    :param udp_port: int
    :return:
    '''

    mpegpcap = pcap.Pcap(pcapfile, mode='r')

    ts = open(ts_file, mode='wb')
    mpeghex = ""
    rec_count = 0

    for rec in mpegpcap:
        try:
            e = eth.Ethernet()
            e.unpack(rec.packet)
            i = eth.IP()
            i.unpack(e.payload)
            u = eth.UDP()
            u.unpack(i.payload)
            if u.dstport == udp_port:
                rec_count += 1
                inet = inetx.iNetX()
                inet.unpack(u.payload)
                mpegtspackets = mpegts.MPEGTS()
                mpegtspackets.unpack(inet.payload)
                for packet in mpegtspackets.blocks:
                    mpeghex += packet.payload
                ts.write(inet.payload)
        except:
            continue
示例#6
0
    def _readNextiNetXPacket(self):
        """This method will read the next iNetX packet one by one. It will raise an IOError when it hits
        the end of the file and n NoImplementedError when it hits packets that are not iNetx. It returns
        the ip, udp and inetx packets"""
        # already at the end of the file
        if self.bytesread >= self.filesize:
            raise IOError

        # otherwise pull our the PCAP header size. Should really push headersize to the object self
        pcapheader = self.fopen.read(Pcap.RECORD_HEADER_SIZE)
        (sec, usec, incl_len,
         orig_len) = struct.unpack(Pcap.RECORD_HEADER_FORMAT, pcapheader)

        # now we have a packet then lets deconstruct it. first read in the ethernet header and unpack it
        eth_header = SimpleEthernet.Ethernet(
            self.fopen.read(SimpleEthernet.Ethernet.HEADERLEN))

        # This is the most portable but as a quick hack I'm going
        # to ignore smoe packets. All non-IP packets for starter
        if eth_header.type != 2048:
            throwaway = self.fopen.read(orig_len -
                                        SimpleEthernet.Ethernet.HEADERLEN)
            self.bytesread += (orig_len + Pcap.RECORD_HEADER_SIZE)
            raise NotImplementedError

        # pull apart the other headers. Again I'm assuming all the IP packets
        # are udp packets
        ip_header = SimpleEthernet.IP(
            self.fopen.read(SimpleEthernet.IP.HEADERLEN))
        udp_header = SimpleEthernet.UDP(
            self.fopen.read(SimpleEthernet.UDP.HEADERLEN))

        # Lets create an iNetx packet then test if we are really dealing with an
        # inetx packet. Do this by testing the first 4 bytes which should be the control word
        CONTROLWORD_LEN = 4
        CONTROLWORD_STRING = struct.pack('>I', 0x11000000)
        inetx_packet = iNetX.iNetX()
        inetx_packet.packet = self.fopen.read(CONTROLWORD_LEN)

        # So are the first 4 bytes the control word
        if inetx_packet.packet != CONTROLWORD_STRING:
            # throw away the rest of the packet and bail out with an exception
            throwaway = self.fopen.read(orig_len -
                                        SimpleEthernet.Ethernet.HEADERLEN -
                                        SimpleEthernet.IP.HEADERLEN -
                                        SimpleEthernet.UDP.HEADERLEN -
                                        CONTROLWORD_LEN)
            self.bytesread += (orig_len + headersize)
            raise NotImplementedError

        # So we have an inetx packet, read in the rest of the pcap packet and unpack it as an inetX packet
        inetx_packet.packet += self.fopen.read(
            orig_len - SimpleEthernet.Ethernet.HEADERLEN -
            SimpleEthernet.IP.HEADERLEN - SimpleEthernet.UDP.HEADERLEN -
            CONTROLWORD_LEN)
        inetx_packet.unpack(inetx_packet.packet)

        self.bytesread += (headersize + orig_len)
        # return the interesting packet headers, the packet time and the temperature if it exists
        return (inetx_packet, ip_header, udp_header, sec, bcu_temperature)
示例#7
0
def UDPClient(arg):
    while True:
        data, addr = udp_socket.recvfrom(2048)
        packet = inetx.iNetX()
        packet.unpack(data)
        samples = struct.unpack("{}H".format(PARAMETERS_PER_PACKET),packet.payload)
        datastack.extend(samples)
示例#8
0
 def test_basiciNet(self):
     i = inetx.iNetX()
     i.sequence = 1
     i.pif = 0
     i.streamid = 0xdc
     i.setPacketTime(1,1)
     i.payload = struct.pack('H',0x5)
     expected_payload = struct.pack(inetx.iNetX.INETX_HEADER_FORMAT,inetx.iNetX.DEF_CONTROL_WORD,0xdc,1,30,1,1,0) + struct.pack('H',0x5)
     self.assertEqual(i.pack(),expected_payload)
示例#9
0
 def test_defaultiNet(self):
     i = inetx.iNetX()
     self.assertEqual(i.packetlen,None)
     self.assertEqual(i.inetxcontrol,inetx.iNetX.DEF_CONTROL_WORD)
     self.assertEqual(i.ptptimeseconds,None)
     self.assertEqual(i.ptptimenanoseconds,None)
     self.assertEqual(i.pif,None)
     self.assertEqual(i.payload,None)
     self.assertEqual(i.sequence,None)
     self.assertEqual(i.streamid,None)
示例#10
0
 def test_defaultiNet(self):
     i = inetx.iNetX()
     self.assertEqual(i.packetlen, None)
     self.assertEqual(i.inetxcontrol, inetx.iNetX.DEF_CONTROL_WORD)
     self.assertEqual(i.ptptimeseconds, None)
     self.assertEqual(i.ptptimenanoseconds, None)
     self.assertEqual(i.pif, None)
     self.assertEqual(i.payload, None)
     self.assertEqual(i.sequence, None)
     self.assertEqual(i.streamid, None)
示例#11
0
 def test_unpackiNet(self):
     expected_payload = struct.pack(inetx.iNetX.INETX_HEADER_FORMAT,inetx.iNetX.DEF_CONTROL_WORD,0xdc,2,30,1,1,0) + struct.pack('H',0x5)
     i = inetx.iNetX()
     i.unpack(expected_payload)
     self.assertEqual(i.sequence,2)
     self.assertEqual(i.streamid,0xdc)
     self.assertEqual(i.ptptimeseconds,1)
     self.assertEqual(i.ptptimenanoseconds,1)
     self.assertEqual(i.packetlen,30)
     self.assertEqual(i.pif,0)
     self.assertEqual(i.payload,struct.pack('H',0x5))
示例#12
0
 def test_basiciNet(self):
     i = inetx.iNetX()
     i.sequence = 1
     i.pif = 0
     i.streamid = 0xdc
     i.setPacketTime(1, 1)
     i.payload = struct.pack('H', 0x5)
     expected_payload = struct.pack(inetx.iNetX.INETX_HEADER_FORMAT,
                                    inetx.iNetX.DEF_CONTROL_WORD, 0xdc, 1,
                                    30, 1, 1, 0) + struct.pack('H', 0x5)
     self.assertEqual(i.pack(), expected_payload)
示例#13
0
 def test_unpackiNet(self):
     expected_payload = struct.pack(inetx.iNetX.INETX_HEADER_FORMAT,
                                    inetx.iNetX.DEF_CONTROL_WORD, 0xdc, 2,
                                    30, 1, 1, 0) + struct.pack('H', 0x5)
     i = inetx.iNetX()
     i.unpack(expected_payload)
     self.assertEqual(i.sequence, 2)
     self.assertEqual(i.streamid, 0xdc)
     self.assertEqual(i.ptptimeseconds, 1)
     self.assertEqual(i.ptptimenanoseconds, 1)
     self.assertEqual(i.packetlen, 30)
     self.assertEqual(i.pif, 0)
     self.assertEqual(i.payload, struct.pack('H', 0x5))
示例#14
0
 def test_unpackiNet(self):
     expected_payload = struct.pack(inetx.iNetX.INETX_HEADER_FORMAT,inetx.iNetX.DEF_CONTROL_WORD, 0xdc, 2, 30, 1, 1, 0) + \
                        struct.pack('H',0x5)
     i = inetx.iNetX(expected_payload)
     self.assertEqual(i.sequence,2)
     self.assertEqual(i.streamid,0xdc)
     self.assertEqual(i.ptptimeseconds,1)
     self.assertEqual(i.ptptimenanoseconds,1)
     self.assertEqual(i.packetlen,30)
     self.assertEqual(i.pif,0)
     self.assertEqual(i.payload,struct.pack('H',0x5))
     self.assertEqual(repr(i), "STREAMID=0XDC SEQ=2 LEN=30 PTPS=1 PTPNS=1")
     i2 = copy.copy(i)
     self.assertEqual(i, i2)
     self.assertEqual(len(i), 28+2)
示例#15
0
    def _readNextiNetXPacket(self):
        """This method will read the next iNetX packet one by one. It will raise an IOError when it hits
        the end of the file and n NoImplementedError when it hits packets that are not iNetx. It returns
        the ip, udp and inetx packets"""
        # already at the end of the file
        if self.bytesread >= self.filesize:
            raise IOError

        # otherwise pull our the PCAP header size. Should really push headersize to the object self
        pcapheader = self.fopen.read(Pcap.RECORD_HEADER_SIZE)
        (sec,usec,incl_len,orig_len) = struct.unpack(Pcap.RECORD_HEADER_FORMAT,pcapheader)

        # now we have a packet then lets deconstruct it. first read in the ethernet header and unpack it
        eth_header = SimpleEthernet.Ethernet(self.fopen.read(SimpleEthernet.Ethernet.HEADERLEN))

        # This is the most portable but as a quick hack I'm going
        # to ignore smoe packets. All non-IP packets for starter
        if eth_header.type != 2048:
            throwaway=self.fopen.read(orig_len-SimpleEthernet.Ethernet.HEADERLEN)
            self.bytesread += (orig_len+Pcap.RECORD_HEADER_SIZE)
            raise NotImplementedError

        # pull apart the other headers. Again I'm assuming all the IP packets
        # are udp packets
        ip_header = SimpleEthernet.IP(self.fopen.read(SimpleEthernet.IP.HEADERLEN))
        udp_header = SimpleEthernet.UDP(self.fopen.read(SimpleEthernet.UDP.HEADERLEN))

        # Lets create an iNetx packet then test if we are really dealing with an
        # inetx packet. Do this by testing the first 4 bytes which should be the control word
        CONTROLWORD_LEN=4
        CONTROLWORD_STRING = struct.pack('>I',0x11000000)
        inetx_packet = iNetX.iNetX()
        inetx_packet.packet = self.fopen.read(CONTROLWORD_LEN)

        # So are the first 4 bytes the control word
        if inetx_packet.packet != CONTROLWORD_STRING:
            # throw away the rest of the packet and bail out with an exception
            throwaway=self.fopen.read(orig_len-SimpleEthernet.Ethernet.HEADERLEN-SimpleEthernet.IP.HEADERLEN-SimpleEthernet.UDP.HEADERLEN-CONTROLWORD_LEN)
            self.bytesread += (orig_len+headersize)
            raise NotImplementedError

        # So we have an inetx packet, read in the rest of the pcap packet and unpack it as an inetX packet
        inetx_packet.packet += self.fopen.read(orig_len-SimpleEthernet.Ethernet.HEADERLEN-SimpleEthernet.IP.HEADERLEN-SimpleEthernet.UDP.HEADERLEN-CONTROLWORD_LEN)
        inetx_packet.unpack(inetx_packet.packet)

        self.bytesread += (headersize + orig_len)
        # return the interesting packet headers, the packet time and the temperature if it exists
        return (inetx_packet,ip_header,udp_header,sec,bcu_temperature)
示例#16
0
 def test_read_pcap(self):
     p = pcap.Pcap(os.path.join(THIS_DIR, "valid_paligned.pcap"))
     mypcaprecord = p[0]
     p.close()
     # Now I have a _payload that will be an inetx packet
     i = inetx.iNetX()
     i.unpack(mypcaprecord.payload[0x2a:-4])
     self.assertEqual(i.streamid, 0xa00)
     p = paligned.ParserAlignedPacket()
     p.unpack(i.payload)
     self.assertEqual(len(p), 83)
     self.assertEqual(repr(p), expected_p)
     for i, b in enumerate(p):
         if i == 3:
             self.assertEqual(len(b), 12)
             self.assertEqual(repr(b), "QuadBytes=3 Error=False ErrorCode=0 BusID=16 MessageCount=3 ElapsedTime=10000")
示例#17
0
    def test_unpackMultiplePackets(self):
        sequencenum = 1011
        mypcap = pcap.Pcap(os.path.join(THIS_DIR, "inetx_test.pcap"))       # Read the pcap file
        for mypcaprecord in mypcap:

            ethpacket = SimpleEthernet.Ethernet()   # Create an Ethernet object
            ethpacket.unpack(mypcaprecord.packet)   # Unpack the pcap record into the eth object
            ippacket =  SimpleEthernet.IP()         # Create an IP packet
            ippacket.unpack(ethpacket.payload)      # Unpack the ethernet _payload into the IP packet
            udppacket = SimpleEthernet.UDP()        # Create a UDP packet
            udppacket.unpack(ippacket.payload)      # Unpack the IP _payload into the UDP packet
            inetxpacket = inetx.iNetX()             # Create an iNetx object
            inetxpacket.unpack(udppacket.payload)   # Unpack the UDP _payload into this iNetX object
            #print "INETX: StreamID ={:08X} Sequence = {:8d} PTP Seconds = {}".format(inetxpacket.streamid,inetxpacket.sequence,inetxpacket.ptptimeseconds)
            self.assertEqual(inetxpacket.sequence,sequencenum)
            sequencenum += 1
        mypcap.close()
示例#18
0
 def test_unpackiNetFromPcap(self):
     p = pcap.Pcap("inetx_test.pcap")
     p.readGlobalHeader()
     mypcaprecord = p.readAPacket()
     e = SimpleEthernet.Ethernet()
     e.unpack(mypcaprecord.packet)
     ip =  SimpleEthernet.IP()
     ip.unpack(e.payload)
     u = SimpleEthernet.UDP()
     u.unpack(ip.payload)
     # Now I have a payload that will be an inetx packet
     i = inetx.iNetX()
     i.unpack(u.payload)
     self.assertEquals(i.inetxcontrol,0x11000000)
     self.assertEquals(i.streamid,0xca)
     self.assertEquals(i.sequence,1011)
     self.assertEquals(i.packetlen,72)
     self.assertEquals(i.ptptimeseconds,0x2f3)
     self.assertEquals(i.ptptimenanoseconds,0x2cb4158c)
     self.assertEquals(i.pif,0)
示例#19
0
 def test_unpackiNetFromPcap(self):
     p = pcap.Pcap("inetx_test.pcap")
     p.readGlobalHeader()
     mypcaprecord = p.readAPacket()
     e = SimpleEthernet.Ethernet()
     e.unpack(mypcaprecord.packet)
     ip = SimpleEthernet.IP()
     ip.unpack(e.payload)
     u = SimpleEthernet.UDP()
     u.unpack(ip.payload)
     # Now I have a payload that will be an inetx packet
     i = inetx.iNetX()
     i.unpack(u.payload)
     self.assertEquals(i.inetxcontrol, 0x11000000)
     self.assertEquals(i.streamid, 0xca)
     self.assertEquals(i.sequence, 1011)
     self.assertEquals(i.packetlen, 72)
     self.assertEquals(i.ptptimeseconds, 0x2f3)
     self.assertEquals(i.ptptimenanoseconds, 0x2cb4158c)
     self.assertEquals(i.pif, 0)
示例#20
0
 def test_unpackiNetFromPcap(self):
     p = pcap.Pcap(os.path.join(THIS_DIR, "inetx_test.pcap"))
     mypcaprecord = p[0]
     p.close()
     e = SimpleEthernet.Ethernet()
     e.unpack(mypcaprecord.packet)
     ip =  SimpleEthernet.IP()
     ip.unpack(e.payload)
     u = SimpleEthernet.UDP()
     u.unpack(ip.payload)
     # Now I have a _payload that will be an inetx packet
     i = inetx.iNetX()
     i.unpack(u.payload)
     self.assertEqual(i.inetxcontrol,0x11000000)
     self.assertEqual(i.streamid,0xca)
     self.assertEqual(i.sequence,1011)
     self.assertEqual(i.packetlen,72)
     self.assertEqual(i.ptptimeseconds,0x2f3)
     self.assertEqual(i.ptptimenanoseconds,0x2cb4158c)
     self.assertEqual(i.pif,0)
示例#21
0
    def test_readAllMPEGTS(self):
        '''
        Reads the same mpeg ts file as previously but reads all the data
        in the file and checks for any continuity errors
        :return:
        '''
        p = pcap.Pcap(os.path.join(THIS_DIR, "mpegts_input.pcap"))
        for mypcaprecord in p:

            ethpacket = SimpleEthernet.Ethernet()   # Create an Ethernet object
            ethpacket.unpack(mypcaprecord.packet)   # Unpack the pcap record into the eth object
            ippacket =  SimpleEthernet.IP()         # Create an IP packet
            ippacket.unpack(ethpacket.payload)      # Unpack the ethernet _payload into the IP packet
            udppacket = SimpleEthernet.UDP()        # Create a UDP packet
            udppacket.unpack(ippacket.payload)      # Unpack the IP _payload into the UDP packet
            inetxpacket = inetx.iNetX()             # Create an iNetx object
            inetxpacket.unpack(udppacket.payload)   # Unpack the UDP _payload into this iNetX object
            mpegts = MPEGTS.MPEGTS()
            mpegts.unpack(inetxpacket.payload)
            self.assertEqual(mpegts.NumberOfBlocks(),7)
            self.assertFalse(mpegts.contunityerror)

        p.close()
示例#22
0
    def test_unpackMultiplePackets(self):
        sequencenum = 1011
        mypcap = pcap.Pcap("inetx_test.pcap")       # Read the pcap file
        mypcap.readGlobalHeader()
        while True:
            # Loop through the pcap file reading one packet at a time
            try:
                mypcaprecord = mypcap.readAPacket()
            except IOError:
                # End of file reached
                break

            ethpacket = SimpleEthernet.Ethernet()   # Create an Ethernet object
            ethpacket.unpack(mypcaprecord.packet)   # Unpack the pcap record into the eth object
            ippacket =  SimpleEthernet.IP()         # Create an IP packet
            ippacket.unpack(ethpacket.payload)      # Unpack the ethernet payload into the IP packet
            udppacket = SimpleEthernet.UDP()        # Create a UDP packet
            udppacket.unpack(ippacket.payload)      # Unpack the IP payload into the UDP packet
            inetxpacket = inetx.iNetX()             # Create an iNetx object
            inetxpacket.unpack(udppacket.payload)   # Unpack the UDP payload into this iNetX object
            #print "INETX: StreamID ={:08X} Sequence = {:8d} PTP Seconds = {}".format(inetxpacket.streamid,inetxpacket.sequence,inetxpacket.ptptimeseconds)
            self.assertEquals(inetxpacket.sequence,sequencenum)
            sequencenum += 1
示例#23
0
ethernet_packet = SimpleEthernet.Ethernet()
ethernet_packet.srcmac = 0x001122334455
ethernet_packet.dstmac = 0x554433221100
ethernet_packet.type = SimpleEthernet.Ethernet.TYPE_IP
ip_packet = SimpleEthernet.IP()
ip_packet.dstip = "235.0.0.2"
ip_packet.srcip = "127.0.0.1"
udp_packet = SimpleEthernet.UDP()
udp_packet.dstport = 4422

# Fixed payload for both
payload = (struct.pack(">B", 5) * PAYLOAD_SIZE)

if args.type == "inetx":
    # Create an inetx packet
    avionics_packet = inetx.iNetX()
    avionics_packet.inetxcontrol = inetx.iNetX.DEF_CONTROL_WORD
    avionics_packet.pif = 0
    avionics_packet.streamid = 0xdc
    avionics_packet.sequence = 0
    avionics_packet.payload = payload
elif args.type == "iena":
    # Create an iena packet
    avionics_packet = iena.IENA()
    avionics_packet.key = 0xdc
    avionics_packet.keystatus = 0
    avionics_packet.endfield = 0xbeef
    avionics_packet.sequence = 0
    avionics_packet.payload = payload
    avionics_packet.status = 0
def main():

    #----------------------------------
    # Setup the command line parser
    #----------------------------------
    parser = argparse.ArgumentParser(
        description='Live Analysis of BCU transmitted packets.')
    parser.add_argument('--inetx',
                        type=int,
                        default=None,
                        required=False,
                        help='Receiving iNetX packets on this UDP port')
    parser.add_argument('--iena',
                        type=int,
                        default=None,
                        required=False,
                        help='Receiving IENA packets on this UDP port')
    args = parser.parse_args()

    if args.inetx != None:
        udp_port = args.inetx
        is_inetx = True
    elif args.iena != None:
        udp_port = args.iena
        is_inetx = False
    else:
        parser.print_help()
        exit()

    #------------------------------------------------------------
    # Setup the coloured output
    #------------------------------------------------------------
    colouredop = ColouredOutput.ColouredOutput()
    colouredop.PrintHeader()
    colouredop.PrintFileName("UDP Port={}".format(udp_port))
    colouredop.PrintExitInfo("Hit ESC to exit...")
    #------------------------------------------------------------
    # Setup a socket to recieve all traffic
    #------------------------------------------------------------
    try:
        recv_socket = McastSocket.McastSocket(local_port=udp_port, reuse=1)
        recv_socket.mcast_add('235.0.0.1', '0.0.0.0')
        recv_socket.settimeout(10)
    except:
        print "Can't bind to socket {}".format(udp_port)
        exit()

    packet_count = 1
    while True:
        # Exit if the esc or q key is hit
        if os.name == "nt":
            # Exit if the esc or q key is hit
            if msvcrt.kbhit():
                if (ord(msvcrt.getch()) == 27 or ord(msvcrt.getch()) == 113):
                    exit()

        # Capture some data from the socket
        try:
            data, addr = recv_socket.recvfrom(
                2048)  # buffer size is 1500 bytes
        except socket.timeout:
            print "timeout on socket"
            exit()

        (udpsrcport, srcipaddr) = addr

        # Create a new packet depending on the command line arguments
        # and unpack the received data into these objects
        if is_inetx:
            avionics_packet = inetx.iNetX()
            data_len = len(data)
            avionics_packet.unpack(data)
            try:
                avionics_packet.unpack(data)
            except ValueError:
                # This isn't an inetx packet
                packet_count += 1
                continue
        else:
            avionics_packet = iena.IENA()
            try:
                avionics_packet.unpack(data)
            except ValueError:
                # We got a length error. Should really handle this better. We could bail on this?
                packet_count += 1
                exit()

        if is_inetx:

            # What string do we want outputted to the screen. The output format is defined in the coloredop class
            outstring = colouredop.output_format.format(
                avionics_packet.streamid, udpsrcport, avionics_packet.sequence,
                datetime.datetime.fromtimestamp(
                    avionics_packet.ptptimeseconds).strftime('%H:%M:%S'))
            # Print out one line and the dropped packet info
            colouredop.PrintALine(outstring, avionics_packet.sequence,
                                  avionics_packet.streamid)
            colouredop.PrintDroppedPacket(avionics_packet.sequence,
                                          avionics_packet.streamid,
                                          packet_count, udp_port)
        else:
            outstring = colouredop.output_format.format(
                avionics_packet.key, udpsrcport, avionics_packet.sequence,
                datetime.datetime.fromtimestamp(
                    avionics_packet._getPacketTime()).strftime('%H:%M:%S'))
            colouredop.PrintALine(outstring, avionics_packet.sequence,
                                  avionics_packet.key)

        packet_count += 1
def main():

    # Setup some constants
    PACKETS_TO_RECEIVE = 1000

    #----------------------------------
    # Setup the command line parser
    #----------------------------------
    parser = argparse.ArgumentParser(description='Live Analysis of BCU transmitted packets.')
    parser.add_argument('--inetx', type=int,  default=None, required=False,  help='Receiving iNetX packets on this UDP port')
    parser.add_argument('--iena', type=int,  default=None, required=False,  help='Receiving IENA packets on this UDP port')
    parser.add_argument('--address', type=str,  default="235.0.0.1", required=False,  help='Destination multicast address')
    args = parser.parse_args()

    if args.inetx != None:
        udp_port = args.inetx
        is_inetx = True
    elif args.iena != None:
        udp_port = args.iena
        is_inetx = False
    else:
        parser.print_help()
        exit()

    #------------------------------------------------------------
    # Setup a socket to receive all traffic
    #------------------------------------------------------------
    try:
        recv_socket = mcast.McastSocket(local_port=udp_port, reuse=1)
        recv_socket.mcast_add(args.address, '0.0.0.0')
        recv_socket.settimeout(3)
    except:
        print("Can't bind to socket {}".format(udp_port))
        exit()

    start_time = time.time()
    packet_count = 1
    drop_count = 0
    streams = dict()
    data_len = deque()


    while packet_count < PACKETS_TO_RECEIVE:

        # Capture some data from the socket
        try:
            data, addr = recv_socket.recvfrom(2048) # buffer size is 1500 bytes
        except:
            print("timeout on socket")
            exit()

        (udpsrcport,srcipaddr) = addr

        # keep a track of the sizes of the last 20 packets received so that we
        # can calculate the bandwitdh
        # The data returned in the UDP _payload only so add 42 bytes for the rest of the
        # ethernet header just so the calculated number agress with Wireshark
        data_len.append(len(data)+42)
        if len(data_len) > 20:
            data_len.popleft()

        # Create a new packet depending on the command line arguments
        # and unpack the received data into these objects
        if is_inetx:
            avionics_packet = inetx.iNetX()
            avionics_packet.unpack(data)
            try:
                avionics_packet.unpack(data)
            except ValueError:
                # This isn't an inetx packet
                packet_count += 1
                continue
        else:
            avionics_packet = iena.IENA()
            try:
                avionics_packet.unpack(data)
            except ValueError:
                # Not a valid IENA packet
                packet_count += 1
                continue

        if is_inetx:
            if avionics_packet.streamid in streams:
                if avionics_packet.sequence != ((streams[avionics_packet.streamid] +1) % 0x100000000):
                    drop_count += 1
            streams[avionics_packet.streamid] = avionics_packet.sequence

        else:
            if avionics_packet.key in streams:
                if avionics_packet.sequence != ((streams[avionics_packet.key] +1) % 65536):
                    drop_count += 1
            streams[avionics_packet.key] = avionics_packet.sequence



        packet_count += 1

    end_time = time.time()
    average_len = sum(data_len)/len(data_len)
    print("INFO: Recevied {} packets in {} seconds with {} dropped packets".format(packet_count,end_time-start_time,drop_count))
    print("INFO: Recevied {:.3f} Mbps".format((average_len*packet_count*8)/((end_time-start_time)*1024*1024)))
def main():

    #----------------------------------
    # Setup the command line parser
    #----------------------------------
    parser = argparse.ArgumentParser(
        description=
        'Analyse a pcap file looking for iNetX parser aligned packets')
    parser.add_argument('--pcap',
                        required=True,
                        action='append',
                        help='The dump pcap packet')
    args = parser.parse_args()

    #------------------------------------------------------------
    # Now read the input.
    #------------------------------------------------------------

    # The input will take multiple pcap files and loop through each

    for pcapfilename in args.pcap:
        try:
            pcapfile = pcap.Pcap(pcapfilename)
        except IOError:
            print "ERROR: File {} not found".format(pcapfilename)
            exit()

        packet_count = 1

        start_of_run = time.time()  # benchmarking

        while True:
            try:

                # So we loop through the file one packet at a time. This will eventually return an
                # exception at the end of file so handle that when it occurs
                (eth_packet, ip_packet,
                 udp_packet) = pcapfile._readNextUDPPacket()
                if udp_packet.isinetx:  # This is a rough guess assuming the control word is 0x11000000
                    inetx_packet = inetx.iNetX()
                    inetx_packet.unpack(udp_packet.payload)
                    readablemac = mactoreadable(
                        eth_packet.srcmac
                    )  # handy function to return the mac address in a readable format
                    output_format = "SRCMAC={:>20s} SRCIP={:>15s} DSTPORT={:5d} StreamID={:#5x} Sequence={:10d}"

                    # What string do we want outputted to the screen. The output format is defined in the coloredop class
                    outstring = output_format.format(readablemac,
                                                     ip_packet.srcip,
                                                     udp_packet.dstport,
                                                     inetx_packet.streamid,
                                                     inetx_packet.sequence)
                    # Print out one line and the dropped packet info
                    print outstring

                    # We have a parser aligned block
                    if inetx_packet.streamid == 0x11121314:  # This specific streamid is a parser aligned block
                        parser_aligned_packet = ParserAligned.ParserAlignedPacket(
                        )
                        # unpack the payload as the parser data
                        parser_aligned_packet.unpack(inetx_packet.payload)
                        # Loop through all the blocks in the packet and spit them out
                        for pblock in parser_aligned_packet.parserblocks:
                            (payload_data, ) = struct.unpack(
                                '>I', pblock.payload)
                            print "Quadb={:5} Msgcnt={:5} BusId={:4} Elapsed={:20}".format(
                                pblock.quadbytes, pblock.messagecount,
                                pblock.busid, pblock.elapsedtime, payload_data)

                packet_count += 1
            except NotImplementedError:
                # We received a packet that we don't care about. So skip silently
                packet_count += 1
                pass
            except IOError:
                # We are at the end of the file so lets jump to the next file
                print(
                    "End of file reached. Packets Per Second ={:5.1f}".format(
                        packet_count / (time.time() - start_of_run)))
                break
示例#27
0
def main():

    #----------------------------------
    # Setup the command line parser
    #----------------------------------
    parser = argparse.ArgumentParser(
        description=
        'Dump out the payload of iNetX packets as ASCII representations')
    parser.add_argument('--pcap',
                        required=True,
                        action='append',
                        help='The input pcap file(s)')
    parser.add_argument(
        '--hex',
        required=False,
        action='store_true',
        default=False,
        help='Print the hex representation not the ASCII coded version')
    parser.add_argument('--outdir',
                        required=False,
                        default="out",
                        help='Name of output directory. Default is out')
    args = parser.parse_args()

    #------------------------------------------------------------
    # Now read the input.
    #------------------------------------------------------------
    # The input will take multiple pcap files and loop through each

    # Keep a track of the position in the line for each streamID
    output_byte_count = {}

    for pcapfilename in args.pcap:
        try:
            pcapfile = pcap.Pcap(pcapfilename)
        except IOError:
            print "ERROR: File {} not found".format(pcapfilename)
            exit()

        if not os.path.exists(args.outdir):
            os.mkdir(args.outdir)

        pcapfile.readGlobalHeader()
        while True:
            try:

                # So we loop through the file one packet at a time. This will eventually return an
                # exception at the end of file so handle that when it occurs

                pcaprecord = pcapfile.readAPacket()
                eth = SimpleEthernet.Ethernet()
                eth.unpack(pcaprecord.packet)
                ip = SimpleEthernet.IP()
                ip.unpack(eth.payload)
                udp_packet = SimpleEthernet.UDP()
                udp_packet.unpack(ip.payload)
                (ctrl_word, ) = struct.unpack('>I', udp_packet.payload[:4])
                if ctrl_word == 0x11000000:
                    inetx_packet = inetx.iNetX()
                    # Unpack the udp payload as an iNetx packet
                    inetx_packet.unpack(udp_packet.payload)
                    # Do we want to dump out an ascii or hex output
                    if args.hex == True:
                        prefix = "hex"
                    else:
                        prefix = "ascii"

                    # Create an output  file per streamID and open it
                    output_file_name = "{}/{}_{:08X}.txt".format(
                        args.outdir, prefix, inetx_packet.streamid)
                    # NB: We are appending to the file here so if you have existing files in the directory then it will be appended
                    output_file = open(output_file_name, 'a')

                    # Start the byte count per streamID
                    if not output_byte_count.has_key(inetx_packet.streamid):
                        output_byte_count[inetx_packet.streamid] = 1

                    # Go thorough each byte in the payload. Not particularly efficient
                    for byte in inetx_packet.payload:
                        # Unpack the payload as an unsigned integer
                        (byte_in_ascii, ) = struct.unpack('B', byte)

                        # Write the output depending on what you want
                        if args.hex == True:
                            output_file.write("{:02X} ".format(byte_in_ascii))
                        else:
                            # Only some ASCII codes are printable so don't print out
                            # the non printable ones. Emulate the wireshark method of printing a period
                            if byte_in_ascii < 31 or byte_in_ascii > 126:
                                printable_string = "."
                            else:
                                printable_string = chr(byte_in_ascii)

                            output_file.write("{}".format(printable_string))

                        # Create a new line after 16 bytes for readability
                        if (output_byte_count[inetx_packet.streamid] %
                                16 == 0):
                            output_file.write('\n')
                        output_byte_count[inetx_packet.streamid] += 1

            except NotImplementedError:
                # We received a packet that we don't care about. So skip silently
                pass

            except IOError:
                # We are at the end of the file so lets jump to the next file
                print("End of {} reached.".format(pcapfilename))
                break

        print "Output files created in {} directory".format(args.outdir)
def main():

    #----------------------------------
    # Setup the command line parser
    #----------------------------------
    parser = argparse.ArgumentParser(description='Analyse MPEG TS over inetx.')
    parser.add_argument('--inetx',
                        type=int,
                        default=None,
                        required=True,
                        help='Capture iNetX packets on this port')
    parser.add_argument('--multicast',
                        type=str,
                        default="235.0.0.1",
                        required=False,
                        help='The transmited multicast address')
    parser.add_argument('--localhost',
                        type=str,
                        default='192.168.28.110',
                        required=False,
                        help='The IP address of the local ethernet card')
    args = parser.parse_args()

    if args.inetx == None:
        parser.print_help()
        exit()

    PID_TEXT = {
        0x1fff: "Null",
        0x0: "Program Association Table",
        0x100: "VID106_Video",
        0x101: "VID106_Audio",
        0x1000: "Program Map Table",
        0x3E8: "VID103_Video",
        0x20: "Unkn"
    }

    #------------------------------------------------------------
    # Setup a socket to recieve all traffic
    #------------------------------------------------------------
    #try:
    recv_socket = McastSocket.McastSocket(local_port=args.inetx, reuse=1)
    recv_socket.mcast_add(args.multicast, args.localhost)
    recv_socket.settimeout(10)
    #except:
    #    print "Can't bind to socket {}".format(args.inetx)
    #    print sys.exc_info()[0]
    #    exit()

    aligned_payload = ""

    while True:

        # Capture some data from the socket
        try:
            data, addr = recv_socket.recvfrom(
                2048)  # buffer size is 1500 bytes
        except socket.timeout:
            print "timeout on socket"
            exit()

        # we are expecting a iNetX packets
        inetxpacket = inetx.iNetX()
        try:
            inetxpacket.unpack(data)
        except:
            pass

        # if we are in snarfer mode then align the payload
        aligned_payload = align_payload(aligned_payload + inetxpacket.payload)
        if len(aligned_payload) >= 1316:

            # take the aligned payload and convert it into MPEG TS blocks
            # Then print out the blocks
            mpegtspackets = mpegts.MPEGTS()
            mpegtspackets.unpack(aligned_payload[:1316])
            for mpegblock in mpegtspackets.blocks:
                print "PID = {}".format(PID_TEXT[mpegblock.pid])

            aligned_payload = aligned_payload[1316:]
def main():

    #----------------------------------
    # Setup the command line parser
    #----------------------------------
    parser = argparse.ArgumentParser(description='Analyse MPEG TS over inetx.')
    parser.add_argument('--inetx', type=int,  default=None, required=True,  help='Capture iNetX packets on this port')
    parser.add_argument('--multicast', type=str,  default="235.0.0.1", required=False,  help='The transmited multicast address')
    parser.add_argument('--localhost', type=str,  default='192.168.28.110', required=False,  help='The IP address of the local ethernet card')
    args = parser.parse_args()

    if args.inetx == None :
        parser.print_help()
        exit()


    PID_TEXT = {0x1fff : "Null", 0x0 : "Program Association Table", 0x100 : "VID106_Video" , 0x101 : "VID106_Audio", 0x1000 : "Program Map Table", 0x3E8 : "VID103_Video", 0x20 : "Unkn"}

    #------------------------------------------------------------
    # Setup a socket to recieve all traffic
    #------------------------------------------------------------
    #try:
    recv_socket = McastSocket.McastSocket(local_port=args.inetx, reuse=1)
    recv_socket.mcast_add(args.multicast, args.localhost)
    recv_socket.settimeout(10)
    #except:
    #    print "Can't bind to socket {}".format(args.inetx)
    #    print sys.exc_info()[0]
    #    exit()


    aligned_payload = ""

    while True:

        # Capture some data from the socket
        try:
            data, addr = recv_socket.recvfrom(2048) # buffer size is 1500 bytes
        except socket.timeout:
            print "timeout on socket"
            exit()

        # we are expecting a iNetX packets
        inetxpacket = inetx.iNetX()
        try:
            inetxpacket.unpack(data)
        except:
            pass

        # if we are in snarfer mode then align the payload
        aligned_payload = align_payload(aligned_payload+inetxpacket.payload)
        if len(aligned_payload) >= 1316:

            # take the aligned payload and convert it into MPEG TS blocks
            # Then print out the blocks
            mpegtspackets = mpegts.MPEGTS()
            mpegtspackets.unpack(aligned_payload[:1316])
            for mpegblock in mpegtspackets.blocks:
                print "PID = {}".format(PID_TEXT[mpegblock.pid])

            aligned_payload = aligned_payload[1316:]
示例#30
0
UDP_IP = "235.0.0.1"
UDP_PORT = 5005

print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT


sock = mcast.McastSocket()
sock.mcast_add(UDP_IP)

# Fixed payload for both
payload = struct.pack(">L",5)


# Create an inetx packet
myinetx = inetx.iNetX()
myinetx.inetxcontrol = inetx.iNetX.DEF_CONTROL_WORD
myinetx.pif = 0
myinetx.streamid = 0xdc
myinetx.sequence = 0
myinetx.payload = payload

# Create an iena packet
myiena = iena.IENA()
myiena.key = 0xdc
myiena.keystatus = 0
myiena.endfield = 0xbeef
myiena.sequence = 0
myiena.payload = payload
myiena.status = 0
def main():

    #----------------------------------
    # Setup the command line parser
    #----------------------------------
    parser = argparse.ArgumentParser(description='Analyse a pcap file looking for iNetX parser aligned packets')
    parser.add_argument('--pcap',  required=True, action='append',  help='The dump pcap packet')
    args = parser.parse_args()

    #------------------------------------------------------------
    # Now read the input.
    #------------------------------------------------------------

    # The input will take multiple pcap files and loop through each

    for pcapfilename in args.pcap:
        try:
            pcapfile = pcap.Pcap(pcapfilename)
        except IOError:
            print "ERROR: File {} not found".format(pcapfilename)
            exit()


        packet_count = 1


        start_of_run = time.time() # benchmarking


        while True:
            try:

                # So we loop through the file one packet at a time. This will eventually return an
                # exception at the end of file so handle that when it occurs
                (eth_packet,ip_packet,udp_packet) = pcapfile._readNextUDPPacket()
                if udp_packet.isinetx: # This is a rough guess assuming the control word is 0x11000000
                    inetx_packet = inetx.iNetX()
                    inetx_packet.unpack(udp_packet.payload)
                    readablemac = mactoreadable(eth_packet.srcmac) # handy function to return the mac address in a readable format
                    output_format = "SRCMAC={:>20s} SRCIP={:>15s} DSTPORT={:5d} StreamID={:#5x} Sequence={:10d}"

                    # What string do we want outputted to the screen. The output format is defined in the coloredop class
                    outstring =output_format.format(readablemac ,ip_packet.srcip, udp_packet.dstport,inetx_packet.streamid,inetx_packet.sequence)
                    # Print out one line and the dropped packet info
                    print outstring

                    # We have a parser aligned block
                    if inetx_packet.streamid == 0x11121314: # This specific streamid is a parser aligned block
                        parser_aligned_packet = ParserAligned.ParserAlignedPacket()
                        # unpack the payload as the parser data
                        parser_aligned_packet.unpack(inetx_packet.payload)
                        # Loop through all the blocks in the packet and spit them out
                        for pblock in parser_aligned_packet.parserblocks:
                            (payload_data,) =struct.unpack('>I',pblock.payload)
                            print "Quadb={:5} Msgcnt={:5} BusId={:4} Elapsed={:20}".format(pblock.quadbytes,pblock.messagecount,pblock.busid,pblock.elapsedtime,payload_data)


                packet_count += 1
            except NotImplementedError:
                # We received a packet that we don't care about. So skip silently
                packet_count += 1
                pass
            except IOError:
                # We are at the end of the file so lets jump to the next file
                print ( "End of file reached. Packets Per Second ={:5.1f}".format(packet_count/(time.time()-start_of_run)))
                break
def main():

    #----------------------------------
    # Setup the command line parser
    #----------------------------------
    parser = argparse.ArgumentParser(description='Dump out the payload of iNetX packets as ASCII representations')
    parser.add_argument('--pcap',  required=True, action='append',  help='The input pcap file(s)')
    parser.add_argument('--hex',  required=False, action='store_true', default=False,  help='Print the hex representation not the ASCII coded version')
    parser.add_argument('--outdir',  required=False, default="out", help='Name of output directory. Default is out')
    args = parser.parse_args()

    #------------------------------------------------------------
    # Now read the input.
    #------------------------------------------------------------
    # The input will take multiple pcap files and loop through each

    # Keep a track of the position in the line for each streamID
    output_byte_count ={}

    for pcapfilename in args.pcap:
        try:
            pcapfile = pcap.Pcap(pcapfilename)
        except IOError:
            print "ERROR: File {} not found".format(pcapfilename)
            exit()


        if not os.path.exists(args.outdir):
            os.mkdir(args.outdir)

        pcapfile.readGlobalHeader()
        while True:
            try:

                # So we loop through the file one packet at a time. This will eventually return an
                # exception at the end of file so handle that when it occurs


                pcaprecord = pcapfile.readAPacket()
                eth = SimpleEthernet.Ethernet()
                eth.unpack(pcaprecord.packet)
                ip = SimpleEthernet.IP()
                ip.unpack(eth.payload)
                udp_packet = SimpleEthernet.UDP()
                udp_packet.unpack(ip.payload)
                (ctrl_word,) = struct.unpack('>I',udp_packet.payload[:4])
                if ctrl_word == 0x11000000:
                    inetx_packet = inetx.iNetX()
                    # Unpack the udp payload as an iNetx packet
                    inetx_packet.unpack(udp_packet.payload)
                    # Do we want to dump out an ascii or hex output
                    if args.hex == True:
                        prefix = "hex"
                    else:
                        prefix = "ascii"

                    # Create an output  file per streamID and open it
                    output_file_name = "{}/{}_{:08X}.txt".format(args.outdir,prefix,inetx_packet.streamid)
                    # NB: We are appending to the file here so if you have existing files in the directory then it will be appended
                    output_file = open(output_file_name,'a')

                    # Start the byte count per streamID
                    if  not output_byte_count.has_key(inetx_packet.streamid):
                        output_byte_count[inetx_packet.streamid] = 1

                    # Go thorough each byte in the payload. Not particularly efficient
                    for byte in inetx_packet.payload:
                        # Unpack the payload as an unsigned integer
                        (byte_in_ascii,) =struct.unpack('B',byte)

                        # Write the output depending on what you want
                        if args.hex == True:
                            output_file.write("{:02X} ".format(byte_in_ascii))
                        else:
                            # Only some ASCII codes are printable so don't print out
                            # the non printable ones. Emulate the wireshark method of printing a period
                            if byte_in_ascii < 31 or byte_in_ascii > 126:
                                printable_string = "."
                            else:
                                printable_string = chr(byte_in_ascii)

                            output_file.write("{}".format(printable_string))

                        # Create a new line after 16 bytes for readability
                        if (output_byte_count[inetx_packet.streamid] % 16 == 0):
                            output_file.write('\n')
                        output_byte_count[inetx_packet.streamid] += 1



            except NotImplementedError:
                # We received a packet that we don't care about. So skip silently
                pass

            except IOError:
                # We are at the end of the file so lets jump to the next file
                print ( "End of {} reached.".format(pcapfilename))
                break

        print "Output files created in {} directory".format(args.outdir)
def main():

    # Setup some constants
    PACKETS_TO_RECEIVE = 1000

    #----------------------------------
    # Setup the command line parser
    #----------------------------------
    parser = argparse.ArgumentParser(description='Live Analysis of BCU transmitted packets.')
    parser.add_argument('--inetx', type=int,  default=None, required=False,  help='Receiving iNetX packets on this UDP port')
    parser.add_argument('--iena', type=int,  default=None, required=False,  help='Receiving IENA packets on this UDP port')
    parser.add_argument('--address', type=str,  default="235.0.0.1", required=False,  help='Destination multicast address')
    args = parser.parse_args()

    if args.inetx != None:
        udp_port = args.inetx
        is_inetx = True
    elif args.iena != None:
        udp_port = args.iena
        is_inetx = False
    else:
        parser.print_help()
        exit()

    #------------------------------------------------------------
    # Setup a socket to receive all traffic
    #------------------------------------------------------------
    try:
        recv_socket = mcast.McastSocket(local_port=udp_port, reuse=1)
        recv_socket.mcast_add(args.address, '0.0.0.0')
        recv_socket.settimeout(3)
    except:
        print "Can't bind to socket {}".format(udp_port)
        exit()

    start_time = time.time()
    packet_count = 1
    drop_count = 0
    streams = dict()
    data_len = deque()


    while packet_count < PACKETS_TO_RECEIVE:

        # Capture some data from the socket
        try:
            data, addr = recv_socket.recvfrom(2048) # buffer size is 1500 bytes
        except:
            print "timeout on socket"
            exit()

        (udpsrcport,srcipaddr) = addr

        # keep a track of the sizes of the last 20 packets received so that we
        # can calculate the bandwitdh
        # The data returned in the UDP payload only so add 42 bytes for the rest of the
        # ethernet header just so the calculated number agress with Wireshark
        data_len.append(len(data)+42)
        if len(data_len) > 20:
            data_len.popleft()

        # Create a new packet depending on the command line arguments
        # and unpack the received data into these objects
        if is_inetx:
            avionics_packet = inetx.iNetX()
            avionics_packet.unpack(data)
            try:
                avionics_packet.unpack(data)
            except ValueError:
                # This isn't an inetx packet
                packet_count += 1
                continue
        else:
            avionics_packet = iena.IENA()
            try:
                avionics_packet.unpack(data)
            except ValueError:
                # Not a valid IENA packet
                packet_count += 1
                continue

        if is_inetx:
            if avionics_packet.streamid in streams:
                if avionics_packet.sequence != ((streams[avionics_packet.streamid] +1) % 0x100000000):
                    drop_count += 1
            streams[avionics_packet.streamid] = avionics_packet.sequence

        else:
            if avionics_packet.key in streams:
                if avionics_packet.sequence != ((streams[avionics_packet.key] +1) % 65536):
                    drop_count += 1
            streams[avionics_packet.key] = avionics_packet.sequence



        packet_count += 1

    end_time = time.time()
    average_len = sum(data_len)/len(data_len)
    print "INFO: Recevied {} packets in {} seconds with {} dropped packets".format(packet_count,end_time-start_time,drop_count)
    print "INFO: Recevied {:.3f} Mbps".format((average_len*packet_count*8)/((end_time-start_time)*1024*1024))
示例#34
0
def main():

    #----------------------------------
    # Setup the command line parser
    #----------------------------------
    parser = argparse.ArgumentParser(description='Live Analysis of BCU transmitted packets.')
    parser.add_argument('--inetx', type=int,  default=None, required=False,  help='Receiving iNetX packets on this UDP port')
    parser.add_argument('--iena', type=int,  default=None, required=False,  help='Receiving IENA packets on this UDP port')
    args = parser.parse_args()

    if args.inetx != None:
        udp_port = args.inetx
        is_inetx = True
    elif args.iena != None:
        udp_port = args.iena
        is_inetx = False
    else:
        parser.print_help()
        exit()

    #------------------------------------------------------------
    # Setup the coloured output
    #------------------------------------------------------------
    colouredop = ColouredOutput.ColouredOutput()
    colouredop.PrintHeader()
    colouredop.PrintFileName("UDP Port={}".format(udp_port))
    colouredop.PrintExitInfo("Hit ESC to exit...")
    #------------------------------------------------------------
    # Setup a socket to recieve all traffic
    #------------------------------------------------------------
    try:
        recv_socket = McastSocket.McastSocket(local_port=udp_port, reuse=1)
        recv_socket.mcast_add('235.0.0.1', '0.0.0.0')
        recv_socket.settimeout(10)
    except:
        print("Can't bind to socket {}".format(udp_port))
        exit()

    packet_count = 1
    while True:
        # Exit if the esc or q key is hit
        if os.name == "nt":
            # Exit if the esc or q key is hit
            if msvcrt.kbhit():
                if ( ord(msvcrt.getch()) == 27 or ord(msvcrt.getch()) == 113):
                    exit()

        # Capture some data from the socket
        try:
            data, addr = recv_socket.recvfrom(2048) # buffer size is 1500 bytes
        except socket.timeout:
            print("timeout on socket")
            exit()

        (udpsrcport,srcipaddr) = addr

        # Create a new packet depending on the command line arguments
        # and unpack the received data into these objects
        if is_inetx:
            avionics_packet = inetx.iNetX()
            data_len = len(data)
            avionics_packet.unpack(data)
            try:
                avionics_packet.unpack(data)
            except ValueError:
                # This isn't an inetx packet
                packet_count += 1
                continue
        else:
            avionics_packet = iena.IENA()
            try:
                avionics_packet.unpack(data)
            except ValueError:
                # We got a length error. Should really handle this better. We could bail on this?
                packet_count += 1
                exit()

        if is_inetx:

            # What string do we want outputted to the screen. The output format is defined in the coloredop class
            outstring =colouredop.output_format.format(avionics_packet.streamid,udpsrcport,avionics_packet.sequence,datetime.datetime.fromtimestamp(avionics_packet.ptptimeseconds).strftime('%H:%M:%S'))
            # Print out one line and the dropped packet info
            colouredop.PrintALine(outstring,avionics_packet.sequence,avionics_packet.streamid)
            colouredop.PrintDroppedPacket(avionics_packet.sequence,avionics_packet.streamid,packet_count,udp_port)
        else:
            outstring =colouredop.output_format.format(avionics_packet.key,udpsrcport,avionics_packet.sequence,datetime.datetime.fromtimestamp(avionics_packet._getPacketTime()).strftime('%H:%M:%S'))
            colouredop.PrintALine(outstring,avionics_packet.sequence,avionics_packet.key)

        packet_count += 1
示例#35
0
SAMPLE_RATE = 512
PARAMETERS_PER_PACKET = 64
DELAY_BETWEEN_PACKETS = float(PARAMETERS_PER_PACKET)/SAMPLE_RATE # milliseconds
FREQ = 10
MULTICAST_IP = "235.0.0.1"
MULTICAST_PORT = 8010
AMPLITUDE = 30000
# end configuration


# open a socket
udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)
udp_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)

# Setup an inetx packet
adcpacket = inetx.iNetX()
adcpacket.streamid = 0xdc
adcpacket.sequence = 1
adcpacket.inetxcontrol = 0x11000000
adcpacket.pif = 0
adcpacket.ptptimeseconds = 0
adcpacket.ptptimenanoseconds = 0

sampletime = 0.0

# loop forever
while True:
    signalValues = []
    # calculate the sample values for all the parameters in the current packet
    for sample in range(PARAMETERS_PER_PACKET):
        sampletime = (sampletime + float(1.0/SAMPLE_RATE)) % 1.0
示例#36
0
UDP_IP = "192.168.28.100"
UDP_PORT = 4444

print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("Rate = {} Hz".format(args.rate))

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#sock.mcast_add(UDP_IP)

# Fixed _payload for both


# Create an inetx packet
myinetx = inetx.iNetX()

payload = struct.pack(">I",0xa5)

myinetx.inetxcontrol = inetx.iNetX.DEF_CONTROL_WORD
myinetx.pif = 0
myinetx.streamid = 0xdc
myinetx.sequence = 0
myinetx.payload = payload * 512

# Create an iena packet
myiena = iena.IENA()
myiena.key = 0xdc
myiena.keystatus = 0
myiena.endfield = 0xbeef
myiena.sequence = 0
parser.add_argument('--ignoretime',required=False, action='store_true', default=False)
args = parser.parse_args()

# constants
PACKETS_TO_SEND = 50000
PAYLOAD_SIZE = 1300 # size of the _payload in bytes
HEADER_SIZE = {'udp' : 58 , 'inetx' :86 ,'iena':74}
UDP_IP = "235.0.0.1"
UDP_PORT = 8888

# Fixed _payload for both
payload = (struct.pack(">B",5) * PAYLOAD_SIZE)

if args.type == "inetx":
    # Create an inetx packet
    avionics_packet = inetx.iNetX()
    avionics_packet.inetxcontrol = inetx.iNetX.DEF_CONTROL_WORD
    avionics_packet.pif = 0
    avionics_packet.streamid = 0xdc
    avionics_packet.sequence = 0
    avionics_packet.payload = payload
elif args.type == "iena":
    # Create an iena packet
    avionics_packet = iena.IENA()
    avionics_packet.key = 0xdc
    avionics_packet.keystatus = 0
    avionics_packet.endfield = 0xbeef
    avionics_packet.sequence = 0
    avionics_packet.payload = payload
    avionics_packet.status = 0
def main():

    try:
        pcapfile = pcap.Pcap("SSR_ABM_102_capture_example1.pcap")
    except IOError:
        print "ERROR: Could not find input file SSR_ABM_102_capture_example1.pcap"
        exit()

    # Keep a running count of the packets
    packet_count = 1
    # Keep a count of previous sequence number to detect a dropped packets
    PreviousSeqNum = dict()

    while True: # while we are not at the end of the file
        try:
            # So we loop through the file one packet at a time. This will eventually return an
            # exception at the end of file so handle that when it occurs
            pcaprecord = pcapfile.readAPacket()
            eth = SimpleEthernet.Ethernet()
            eth.unpack(pcaprecord.packet)
            ip = SimpleEthernet.IP()
            ip.unpack(eth.payload)
            udp_packet = SimpleEthernet.UDP()
            udp_packet.unpack(ip.payload)
            (ctrl_word,) = struct.unpack('>I',udp_packet.payload[:4])
            if ctrl_word == 0x11000000: # This is a rough guess assuming the control word is 0x11000000
                inetx_packet = inetx.iNetX()
                inetx_packet.unpack(udp_packet.payload)

                #----------------------------
                # Check for dropped packet
                #----------------------------
                if inetx_packet.streamid not in PreviousSeqNum:
                    PreviousSeqNum[inetx_packet.streamid] = inetx_packet.sequence
                else:
                    if PreviousSeqNum[inetx_packet.streamid]+1 != inetx_packet.sequence:
                        print "ERROR: Dropped {} packets on streamid={:#x} at packet count={}".format(inetx_packet.sequence - PreviousSeqNum[inetx_packet.streamid] + 1,inetx_packet.streamid,packet_count)
                    PreviousSeqNum[inetx_packet.streamid] = inetx_packet.sequence

                print "----- StreamID={:#10x} SourceIP= {:10s} -----".format(inetx_packet.streamid,ip_packet.srcip)
                #--------------------------------------------------------------------------------
                # Packets on stream id 0x11121314 is a parser aligned block so lets look at this
                #--------------------------------------------------------------------------------
                if inetx_packet.streamid == 0x11121314:
                    parser_aligned_packet = ParserAligned.ParserAlignedPacket()
                    # unpack the payload as the parser data
                    parser_aligned_packet.unpack(inetx_packet.payload)

                    # Loop through all the blocks in the packet and spit them out
                    for pblock in parser_aligned_packet.parserblocks:
                        (payload_data,) =struct.unpack('>I',pblock.payload)
                        print "Sequence Number = {:8} Quadbyes={:5} Msgcnt={:5} BusId={:4} Elapsed={:20} ".format(inetx_packet.sequence, pblock.quadbytes,pblock.messagecount,pblock.busid,pblock.elapsedtime,payload_data)


            packet_count += 1

        except NotImplementedError:
            # We received a packet that we don't care about. So skip silently
            packet_count += 1
            pass

        except IOError:
            # We are at the end of the file so lets jump to the next file
            print ( "End of file reached")
            exit()
def main():

    try:
        pcapfile = pcap.Pcap("SSR_ABM_102_capture_example1.pcap")
    except IOError:
        print("ERROR: Could not find input file SSR_ABM_102_capture_example1.pcap")
        exit()

    # Keep a running count of the packets
    packet_count = 1
    # Keep a count of previous sequence number to detect a dropped packets
    PreviousSeqNum = dict()

    while True: # while we are not at the end of the file
        try:
            # So we loop through the file one packet at a time. This will eventually return an
            # exception at the end of file so handle that when it occurs
            pcaprecord = pcapfile.readAPacket()
            eth = SimpleEthernet.Ethernet()
            eth.unpack(pcaprecord.packet)
            ip = SimpleEthernet.IP()
            ip.unpack(eth.payload)
            udp_packet = SimpleEthernet.UDP()
            udp_packet.unpack(ip.payload)
            (ctrl_word,) = struct.unpack('>I',udp_packet.payload[:4])
            if ctrl_word == 0x11000000: # This is a rough guess assuming the control word is 0x11000000
                inetx_packet = inetx.iNetX()
                inetx_packet.unpack(udp_packet.payload)

                #----------------------------
                # Check for dropped packet
                #----------------------------
                if inetx_packet.streamid not in PreviousSeqNum:
                    PreviousSeqNum[inetx_packet.streamid] = inetx_packet.sequence
                else:
                    if PreviousSeqNum[inetx_packet.streamid]+1 != inetx_packet.sequence:
                        print("ERROR: Dropped {} packets on streamid={:#x} at packet count={}".format(inetx_packet.sequence - PreviousSeqNum[inetx_packet.streamid] + 1,inetx_packet.streamid,packet_count))
                    PreviousSeqNum[inetx_packet.streamid] = inetx_packet.sequence

                print("----- StreamID={:#10x} SourceIP= {:10s} -----".format(inetx_packet.streamid,ip_packet.srcip))
                #--------------------------------------------------------------------------------
                # Packets on stream id 0x11121314 is a parser aligned block so lets look at this
                #--------------------------------------------------------------------------------
                if inetx_packet.streamid == 0x11121314:
                    parser_aligned_packet = ParserAligned.ParserAlignedPacket()
                    # unpack the _payload as the parser data
                    parser_aligned_packet.unpack(inetx_packet.payload)

                    # Loop through all the blocks in the packet and spit them out
                    for pblock in parser_aligned_packet.parserblocks:
                        (payload_data,) =struct.unpack('>I',pblock.payload)
                        print("Sequence Number = {:8} Quadbyes={:5} Msgcnt={:5} BusId={:4} Elapsed={:20} ".format(inetx_packet.sequence, pblock.quadbytes,pblock.messagecount,pblock.busid,pblock.elapsedtime,payload_data))


            packet_count += 1

        except NotImplementedError:
            # We received a packet that we don't care about. So skip silently
            packet_count += 1
            pass

        except IOError:
            # We are at the end of the file so lets jump to the next file
            print ( "End of file reached")
            exit()
示例#40
0

import sys
sys.path.append("..")

import AcraNetwork.Pcap as pcap
import csv
import AcraNetwork.iNetX as inetx


# Modify this
pcapf = "../test/inetx_test.pcap"
streamid = 0xca
csv_output = "ts.csv"

csvfile = open(csv_output, 'wb')
csvwriter = csv.writer(csvfile)
csvwriter.writerow(["Packet Number", "Seconds", "Nanoseconds"])

pcapfile = pcap.Pcap(pcapf, mode="r")
for idx, record in enumerate(pcapfile):
    inetx_pkt = inetx.iNetX()
    try:
        inetx_pkt.unpack(record.payload[0x2a:])
    except:
        pass
    else:
        if inetx_pkt.streamid == streamid:
            csvwriter.writerow([idx+1, inetx_pkt.ptptimeseconds, inetx_pkt.ptptimenanoseconds])