예제 #1
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("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()
예제 #2
0
    def test_readUDP(self):
        TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__),
                                         'test_input.pcap')
        p = pcap.Pcap(TESTDATA_FILENAME)
        p.readGlobalHeader()
        mypcaprecord = p.readAPacket()
        e = Ethernet.Ethernet()
        e.regress = False
        e.unpack(mypcaprecord.packet)
        self.assertEqual(e.srcmac, 0x0018f8b84454)
        self.assertEqual(e.dstmac, 0xe0f847259336)
        self.assertEqual(e.type, 0x0800)

        i = IP()
        i.regress = False
        i.unpack(e.payload)
        self.assertEqual(i.dstip, "192.168.1.110")
        self.assertEqual(i.srcip, "213.199.179.165")
        self.assertEqual(i.protocol, 0x6)
        self.assertEqual(i.ttl, 48)
        self.assertEqual(i.flags, 0x2)
        self.assertEqual(i.id, 0x4795)
        self.assertEqual(i.len, 56)

        self.assertEqual(i.dstip, 3232235886)
        self.assertEqual(i.srcip, 3586634661)

        p.close()
예제 #3
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("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_unpackIEANFromPcap(self):
     '''Read all the IENA packets in a pcap file and check each field'''
     p = pcap.Pcap("iena_test.pcap")
     p.readGlobalHeader()
     sequencenum = 195
     exptime = 0x1d102f800
     while True:
         # Loop through the pcap file reading one packet at a time
         try:
             mypcaprecord = p.readAPacket()
         except IOError:
             # End of file reached
             break
         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 iena packet
         i = iena.IENA()
         i.unpack(u.payload)
         self.assertEquals(i.key, 0x1a)
         self.assertEquals(i.size, 24)
         self.assertEquals(i.status, 0)
         self.assertEquals(i.keystatus, 0)
         self.assertEquals(i.sequence, sequencenum)
         sequencenum += 1
         self.assertEqual(i.timeusec, exptime)
         exptime += 0x186a0  # The timestamp increments by a fixed number of microseconds
         self.assertEquals(i.endfield, 0xdead)
예제 #5
0
 def test_unpackIEANFromPcap(self):
     '''Read all the IENA packets in a pcap file and check each field'''
     TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__),
                                      'iena_test.pcap')
     p = pcap.Pcap(TESTDATA_FILENAME)
     p.readGlobalHeader()
     sequencenum = 195
     exptime = 0x1d102f800
     while True:
         # Loop through the pcap file reading one packet at a time
         try:
             mypcaprecord = p.readAPacket()
         except IOError:
             # End of file reached
             break
         e = Ethernet.Ethernet()
         e.unpack(mypcaprecord.packet)
         i = ip.IP()
         i.unpack(e.payload)
         u = udp.UDP()
         u.unpack(i.payload)
         # Now I have a payload that will be an iena packet
         ie = iena.IENA()
         ie.unpack(u.payload)
         self.assertEqual(ie.key, 0x1a)
         self.assertEqual(ie.size, 24)
         self.assertEqual(ie.status, 0)
         self.assertEqual(ie.keystatus, 0)
         self.assertEqual(ie.sequence, sequencenum)
         sequencenum += 1
         self.assertEqual(ie.timeusec, exptime)
         exptime += 0x186a0  # The timestamp increments by a fixed number of microseconds
         self.assertEqual(ie.endfield, 0xdead)
     p.close()
예제 #6
0
    def test_unpackMultiplePackets(self):
        sequencenum = 1011
        TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'inetx_test.pcap')
        mypcap = pcap.Pcap(TESTDATA_FILENAME)
        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.assertEqual(inetxpacket.sequence,sequencenum)
            sequencenum += 1
        mypcap.close()
예제 #7
0
 def test_readARecord(self):
     p = pcap.Pcap("test_input.pcap")
     p.readGlobalHeader()
     mypcaprecord = p.readAPacket()
     self.assertEqual(mypcaprecord.sec, 1419678111)
     self.assertEqual(mypcaprecord.usec, 811463)
     self.assertEqual(mypcaprecord.orig_len, 70)
     self.assertEqual(mypcaprecord.incl_len, 70)
예제 #8
0
    def test_unpackTCPFromPcap(self):
        '''
        Read all the TCP packets in a pcap file and check each field
        '''
        filename = 'pcap/tcp_test.pcap'
        TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), filename)
        p = pcap.Pcap(TESTDATA_FILENAME)
        p.readGlobalHeader()
        sequencenum = 195
        exptime = 0x1d102f800
        mypcaprecord = p.readAPacket()
        e = Ethernet.Ethernet()
        e.unpack(mypcaprecord.packet)
        i = ip.IP()
        i.unpack(e.payload)
        # Now I have a payload that will be an tcp packet
        t = tcp.TCP()
        t.unpack(i.payload)
        self.assertEqual(t.src, 55431)
        self.assertEqual(t.dst, 389)
        self.assertEqual(t.sequence, 2170942011)
        self.assertEqual(t.acknowledge, 0)
        self.assertEqual(t.flags, 32770)
        self.assertEqual(t.window, 8192)
        self.assertEqual(t.checksum, 57928)
        self.assertEqual(t.urgentptr, 0)

        self.assertEqual(e.ip.tcp.src, 55431)
        self.assertEqual(e.ip.tcp.dst, 389)
        self.assertEqual(e.ip.tcp.sequence, 2170942011)
        self.assertEqual(e.ip.tcp.acknowledge, 0)
        self.assertEqual(e.ip.tcp.flags, 32770)
        self.assertEqual(e.ip.tcp.window, 8192)
        self.assertEqual(e.ip.tcp.checksum, 57928)
        self.assertEqual(e.ip.tcp.urgentptr, 0)

        mypcaprecord = p.readAPacket()
        e = Ethernet.Ethernet()
        e.unpack(mypcaprecord.packet)
        self.assertEqual(e.ip.tcp.src, 55432)
        self.assertEqual(e.ip.tcp.dst, 389)
        self.assertEqual(e.ip.tcp.sequence, 1946064890)
        self.assertEqual(e.ip.tcp.acknowledge, 0)
        self.assertEqual(e.ip.tcp.flags, 32770)
        self.assertEqual(e.ip.tcp.window, 8192)
        self.assertEqual(e.ip.tcp.checksum, 18928)
        self.assertEqual(e.ip.tcp.urgentptr, 0)

        self.assertEqual(e.isPacket('ip'), True)
        self.assertEqual(e.isPacket('tcp'), True)
        self.assertEqual(e.isPacket('udp'), False)
        self.assertEqual(e.isPacket('IP'), True)
        self.assertEqual(e.isPacket('TCP'), True)
        self.assertEqual(e.isPacket('UDP'), False)
        self.assertEqual(e.packetpath, ['Ethernet', 'ip', 'tcp'])
        self.assertEqual(e.ip.packetpath, ['ip', 'tcp'])

        p.close()
예제 #9
0
 def test_writeARecord(self):
     p = pcap.Pcap("_tmp.pcap", forreading=False)
     p.writeGlobalHeader()
     r = pcap.PcapRecord()
     r.setCurrentTime()
     r.packet = struct.pack("H", 0x5)
     p.writeARecord(r)
     p.close()
     p = pcap.Pcap("_tmp.pcap")
     p.readGlobalHeader()
     self.assertEqual(p.magic, 0xa1b2c3d4)
     self.assertEqual(p.network, 1)
     self.assertEqual(p.sigfigs, 0)
     self.assertEqual(p.snaplen, 65535)
     self.assertEqual(p.versionmaj, 2)
     self.assertEqual(p.versionmin, 4)
     self.assertEqual(p.zone, 0)
     self.assertEqual(p.filesize, 42)
     os.remove("_tmp.pcap")
예제 #10
0
 def test_readARecord(self):
     TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__),
                                      'test_input.pcap')
     p = pcap.Pcap(TESTDATA_FILENAME)
     p.readGlobalHeader()
     mypcaprecord = p.readAPacket()
     self.assertEqual(mypcaprecord.sec, 1419678111)
     self.assertEqual(mypcaprecord.usec, 811463)
     self.assertEqual(mypcaprecord.orig_len, 70)
     self.assertEqual(mypcaprecord.incl_len, 70)
     p.close()
예제 #11
0
 def test_readTestFile(self):
     p = pcap.Pcap("test_input.pcap")
     p.readGlobalHeader()
     self.assertEqual(p.magic, 0xa1b2c3d4)
     self.assertEqual(p.network, 1)
     self.assertEqual(p.sigfigs, 0)
     self.assertEqual(p.snaplen, 262144)
     self.assertEqual(p.versionmaj, 2)
     self.assertEqual(p.versionmin, 4)
     self.assertEqual(p.zone, 0)
     self.assertEqual(p.filesize, 704)
     p.close()
예제 #12
0
 def test_readTestFile(self):
     TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__),
                                      'test_input.pcap')
     p = pcap.Pcap(TESTDATA_FILENAME)
     p.readGlobalHeader()
     self.assertEqual(p.magic, 0xa1b2c3d4)
     self.assertEqual(p.network, 1)
     self.assertEqual(p.sigfigs, 0)
     self.assertEqual(p.snaplen, 262144)
     self.assertEqual(p.versionmaj, 2)
     self.assertEqual(p.versionmin, 4)
     self.assertEqual(p.zone, 0)
     self.assertEqual(p.filesize, 704)
     p.close()
예제 #13
0
    def test_readMultiplePackets(self):
        TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__),
                                         'test_input.pcap')
        p = pcap.Pcap(TESTDATA_FILENAME)
        p.silent = True
        packets = p.parse()

        self.assertEqual(packets[0].eth.srcmac, 0x0018f8b84454)
        self.assertEqual(packets[0].eth.dstmac, 0xe0f847259336)
        self.assertEqual(packets[0].eth.type, 0x0800)

        self.assertEqual(packets[1].eth.srcmac, 0xe0f847259336)
        self.assertEqual(packets[1].eth.dstmac, 0x0018f8b84454)
        self.assertEqual(packets[1].eth.type, 0x0800)

        p.close()
예제 #14
0
    def test_readUDP(self):
        p = pcap.Pcap("test_input.pcap")
        p.readGlobalHeader()
        mypcaprecord = p.readAPacket()
        e = SimpleEthernet.Ethernet()
        e.unpack(mypcaprecord.packet)
        self.assertEqual(e.srcmac, 0x0018f8b84454)
        self.assertEqual(e.dstmac, 0xe0f847259336)
        self.assertEqual(e.type, 0x0800)

        i = SimpleEthernet.IP()
        i.unpack(e.payload)
        self.assertEqual(i.dstip, "192.168.1.110")
        self.assertEqual(i.srcip, "213.199.179.165")
        self.assertEqual(i.protocol, 0x6)
        self.assertEqual(i.ttl, 48)
        self.assertEqual(i.flags, 0x2)
        self.assertEqual(i.id, 0x4795)
        self.assertEqual(i.len, 56)
예제 #15
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)
예제 #16
0
 def test_unpackiNetFromPcap(self):
     TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'inetx_test.pcap')
     p = pcap.Pcap(TESTDATA_FILENAME)
     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.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)
     p.close()
예제 #17
0
    def test_unpackTTEFromPcap(self):
        '''
        Read all the TCP packets in a pcap file and check each field
        '''
        filename = 'pcap/tte_test.pcap'
        TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), filename)
        p = pcap.Pcap(TESTDATA_FILENAME)
        p.silent = True
        packets = p.parse()
        
        self.assertEqual(len(packets), 4)
        self.assertEqual(packets[0].eth.isPacket('TTE'), True)
        self.assertEqual(packets[0].eth.isPacket('TCP'), False)
        
        t = packets[0].eth.tte
        self.assertEqual(t.integration_cycle, 0)
        self.assertEqual(t.membership_new, 1)
        self.assertEqual(t.sync_priority, 128)
        self.assertEqual(t.sync_domain, 0)
        self.assertEqual(t.type, 0)
        self.assertEqual(t.transparent_clock, 110100480)
        self.assertEqual(t.type_text, 'Unknown')
        self.assertEqual(t.macdest, 0x3000101)
        self.assertEqual(t.ctid, 0xffff)
        
        t = packets[1].eth.tte
        self.assertEqual(t.integration_cycle, 0)
        self.assertEqual(t.membership_new, 1)
        self.assertEqual(t.sync_priority, 128)
        self.assertEqual(t.sync_domain, 0)
        self.assertEqual(t.type, 0)
        self.assertEqual(t.transparent_clock, 110100480)
        self.assertEqual(t.type_text, 'Unknown')
        self.assertEqual(t.macdest, 0x11223344)
        self.assertEqual(t.ctid, 0x5566)

        p.close()
예제 #18
0
 def test_missingreadfile(self):
     self.assertRaises(IOError, lambda: pcap.Pcap("nofile.pcap"))
예제 #19
0
 def test_defaultMagicNumber(self):
     p = pcap.Pcap("_tmp.pcap", forreading=False)
     self.assertEqual(p.magic, 0xa1b2c3d4)
예제 #20
0
                    choices=["udp", "iena", "inetx"],
                    help='The type of payload, udp iena or inetx')
parser.add_argument('--ignoretime',
                    required=False,
                    action='store_true',
                    default=False)
args = parser.parse_args()

# constants
PCAP_FNAME = "output_test.pcap"
PACKETS_TO_WRITE = 50000
PAYLOAD_SIZE = 1300  # size of the payload in bytes
HEADER_SIZE = {'udp': 58, 'inetx': 86, 'iena': 74}

# Write out a pcapfile with each inetx and iena packet generated
mypcap = pcap.Pcap(PCAP_FNAME, forreading=False)
mypcap.writeGlobalHeader()
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":
예제 #21
0
 def test_defaultVersionMaj(self):
     p = pcap.Pcap("_tmp.pcap", forreading=False)
     self.assertEqual(p.versionmaj, 2)
     p.close()
예제 #22
0
 def test_missingfilename(self):
     self.assertRaises(TypeError, lambda: pcap.Pcap())
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():

    #----------------------------------
    # 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
예제 #25
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)
예제 #26
0
 def test_defaultVersionMin(self):
     p = pcap.Pcap("_tmp.pcap", forreading=False)
     self.assertEqual(p.versionmin, 4)