Esempio n. 1
0
        public void ReadDumpFile(string path)
        {
            // Opens device
            OfflinePacketDevice device = new OfflinePacketDevice(path);

            using (PacketCommunicator communicator = device.Open(0x10000, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                //communicator.SetFilter("ip and tcp");
                //communicator.ReceivePackets(0, DispatcherHandler);

                Packet packet;
                communicator.ReceivePacket(out packet);

                while (packet != null)
                {
                    if (IsHttpRequest(packet))
                    {
                        HttpRequestDatagram request = packet?.Ethernet?.Ip?.Tcp?.Http as HttpRequestDatagram;
                        ParseHttpRequest(request);
                    }

                    // Gets next packet
                    communicator.ReceivePacket(out packet);
                }
            }
        }
Esempio n. 2
0
        public void DumpWithoutDeviceTest()
        {
            string filename = Path.GetTempPath() + @"dump.pcap";

            Packet expectedPacket = PacketBuilder.Build(DateTime.Now,
                                                        new EthernetLayer
                                                        {
                                                            Source = new MacAddress(1),
                                                            Destination = new MacAddress(2),
                                                            EtherType = EthernetType.QInQ,
                                                        },
                                                        new PayloadLayer
                                                        {
                                                            Data = new Datagram(new byte[] {1, 2, 3})
                                                        });
            PacketDumpFile.Dump(filename, DataLinkKind.Ethernet, PacketDevice.DefaultSnapshotLength,
                                new[] {expectedPacket});
  
            using (PacketCommunicator communicator = new OfflinePacketDevice(filename).Open())
            {
                Packet actualPacket;
                PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out actualPacket);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                Assert.AreEqual(expectedPacket, actualPacket);
                MoreAssert.IsInRange(expectedPacket.Timestamp.AddMicroseconds(-2), expectedPacket.Timestamp.AddMicroseconds(1), actualPacket.Timestamp);
            }
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            //var hex = "";
            if (args.Length != 1)
            {
                Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>");
                return;
            }
            // Create the offline device
            OfflinePacketDevice selectedDevice = new OfflinePacketDevice(args[0]);

            // Open the capture file
            using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                communicator.SetFilter("tcp");
                // start the capture
                var i = 0;
                communicator.ReceiveSomePackets(out i, 1000, PacketHandler);
                Console.WriteLine(i);
                //communicator.ReceivePackets(0, PacketHandler);
            }

            /*string docHeader = "25504446";
             * string docFooter = "0D0A2525454F460D0A";
             * int pFrom = hex.IndexOf(docHeader) + docHeader.Length;
             * int pTo = hex.LastIndexOf(docFooter);
             * String result2 = hex.Substring(pFrom, pTo - pFrom);*/
        }
        public void DumpWithoutDeviceTest()
        {
            string filename = Path.GetTempPath() + @"dump.pcap";

            Packet expectedPacket = PacketBuilder.Build(DateTime.Now,
                                                        new EthernetLayer
            {
                Source      = new MacAddress(1),
                Destination = new MacAddress(2),
                EtherType   = EthernetType.QInQ,
            },
                                                        new PayloadLayer
            {
                Data = new Datagram(new byte[] { 1, 2, 3 })
            });

            PacketDumpFile.Dump(filename, DataLinkKind.Ethernet, PacketDevice.DefaultSnapshotLength,
                                new[] { expectedPacket });

            using (PacketCommunicator communicator = new OfflinePacketDevice(filename).Open())
            {
                Packet actualPacket;
                PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out actualPacket);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                Assert.AreEqual(expectedPacket, actualPacket);
                MoreAssert.IsInRange(expectedPacket.Timestamp.AddMicroseconds(-2), expectedPacket.Timestamp.AddMicroseconds(1), actualPacket.Timestamp);
            }
        }
Esempio n. 5
0
		/// <summary>
		/// Start an off-line capture
		/// </summary>
		/// <param name="file">The dump file name to capture</param>
		/// <param name="callback">Callback to handle packets</param>
		/// <param name="IsBadDumpFile">Flag indicates whether the dump file is invalid</param>
		public static void StartOfflineCapture(string file, HandlePacket callback, ref bool IsBadDumpFile)
		{
			PacketCommunicator pc = communicator;
			try {
				// Create the off-line device
				OfflinePacketDevice selectedDevice = new OfflinePacketDevice(file);

				communicator =
					selectedDevice.Open(65536,                      // portion of the packet to capture
																	// 65536 guarantees that the whole packet will be captured on all the link layers
							PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
							1000);                                  // read timeout
				// Compile the filter
				using (BerkeleyPacketFilter filter =
					communicator.CreateFilter(SnifferConfig.Filter.FilterString)) {
					communicator.SetFilter(filter);
				}

				// Read and dispatch packets until EOF is reached
				communicator.ReceivePackets(0, callback);
			}
			catch (Exception) {
				IsBadDumpFile = true;
			}
			finally {
				if (pc != null)
					communicator = pc;
			}

		}
Esempio n. 6
0
        /// <summary>
        /// Retrieve details about a packet
        /// </summary>
        /// <param name="index">Index of the packet to retrieve</param>
        /// <param name="ctrl">UI elements</param>
        public static void RetrievePacketDetails(int index, object[] ctrl)
        {
            // Create the off-line device
            OfflinePacketDevice selectedDevice = new OfflinePacketDevice(detailsFile);

            // Open the capture file
            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,                                  // portion of the packet to capture
                                                                                   // 65536 guarantees that the whole packet will be captured on all the link layers
                                           PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                           1000))                                  // read timeout
            {
                Packet packet = null;
                try {
                    while (index-- > 0)
                    {
                        communicator.ReceivePacket(out packet);
                    }
                }
                catch (Exception) {
                    return;
                }


                PacketParser.ParsePacket(packet, ctrl);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Start an off-line capture
        /// </summary>
        /// <param name="file">The dump file name to capture</param>
        /// <param name="callback">Callback to handle packets</param>
        /// <param name="IsBadDumpFile">Flag indicates whether the dump file is invalid</param>
        public static void StartOfflineCapture(string file, HandlePacket callback, ref bool IsBadDumpFile)
        {
            PacketCommunicator pc = communicator;

            try {
                // Create the off-line device
                OfflinePacketDevice selectedDevice = new OfflinePacketDevice(file);

                communicator =
                    selectedDevice.Open(65536,                                  // portion of the packet to capture
                                                                                // 65536 guarantees that the whole packet will be captured on all the link layers
                                        PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                        1000);                                  // read timeout
                // Compile the filter
                using (BerkeleyPacketFilter filter =
                           communicator.CreateFilter(SnifferConfig.Filter.FilterString)) {
                    communicator.SetFilter(filter);
                }

                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, callback);
            }
            catch (Exception) {
                IsBadDumpFile = true;
            }
            finally {
                if (pc != null)
                {
                    communicator = pc;
                }
            }
        }
Esempio n. 8
0
        // Long time operation
        public void Load(string filepath)
        {
            // file validation
            if (!Path.GetExtension(filepath).Equals(".pcap", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException("The file is nonexist or not valid");
            }

            Reset();

            dev = new OfflinePacketDevice(filepath);

            FileInfo info = new FileInfo(filepath);

            totalbytes = info.Length;

            ReportProgress(ProgressSource.Load, Prog_ReadFileStart, "读取文件...");


            // Read all packets from file until EOF
            using (PacketCommunicator communicator = dev.Open())
            {
                communicator.ReceivePackets(0, OnPacketArrival);
            }

            ReportProgress(ProgressSource.Load, Prog_SortPacketsStart, "对数据包排序...");
            plist.Sort();

            ReportProgress(ProgressSource.Load, Prog_AnalyzePacketsStart, "分析中...");
            Analyze();
            fileLoaded = true;

            ReportProgress(ProgressSource.Load, 100, "完成");
        }
Esempio n. 9
0
        public static void Test_ReadPacketsFromDumpFile_01()
        {
            // from project ReadingPacketsFromADumpFile
            _tr.WriteLine("Test_ReadPacketsFromDumpFile_01");

            string dumpFile = @"dump\dump.pcap";

            dumpFile = GetPath(dumpFile);
            _tr.WriteLine("read packets from dump file \"{0}\"", dumpFile);

            // Create the offline device
            OfflinePacketDevice device = new OfflinePacketDevice(dumpFile);

            __communicator = null;
            //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution);
            _rs.OnAbortExecution = OnAbortExecution;
            try
            {
                // Open the capture file
                using (__communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    // Read and dispatch packets until EOF is reached
                    __communicator.ReceivePackets(0, ReadPacketsFromDumpFile);
                }
            }
            finally
            {
                //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution);
            }
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            // Send anonymous statistics about the usage of Pcap.Net
            PcapDotNet.Analysis.PcapDotNetAnalysis.OptIn = true;

            // Check command line
            if (args.Length != 1)
            {
                Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>");
                return;
            }

            // Create the offline device
            OfflinePacketDevice selectedDevice = new OfflinePacketDevice(args[0]);

            // Open the capture file
            using (PacketCommunicator communicator =
                selectedDevice.Open(65536,                                  // portion of the packet to capture
                                                                            // 65536 guarantees that the whole packet will be captured on all the link layers
                                    PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                    1000))                                  // read timeout
            {
                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, DispatcherHandler);
            }
        }
Esempio n. 11
0
        private async Task LoadFile()
        {
            var file = txtPath.Text;

            if (!File.Exists(file))
            {
                throw new Exception("File not found - " + file);
            }

            Log("Loading packets from file " + file);

            var dumpFile = new OfflinePacketDevice(file);

            var packets = new List <Packet>();

            await Task.Run(() =>
            {
                using (var communicator =
                           dumpFile.Open(65536,
                                         PacketDeviceOpenAttributes.None,
                                         1000))
                {
                    while (true)
                    {
                        try
                        {
                            communicator.ReceivePacket(out var packet);
                            if (packet == null)
                            {
                                break;
                            }

                            packets.Add(packet);
                        }
                        catch (Exception e)
                        {
                            Log(e);
                        }
                    }
                }

                _packets = packets.Select((p, i) => new PacketInfo
                {
                    Num       = i + 1,
                    TimeStamp = p.Timestamp,
                    Length    = p.Length,
                    Kind      = p.DataLink.Kind,
                    Protocol  = GetPacketProto(p).ToString(),
                    Packet    = p
                }).ToArray();
            });

            lstPackets.SetObjects(_packets);

            lstPackets.AutoResizeColumns();
            lstPackets.CalculateReasonableTileSize();

            SetColumnWidth("Length", 80);
        }
Esempio n. 12
0
 public static PacketDevice SelectDevice(string deviceName)
 {
     PacketDevice device = null;
     if (deviceName.StartsWith("rpcap://"))
         device = (from d in LivePacketDevice.AllLocalMachine where d.Name == deviceName select d).FirstOrDefault();
     else
         device = new OfflinePacketDevice(deviceName);
     return device;
 }
Esempio n. 13
0
        public void ReadNonExistingUnicodeFilenameTest()
        {
            const string        ReadUnicodeFilename = "abc_non_existing_\u00F9_\u05D0\u05D1\u05D2.pcap";
            OfflinePacketDevice device = new OfflinePacketDevice(ReadUnicodeFilename);

            using (PacketCommunicator communicator = device.Open())
            {
                Assert.Fail();
            }
        }
Esempio n. 14
0
        public void AddDevice(string path)
        {
            OfflinePacketDevice device = new OfflinePacketDevice(path);

            if (device == null)
            {
                return;
            }

            this.Devices.Add(device);
        }
        public static void Parse(string fileName, Action <Packet> handler)
        {
            // Create the offline device
            OfflinePacketDevice selectedDevice = new OfflinePacketDevice(fileName);

            // Open the capture file
            using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, new HandlePacket(handler));
            }
        }
Esempio n. 16
0
        public SY_Sort_PCap(String path)
        {
            OfflinePacketDevice selectedDevice = new OfflinePacketDevice(path);

            list = new List <SY_Sort_PCap>();

            // Open the capture file
            using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, DispatcherHandler);
            }
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            List <string> wordlis = LoadWordList();


            // Create the offline device
            OfflinePacketDevice selectedDevice = new OfflinePacketDevice("03.cap");

            // Open the capture file
            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,                                  // portion of the packet to capture
                                                                                   // 65536 guarantees that the whole packet will be captured on all the link layers
                                           PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                           1000))                                  // read timeout
            {
                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, DispatcherHandler);
            }

            byte[] apMac  = GetPortion(fourWayHandShake[0], 4, 6);
            byte[] stMac  = GetPortion(fourWayHandShake[0], 10, 6);
            byte[] aNonce = GetPortion(fourWayHandShake[0], 51, 32);
            byte[] sNonce = GetPortion(fourWayHandShake[1], 51, 32);
            byte[] mic    = GetPortion(fourWayHandShake[1], 115, 16);
            byte[] eapol  = GetPortion(fourWayHandShake[1], 34, fourWayHandShake[1].Length - 34);

            for (int i = eapol.Length - 40; i < eapol.Length - 40 + 16; i++)
            {
                eapol[i] = 0;
            }

            bool isFind = false;

            foreach (var pass in wordlis)
            {
                Console.WriteLine(pass);
                byte[] pmk = CalculatePMK(Encoding.ASCII.GetBytes(pass), Encoding.ASCII.GetBytes("k_and_s"));
                byte[] ptk = CalculatePTK(pmk, stMac, apMac, sNonce, aNonce);
                if (PtkIsValid(ptk, eapol, mic))
                {
                    Console.WriteLine("Key Found ({0})", pass);
                    isFind = true;
                    break;
                }
            }

            if (!isFind)
            {
                Console.WriteLine("Key Not Found");
            }
        }
Esempio n. 18
0
        public static void ReconstructSingleFileSharpPcap(string capFile)
        {
            //PcapDevice device;
            PacketDevice device;

            //FileInfo fi = new FileInfo(capFile);
            var fi = zFile.CreateFileInfo(capFile);

            _path = fi.DirectoryName + "\\";
            try
            {
                //Get an offline file pcap device
                //device = SharpPcap.GetPcapOfflineDevice(capFile);
                device = new OfflinePacketDevice(capFile);
                //Open the device for capturing
                //device.PcapOpen();
                using (PacketCommunicator communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    communicator.ReceivePackets(0, device_PcapOnPacketArrival);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            //Register our handler function to the 'packet arrival' event
            //device.PcapOnPacketArrival += new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);

            // FOR THIS LINE TO WORK YOU NEED TO CHANGE THE
            // SHARPPCAP LIBRARY MANUALLY AND REMOVE PcapSetFilter method
            // FROM PcapOfflineDevice
            //
            // add a filter so we get only tcp packets
            // device.PcapSetFilter("tcp");

            //Start capture 'INFINTE' number of packets
            //This method will return when EOF reached.
            //device.PcapCapture(SharpPcap.INFINITE);

            //Close the pcap device
            //device.PcapClose();

            // Clean up
            foreach (TcpRecon tr in sharpPcapDict.Values)
            {
                tr.Close();
            }
            sharpPcapDict.Clear();
        }
Esempio n. 19
0
        public static PacketDevice SelectDevice(string deviceName)
        {
            PacketDevice device = null;

            if (deviceName.StartsWith("rpcap://"))
            {
                device = (from d in LivePacketDevice.AllLocalMachine where d.Name == deviceName select d).FirstOrDefault();
            }
            else
            {
                device = new OfflinePacketDevice(deviceName);
            }
            return(device);
        }
    public void ParsePacket(string filePath)
    {
        OfflinePacketDevice selectedDevice = new OfflinePacketDevice(filePath);

        using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
        {
            try
            {
                communicator.ReceivePackets(0, AnalyzeCurrentPacket);
            }
            catch { }
        }
        var AnalyzedSession = CombineOpenCloseSessions();
    }
Esempio n. 21
0
 public void Reset()
 {
     plist.Clear();
     presum.Clear();
     bpsList.Clear();
     ppsList.Clear();
     dev         = null;
     loadedbytes = 0;
     totalbytes  = 0;
     lastreport  = -1;
     fileLoaded  = false;
     Earliest    = DateTime.MaxValue;
     Latest      = DateTime.MinValue;
 }
Esempio n. 22
0
        public static void ReconstructSingleFileSharpPcap(string capFile)
        {
            //PcapDevice device;
            PacketDevice device;

            //FileInfo fi = new FileInfo(capFile);
            var fi = zFile.CreateFileInfo(capFile);
            _path = fi.DirectoryName + "\\";
            try
            {
                //Get an offline file pcap device
                //device = SharpPcap.GetPcapOfflineDevice(capFile);
                device = new OfflinePacketDevice(capFile);
                //Open the device for capturing
                //device.PcapOpen();
                using (PacketCommunicator communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    communicator.ReceivePackets(0, device_PcapOnPacketArrival);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            //Register our handler function to the 'packet arrival' event
            //device.PcapOnPacketArrival += new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);

            // FOR THIS LINE TO WORK YOU NEED TO CHANGE THE
            // SHARPPCAP LIBRARY MANUALLY AND REMOVE PcapSetFilter method
            // FROM PcapOfflineDevice
            //
            // add a filter so we get only tcp packets
            // device.PcapSetFilter("tcp");

            //Start capture 'INFINTE' number of packets
            //This method will return when EOF reached.
            //device.PcapCapture(SharpPcap.INFINITE);

            //Close the pcap device
            //device.PcapClose();

            // Clean up
            foreach (TcpRecon tr in sharpPcapDict.Values)
            {
                tr.Close();
            }
            sharpPcapDict.Clear();
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            if (FileCheck(fileName))
            {
                PacketDevice selectedDevice = new OfflinePacketDevice(fileName);
                // Open the device
                using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    communicator.ReceivePackets(0, PacketHandler);
                }
            }

            Console.WriteLine(arr);
            Console.ReadLine();
        }
Esempio n. 24
0
        public static OfflinePacketDevice GetOfflineDevice(int numPackets, Packet packet, TimeSpan intervalBetweenPackets, string dumpFilename, string readFilename = null)
        {
            if (readFilename == null)
            {
                readFilename = dumpFilename;
            }
            PacketCommunicator communicator;

            using (communicator = LivePacketDeviceTests.OpenLiveDevice())
            {
                using (PacketDumpFile dumpFile = communicator.OpenDump(dumpFilename))
                {
                    int lastPosition = 0;
                    for (int i = 0; i != numPackets; ++i)
                    {
                        if (intervalBetweenPackets != TimeSpan.Zero && i != 0)
                        {
                            DateTime timestamp = packet.Timestamp;
                            timestamp = timestamp.Add(intervalBetweenPackets);
                            packet    = new Packet(packet.Buffer, timestamp, packet.DataLink);
                        }
                        dumpFile.Dump(packet);
                        MoreAssert.IsBigger(lastPosition, dumpFile.Position);
                        lastPosition = dumpFile.Position;
                        dumpFile.Flush();
                    }
                }
            }

            if (readFilename != dumpFilename)
            {
                if (File.Exists(readFilename))
                {
                    File.Delete(readFilename);
                }
                File.Move(dumpFilename, readFilename);
            }

            OfflinePacketDevice device = new OfflinePacketDevice(readFilename);

            Assert.AreEqual(0, device.Addresses.Count);
            Assert.AreEqual(string.Empty, device.Description);
            Assert.AreEqual(DeviceAttributes.None, device.Attributes);
            Assert.AreEqual(readFilename, device.Name);

            return(device);
        }
Esempio n. 25
0
        public static void Read(string file)
        {
            var selectedDevice = new OfflinePacketDevice(file);

            // Open the capture file
            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,                                  // portion of the packet to capture
                                                                                   // 65536 guarantees that the whole packet will be captured on all the link layers
                                           PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                           1000))                                  // read timeout
            {
                communicator.SetFilter("tcp port 1119 and ip net " + GameServerRange);

                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, DispatcherHandler);
            }
        }
Esempio n. 26
0
        public static void Read(string file)
        {
            var selectedDevice = new OfflinePacketDevice(file);

            // Open the capture file
            using (PacketCommunicator communicator =
                selectedDevice.Open(65536, // portion of the packet to capture
                                    // 65536 guarantees that the whole packet will be captured on all the link layers
                                    PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                    1000)) // read timeout
            {
                communicator.SetFilter("tcp port 1119 and ip net "+ GameServerRange);

                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, DispatcherHandler);
            }
        }
Esempio n. 27
0
 public MessageBoxResult Send(string PcapPath, PacketDevice Nic)
 {
     try
     {
         var capLength    = new FileInfo(PcapPath).Length;
         var selectedPcap = new OfflinePacketDevice(PcapPath);
         using (var inputCommunicator = selectedPcap.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
         {
             using (var outputCommunicator = Nic.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
             {
                 using (var sendBuffer = new PacketSendBuffer((uint)capLength))
                 {
                     var    numPackets   = 0;
                     var    falsePackets = 0;
                     Packet packet;
                     while (inputCommunicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok)
                     {
                         if ((packet.Count > 1514))
                         {
                             ++falsePackets;
                         }
                         else
                         {
                             sendBuffer.Enqueue(packet);
                             ++numPackets;
                         }
                     }
                     outputCommunicator.Transmit(sendBuffer, false);
                     return(MessageBox.Show(numPackets.ToString() + " " + "Packets were sent successfully,\n" +
                                            falsePackets.ToString() + " " + "Packets weren't sent successfully,\n" +
                                            " Would you like to exit?", "Success", MessageBoxButton.YesNo));
                 }
             }
         }
     }
     catch (System.ArgumentException)
     {
         return(MessageBox.Show("User Must Choose a file"));
     }
     catch (System.InvalidOperationException)
     {
         return(MessageBox.Show("Wrong File, only .pcap file supperted"));
     }
 }
        public static OfflinePacketDevice GetOfflineDevice(int numPackets, Packet packet, TimeSpan intervalBetweenPackets, string dumpFilename, string readFilename = null)
        {
            if (readFilename == null)
                readFilename = dumpFilename;
            PacketCommunicator communicator;
            using (communicator = LivePacketDeviceTests.OpenLiveDevice())
            {
                using (PacketDumpFile dumpFile = communicator.OpenDump(dumpFilename))
                {
                    int lastPosition = 0;
                    for (int i = 0; i != numPackets; ++i)
                    {
                        if (intervalBetweenPackets != TimeSpan.Zero && i != 0)
                        {
                            DateTime timestamp = packet.Timestamp;
                            timestamp = timestamp.Add(intervalBetweenPackets);
                            packet = new Packet(packet.Buffer, timestamp, packet.DataLink);
                        }
                        dumpFile.Dump(packet);
                        MoreAssert.IsBigger(lastPosition, dumpFile.Position);
                        lastPosition = dumpFile.Position;
                        dumpFile.Flush();
                    }
                }
            }

            if (readFilename != dumpFilename)
            {
                if (File.Exists(readFilename))
                    File.Delete(readFilename);
                File.Move(dumpFilename, readFilename);
            }

            OfflinePacketDevice device = new OfflinePacketDevice(readFilename);
            Assert.AreEqual(0, device.Addresses.Count);
            Assert.AreEqual(string.Empty, device.Description);
            Assert.AreEqual(DeviceAttributes.None, device.Attributes);
            Assert.AreEqual(readFilename, device.Name);

            return device;
        }
Esempio n. 29
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Create the offline device
            OfflinePacketDevice selectedDevice = new OfflinePacketDevice(System.IO.Path.Combine(inpath.Text, "SV.pcap"));

            // Open the capture file
            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,                                  // portion of the packet to capture
                                                                                   // 65536 guarantees that the whole packet will be captured on all the link layers
                                           PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                           1000))                                  // read timeout
            {
                communicator.SetFilter("ether proto 0x88ba");
                communicator.ReceivePackets(0, DispatcherHandler);
            }

            foreach (Data adata in data)
            {
                kek.Text += adata.ToString() + Environment.NewLine;
            }
        }
Esempio n. 30
0
        private static void ParseAndRead()
        {
            var device = new OfflinePacketDevice(@"C:\Users\Thomas\Desktop\dumpfile.pcap");

            // Open the capture file
            using (PacketCommunicator communicator = device.Open(65536,                                  // portion of the packet to capture
                                                                                                         // 65536 guarantees that the whole packet will be captured on all the link layers
                                                                 PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                                                 1000))                                  // read timeout
            {
                // Read and dispatch packets until EOF is reached
                try
                {
                    communicator.ReceivePackets(0, DispatcherHandler);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Tries to open packet on provided path
        /// </summary>
        /// <param name="path">Path to packet</param>
        /// <returns>Packet object with data</returns>
        public Packet TryOpenUserPacketFromFile(string path)
        {
            try
            {
                var providedPacket = new OfflinePacketDevice(path);
                using (PacketCommunicator communicator =
                           providedPacket.Open(65536,
                                               PacketDeviceOpenAttributes.Promiscuous,
                                               1000))
                {
                    Packet savedPacket;
                    communicator.ReceivePacket(out savedPacket);
                    return(savedPacket);
                }
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(null);
        }
Esempio n. 32
0
        public WiresharkFile(string filepath)
        {
            FileName        = filepath;
            PacketCount     = 0;
            TimePacketCount = 0;
            FileInfo file = new FileInfo(filepath);

            FileSizeKB    = file.Length / 1000;
            FileCreatedOn = file.CreationTime.ToString();
            FileEstTime   = 0;

            // Create the offline device
            OfflineDevice = new OfflinePacketDevice(filepath);

            // Count packets
            using (PacketCommunicator communicator =
                       OfflineDevice.Open(65536,                                  // portion of the packet to capture
                                                                                  // 65536 guarantees that the whole packet will be captured on all the link layers
                                          PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                          1000))                                  // read timeout
            {
                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, ProcessNewFilePackets);
            }

            // Estimate time
            using (PacketCommunicator communicator =
                       OfflineDevice.Open(65536,                                  // portion of the packet to capture
                                                                                  // 65536 guarantees that the whole packet will be captured on all the link layers
                                          PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                          1000))                                  // read timeout
            {
                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, EstimateTime);
            }

            Common.ConsoleWriteLine(ConsoleText);
            Common.ConsoleWriteLine(ConsoleText, "File Loaded: " + FileName.Substring(FileName.LastIndexOf("\\") + 1) + "\n   - SIP Packets = " + SIP_Packets + "\n   - RTP Packets = " + RTP_Packets);
        }
Esempio n. 33
0
        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = "C:\\Магистратура\\1 курс 2 семестр\\СОВвИ\\CTU-13-Dataset\\CTU-13-Dataset\\2 - взял";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = openFileDialog1.FileName;
                OfflinePacketDevice offlinePacketDevice = new OfflinePacketDevice(openFileDialog1.FileName);

                //offlinePacketDevice.

                PacketCommunicator communicator = offlinePacketDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000);                                // read timeout
                //communicator.ReceivePackets(0, DispatcherHandler);

                //List<Packet> packets = new List<Packet>();

                InfaDlyaLoadingPackets infa = new InfaDlyaLoadingPackets();
                infa.communicator = communicator;

                Task.Factory.StartNew(() => { LoadingPackets(infa); }); //Создание и запуск нового потока

                /*
                 * while (true)
                 * {
                 *  Packet packet;
                 *  communicator.ReceivePacket(out packet);
                 *
                 *  if (packet == null)
                 *  {
                 *      break;
                 *  }
                 *
                 *  packets.Add(packet);
                 *  textBoxLog.Text += packets.Count;
                 * }
                 */
            }
        }
Esempio n. 34
0
        public void start_capture(object path_to_file)
        {
            if (!(path_to_file is string))
            {
                throw new Exception("bad type of input given");
            }

            OfflinePacketDevice selectedDevice = new OfflinePacketDevice((string)path_to_file);

            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,                                  // portion of the packet to capture
                                                                                   // 65536 guarantees that the whole packet will be captured on all the link layers
                                           PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                           1000))                                  // read timeout
            {
                Packet packet;
                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        capturedPackets.Add(CapturedPacketManager.providePacket(packet));    // PacketHandler(packet);
                        break;

                    case PacketCommunicatorReceiveResult.Eof:
                        return;

                    default:
                        throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                    }
                } while (true);
            }
        }
Esempio n. 35
0
        static void Main(string[] args)
        {
            // Check command line
            if (args.Length != 1)
            {
                Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>");
                return;
            }

            // Create the offline device
            OfflinePacketDevice selectedDevice = new OfflinePacketDevice(args[0]);

            // Open the capture file
            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,                                  // portion of the packet to capture
                                                                                   // 65536 guarantees that the whole packet will be captured on all the link layers
                                           PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                           1000))                                  // read timeout
            {
                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, DispatcherHandler);
            }
        }
Esempio n. 36
0
        public static PacketDevice SelectDevice(string deviceName = null)
        {
            if (deviceName == null)
            {
                deviceName = @"rpcap://\Device\NPF_{BF8A52CB-F023-4F24-AA7E-958A8D1F3069}";
            }
            Trace.WriteLine("select device \"{0}\"", deviceName);
            PacketDevice device = null;

            if (deviceName.StartsWith("rpcap://"))
            {
                device = (from d in LivePacketDevice.AllLocalMachine where d.Name == deviceName select d).FirstOrDefault();
            }
            else
            {
                device = new OfflinePacketDevice(GetPath(deviceName));
            }
            if (device == null)
            {
                Trace.WriteLine("device not found");
            }
            return(device);
        }
Esempio n. 37
0
        private void tbtnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = @"C:\";
            openFileDialog1.Title            = "Browse Text Files";

            openFileDialog1.Filter           = "dump files (*.pcap)|*.pcap";
            openFileDialog1.FilterIndex      = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                OfflinePacketDevice selectedDevice = new OfflinePacketDevice(openFileDialog1.FileName);
                using (PacketCommunicator communicator =
                           selectedDevice.Open(65536,                                  // portion of the packet to capture
                                                                                       // 65536 guarantees that the whole packet will be captured on all the link layers
                                               PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                               1000))                                  // read timeout
                {
                    communicator.ReceivePackets(0, DispatcherHandler);
                }
            }
        }
        private void OpenDumpFileCommandExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter = "Pcap dump file|*.pcap",
                Title = "Open saved pcap dump file",
                FileName = "e:\\dump.pcap"
            };
            if (openFileDialog.ShowDialog().Value)
            {
                Captured.Clear();

                var selectedDevice = new OfflinePacketDevice(openFileDialog.FileName);
                capturedPacketsListBox.DataContext = Captured;

                using (var communicator = selectedDevice.Open(65536,
                                                              PacketDeviceOpenAttributes.Promiscuous,
                                                              1000))
                {
                    communicator.ReceivePackets(0, p => Captured.Add(p));
                }
                e.Handled = true;
            }
        }
Esempio n. 39
0
        /// <summary>
        /// experiment to parse packets in parallel
        /// </summary>
        /// <param name="pcapfile"></param>
        public void LoadDataParallel(string pcapfile)
        {
            Dictionary<int, Dictionary<string, double[]>> streamParameters = Globals.limitPCAP;
            try
            {
            int pktCnt = 0;
            frames = new List<byte[]>();
            using (PacketCommunicator communicator = new OfflinePacketDevice(pcapfile).Open(65536,                                  // portion of the packet to capture
                // 65536 guarantees that the whole packet will be captured on all the link layers
                                    PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                    1000))     // read timeout
            {
                //communicator.ReceiveSomePackets(out pktCnt, 10, parsePacketParrallel);
                communicator.ReceivePackets(0, getParallel);
                //communicator.ReceivePackets(0, parsePacketDownSampled);
                //communicator.ReceivePackets(0, parsePacketPTP);
            }

            //ThreadPool.GetMaxThreads(out threadCnt,out threadDone);
            ThreadPool.SetMaxThreads(50, 50);
            int threadCnt = 0;
            int threadDone = 0;
            ThreadPool.GetAvailableThreads(out threadCnt, out threadDone);

            if (frames.Count == 0) return;
            for (int i = 0; i != frames.Count - 1; i++)
            {
                ThreadPool.QueueUserWorkItem(state => parseFrame(frames[i], i));
            }
            //Parallel.For(0, frames.Count, i =>
            //    parseFrame(frames[i], i)
            //    );
            while (true)
            {
                ThreadPool.GetAvailableThreads(out threadCnt, out threadDone);

                if ((threadCnt == 50) && (threadDone == 50))
                { break; }
                Thread.Sleep(100);

            }
            }
            catch (Exception e)
            {
            MessageBox.Show(String.Format("Cannot open {0} or crashed during parsing, please make sure that file is not in use by other program\nRead the rest of the crash report below\n\n\n{1}",
                pcapfile, e.ToString()));
            }
        }
        private static void ComparePacketsToWireshark(IEnumerable<Packet> packets)
        {
            string pcapFilename = Path.GetTempPath() + "temp." + new Random().NextByte() + ".pcap";
#pragma warning disable 162
// ReSharper disable ConditionIsAlwaysTrueOrFalse
// ReSharper disable HeuristicUnreachableCode
            if (!IsRetry)
            {
                PacketDumpFile.Dump(pcapFilename, new PcapDataLink(packets.First().DataLink.Kind), PacketDevice.DefaultSnapshotLength, packets);
            }
            else
            {
                pcapFilename = Path.GetTempPath() + "temp." + RetryNumber + ".pcap";
                List<Packet> packetsList = new List<Packet>();
                using (PacketCommunicator communicator = new OfflinePacketDevice(pcapFilename).Open())
                {
                    communicator.ReceivePackets(-1, packetsList.Add);
                }
                packets = packetsList;
            }
// ReSharper restore HeuristicUnreachableCode
// ReSharper restore ConditionIsAlwaysTrueOrFalse
#pragma warning restore 162

            // Create pdml file
            string documentFilename = pcapFilename + ".pdml";
            using (Process process = new Process())
            {
                process.StartInfo = new ProcessStartInfo
                                    {
                                        // Wireshark's preferences file is %APPDATA%\Wireshark\preferences
                                            FileName = WiresharkTsharkPath,
                                            Arguments = "-o ip.check_checksum:TRUE " + 
                                                        "-o ipv6.use_geoip:FALSE " +
                                                        "-o udp.check_checksum:TRUE " +
                                                        "-o tcp.relative_sequence_numbers:FALSE " +
                                                        "-o tcp.analyze_sequence_numbers:FALSE " +
                                                        "-o tcp.track_bytes_in_flight:FALSE " +
                                                        "-o tcp.desegment_tcp_streams:FALSE " +
                                                        "-o tcp.check_checksum:TRUE " +
                                                        "-o http.dechunk_body:FALSE " +
                                                        "-t r -n -r \"" + pcapFilename + "\" -T pdml",
                                            WorkingDirectory = WiresharkDiretory,
                                            UseShellExecute = false,
                                            RedirectStandardOutput = true,
                                            RedirectStandardError = true,
                                            CreateNoWindow = true
                                        };
                Console.WriteLine("Starting process " + process.StartInfo.FileName + " " + process.StartInfo.Arguments);
                Assert.IsTrue(process.Start());
                string output = process.StandardOutput.ReadToEnd();
                string errorOutput = process.StandardError.ReadToEnd();
                process.WaitForExit();
                Console.WriteLine(errorOutput);
                File.WriteAllText(documentFilename, output);
                Assert.AreEqual(0, process.ExitCode);
            }

            // Fix pdml file
            string fixedDocumentFilename = documentFilename + ".fixed";
            File.WriteAllBytes(fixedDocumentFilename, new List<byte>(from b in File.ReadAllBytes(documentFilename)
                                                                     select b == 0x0A || b == 0x0D
                                                                                ? b
                                                                                : Math.Max((byte)0x20, Math.Min(b, (byte)0x7F))).ToArray());

            try
            {
                Compare(XDocument.Load(fixedDocumentFilename, LoadOptions.None), packets);
            }
            catch (AssertFailedException exception)
            {
                throw new AssertFailedException("Failed comparing packets in file " + pcapFilename + ". Message: " + exception.Message, exception);
            }
        }
Esempio n. 41
0
        static void Main(string[] args)
        {
            // Check the validity of the command line
            if (args.Length == 0 || args.Length > 2)
            {
                Usage();
                return;
            }

            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the list
            for (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedOutputDevice = allDevices[deviceIndex - 1];

            // Retrieve the length of the capture file
            long capLength = new FileInfo(args[0]).Length;

            // Chek if the timestamps must be respected
            bool isSync = (args.Length == 2 && args[1][0] == 's');

            // Open the capture file
            OfflinePacketDevice selectedInputDevice = new OfflinePacketDevice(args[0]);

            using (PacketCommunicator inputCommunicator =
                selectedInputDevice.Open(65536, // portion of the packet to capture
                // 65536 guarantees that the whole packet will be captured on all the link layers
                                         PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                         1000)) // read timeout
            {
                using (PacketCommunicator outputCommunicator =
                    selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    // Check the MAC type
                    if (inputCommunicator.DataLink != outputCommunicator.DataLink)
                    {
                        Console.WriteLine(
                            "Warning: the datalink of the capture differs from the one of the selected interface.");
                        Console.WriteLine("Press a key to continue, or CTRL+C to stop.");
                        Console.ReadKey();
                    }

                    // Allocate a send buffer
                    using (PacketSendBuffer sendBuffer = new PacketSendBuffer((uint)capLength))
                    {
                        // Fill the buffer with the packets from the file
                        int numPackets = 0;
                        Packet packet;
                        while (inputCommunicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok)
                        {
                            sendBuffer.Enqueue(packet);
                            ++numPackets;
                        }

                        // Transmit the queue
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();
                        long startTimeMs = stopwatch.ElapsedMilliseconds;
                        Console.WriteLine("Start Time: " + startTimeMs);
                        outputCommunicator.Transmit(sendBuffer, isSync);
                        long endTimeMs = stopwatch.ElapsedMilliseconds;
                        Console.WriteLine("End Time: " + endTimeMs);
                        long elapsedTimeMs = endTimeMs - startTimeMs;
                        Console.WriteLine("Elapsed Time: " + elapsedTimeMs);
                        double averagePacketsPerSecond = elapsedTimeMs == 0 ? double.MaxValue : (double)numPackets / elapsedTimeMs * 1000;

                        Console.WriteLine("Elapsed time: " + elapsedTimeMs + " ms");
                        Console.WriteLine("Total packets generated = " + numPackets);
                        Console.WriteLine("Average packets per second = " + averagePacketsPerSecond);
                        Console.WriteLine();
                    }
                }
            }
        }
Esempio n. 42
0
        public void LoadData(string pcapfile)
        {
            //try
            //{
            int pktCnt;
            frames = new List<byte[]>();
            LogItems.addStreamInfo(String.Format("Starting to parse {0}", pcapfile));
            using (PacketCommunicator communicator = new OfflinePacketDevice(pcapfile).Open(65536,
                                    PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                    1000))     // read timeout
            {
                //communicator.ReceiveSomePackets(out pktCnt,-1, extractUDP);
                    communicator.ReceivePackets(0,extractUDP);
            }

            //for(int f=0;f!=frames.Count;f++)
            //{
            //    parseFrame(frames[f], f);
            //}
            //frames.Clear();
                //}
            //}
            //catch (Exception e)
            //{
            //    var msg = (String.Format("Cannot open {0} or crashed during parsing, please make sure that file is not in use by other program\nRead the rest of the crash report below\n\n\n{1}",
            //        pcapfile, e.ToString()));
            //    LogItems.addParsingError(msg);
            //}
        }
Esempio n. 43
0
 public void LoadData(string pcapfile)
 {
     Dictionary<int, Dictionary<string, double[]>> streamParameters = Globals.limitPCAP;
     try
     {
     int pktCnt;
     using (PacketCommunicator communicator = new OfflinePacketDevice(pcapfile).Open(65536,
                             PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                             1000))     // read timeout
     {
         communicator.ReceivePackets(0,parsePacket2);
         //communicator.ReceivePackets(0, parsePacketPTP);
         //communicator.ReceiveSomePackets(out pktCnt, -1, parsePacketParrallel);
     }
     //}
     }
     catch (Exception e)
     {
     MessageBox.Show(String.Format("Cannot open {0} or crashed during parsing, please make sure that file is not in use by other program\nRead the rest of the crash report below\n\n\n{1}",
         pcapfile, e.ToString()));
     }
 }
Esempio n. 44
0
		/// <summary>
		/// Retrieve details about a packet
		/// </summary>
		/// <param name="index">Index of the packet to retrieve</param>
		/// <param name="ctrl">UI elements</param>
		public static void RetrievePacketDetails(int index, object[] ctrl)
		{
			// Create the off-line device
			OfflinePacketDevice selectedDevice = new OfflinePacketDevice(detailsFile);

			// Open the capture file
			using (PacketCommunicator communicator =
				selectedDevice.Open(65536,                                  // portion of the packet to capture
				// 65536 guarantees that the whole packet will be captured on all the link layers
									PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
									1000))                                  // read timeout
			{
				Packet packet = null;
				try {
					while (index-- > 0)
						communicator.ReceivePacket(out packet);
				}
				catch (Exception) {
					return;
				}


				PacketParser.ParsePacket(packet, ctrl);
			}
		}
Esempio n. 45
0
 public void ReadNonExistingUnicodeFilenameTest()
 {
     const string ReadUnicodeFilename = "abc_non_existing_\u00F9_\u05D0\u05D1\u05D2.pcap";
     OfflinePacketDevice device = new OfflinePacketDevice(ReadUnicodeFilename);
     using (PacketCommunicator communicator = device.Open())
     {
         Assert.Fail();
     }
 }
Esempio n. 46
0
 public static PacketDevice SelectDevice(string deviceName = null)
 {
     if (deviceName == null)
         deviceName = @"rpcap://\Device\NPF_{BF8A52CB-F023-4F24-AA7E-958A8D1F3069}";
     Trace.WriteLine("select device \"{0}\"", deviceName);
     PacketDevice device = null;
     if (deviceName.StartsWith("rpcap://"))
         device = (from d in LivePacketDevice.AllLocalMachine where d.Name == deviceName select d).FirstOrDefault();
     else
         device = new OfflinePacketDevice(GetPath(deviceName));
     if (device == null)
         Trace.WriteLine("device not found");
     return device;
 }
Esempio n. 47
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                packetCount = 0;
                startTime = 0;

                listView1.Items.Clear();

                Debug.WriteLine("Selected file: " + openFileDialog1.FileName);
                OfflinePacketDevice interpreter = new OfflinePacketDevice(openFileDialog1.FileName);
                using (PacketCommunicator communicator =
                    interpreter.Open(250,
                                    PacketDeviceOpenAttributes.Promiscuous,
                                    1000))
                {
                    communicator.ReceivePackets(0, DispatchHandler);

                }
            }
            else
            {
                Debug.WriteLine("No file");
            }
        }
Esempio n. 48
0
        public static void Test_ReadPacketsFromDumpFile_01()
        {
            // from project ReadingPacketsFromADumpFile
            _tr.WriteLine("Test_ReadPacketsFromDumpFile_01");

            string dumpFile = @"dump\dump.pcap";
            dumpFile = GetPath(dumpFile);
            _tr.WriteLine("read packets from dump file \"{0}\"", dumpFile);

            // Create the offline device
            OfflinePacketDevice device = new OfflinePacketDevice(dumpFile);

            __communicator = null;
            //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution);
            _rs.OnAbortExecution = OnAbortExecution;
            try
            {
                // Open the capture file
                using (__communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    // Read and dispatch packets until EOF is reached
                    __communicator.ReceivePackets(0, ReadPacketsFromDumpFile);
                }
            }
            finally
            {
                //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution);
            }
        }
Esempio n. 49
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pcapPath"></param>
        /// <param name="outputPath"></param>
        /// <param name="maxSize"></param>
        public void Parse(string pcapPath, 
                          string outputPath,
                          long maxSize)
        {
            this.cancelSource = new CancellationTokenSource();
            Task task = Task.Factory.StartNew(() =>
            {
                this.IsRunning = true;
                this.IsStopping = false;
                this.sessionParser.Start();

                try
                {
                    _outputPath = outputPath;
                    _maxSize = maxSize;

                    // Check for previous DB
                    if (File.Exists(System.IO.Path.Combine(_outputPath, Global.DB_FILE)) == true)
                    {
                        OnMessage("Deleting database...");

                        string retDel = IO.DeleteFiles(_outputPath);
                        if (retDel.Length > 0)
                        {
                            OnError("An error occurred whilst deleting the existing files: " + retDel);
                            return;
                        }
                    }

                    woanware.IO.WriteTextToFile("Start: " + DateTime.Now.ToString() + Environment.NewLine, System.IO.Path.Combine(_outputPath, "Log.txt"), true);

                    OnMessage("Creating database...");

                    string ret = Db.CreateDatabase(_outputPath);
                    if (ret.Length > 0)
                    {
                        OnError("Unable to create database: " + ret);
                        return;
                    }

                    OnMessage("Database created...");

                    _packetCount = 0;
                    _dictionary = new Dictionary<Connection, PacketReconstructor>();

                    OfflinePacketDevice selectedDevice = new OfflinePacketDevice(pcapPath);
                    using (PacketCommunicator packetCommunicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                    {
                        packetCommunicator.ReceivePackets(0, DispatcherHandler);
                    }

                    // Write any remaining sessions
                    WriteOldSessions(null);

                    _dictionary.Clear();
                    _dictionary = null;

                    sessionParser.SetProcessed();

                    OnMessage("All sessions added to queue, now waiting for session parsing to complete...");

                    this.done = new AutoResetEvent(false);
                    this.done.WaitOne();

                    woanware.IO.WriteTextToFile("End: " + DateTime.Now.ToString() + Environment.NewLine, System.IO.Path.Combine(_outputPath, "Log.txt"), true);
                    woanware.IO.WriteTextToFile("Packets: " + _packetCount + Environment.NewLine, System.IO.Path.Combine(_outputPath, "Log.txt"), true);
                    woanware.IO.WriteTextToFile("TCP Sessions: " + this.sessionParser.TotalSessions + Environment.NewLine, System.IO.Path.Combine(_outputPath, "Log.txt"), true);

                    OnComplete();
                }
                catch (Exception ex)
                {
                    OnError("An error occurred whilst parsing: " + ex.Message);
                }
                finally
                {
                    IsRunning = false;
                }
            }, cancelSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }
Esempio n. 50
0
        private void AnalyzeGRE(string filename, bool printSubstreams = false)
        {
            int streamcount = 0;
            if (filename !="")
            {
                txtFileName.Text = filename;
                greHash.Clear();
                greStreamHash.Clear();

                richTextBox1.Clear();
                packetCount = 0;
                mplsPackets = 0;
                totalMPLSBytes = 0;
                richTextBox1.AppendText("Open file " +filename + "\n");
                startTime = 0;
                lastPaketTime = 0;
                elapsedTime = 0;
                totalIPBytes = 0;
                totalGREBytes = 0;
                totalMPLSBytes = 0;

                OfflinePacketDevice interpreter = new OfflinePacketDevice(filename);
                using (PacketCommunicator communicator = interpreter.Open(250,
                                    PacketDeviceOpenAttributes.Promiscuous,
                                    1000))
                {
                    communicator.ReceivePackets(0, DispatchHandler);

                }
            }
            else
            {
                richTextBox1.AppendText("No file");
                return;
            }

            float totalTime = ((lastPaketTime - startTime) / 10000000.0f);

            float ipbitrate = totalIPBytes * 8.0f / totalTime / 1000000.0f;
            float grebitrate = totalGREBytes * 8.0f / totalTime / 1000000.0f;
            float mplsbitrate = totalMPLSBytes * 8 / totalTime / 1000000.0f;
            richTextBox1.AppendText("\n\n---------------------\n\n\n");

            int substreamCount = 0;
            foreach (string key in greHash.Keys)
            {
                string[] ips = key.Split(',');
                richTextBox1.AppendText("GRE," + ips[0] + ", " + ips[1] + "," + ((Int64)greHash[key] * 8.0f / totalTime / 1000000.0f).ToString() + "," + ((Hashtable)greStreamHash[key]).Keys.Count.ToString() + "\n");

                    Hashtable streamHash = (Hashtable)greStreamHash[key];
                    streamcount += streamHash.Keys.Count;
                    foreach (string skey in streamHash.Keys)
                    {
                        substreamCount++;
                        Int64 tbytes = (Int64)streamHash[skey];
                        float sbitrate = tbytes * 8.0f / totalTime / 1000000.0f;
                        string[] newips = skey.Split(',');
                        if (printSubstreams)
                        {
                            richTextBox1.AppendText("\t " + newips[0] + ", " + newips[1] + ", " + sbitrate.ToString() + "\n");
                        }
                    }

            }

            float averageStreamCount = 1.0f * streamcount / greHash.Keys.Count ;

            richTextBox1.AppendText("---------------------\n\n\n");
            richTextBox1.AppendText("Capture: " + filename + "\n");
            richTextBox1.AppendText("Total packet count: " + packetCount.ToString() + "\n");
            richTextBox1.AppendText("Total MPLS Packet count: " + mplsPackets.ToString() + "\n\n");

            richTextBox1.AppendText("Unique GRE discovered : " + greHash.Keys.Count.ToString() + "\n");
            richTextBox1.AppendText("Total GRE substreams discovered:  " + substreamCount.ToString() + "\n");
            richTextBox1.AppendText("Average number of streams per GRE: " + averageStreamCount.ToString() + "\n\n");

            richTextBox1.AppendText("Total GRE Bytes : " + totalGREBytes.ToString() + "\n");
            richTextBox1.AppendText("Total MPLS Bytes is " + totalMPLSBytes.ToString() + "\n");
            richTextBox1.AppendText("IP Only Bytes : " + totalIPBytes.ToString() + "\n");
            richTextBox1.AppendText("Total Bytes from all protocols : " + totalBytes.ToString() + "\n\n");

            richTextBox1.AppendText("GRE Bitrate is " + (grebitrate).ToString() + " Mbits/sec \n");
            richTextBox1.AppendText("Average GRE Tunnel Bitrate = " + (grebitrate / greHash.Keys.Count).ToString() + "\n");
            richTextBox1.AppendText("Average GRE Substream bitrate = " + (grebitrate / substreamCount).ToString() + " Mbps\n");

            richTextBox1.AppendText("MPLS Bitrate is " + (mplsbitrate).ToString() + " MBits/Sec\n");
            richTextBox1.AppendText("Non GRE IP Bitrate is " + (ipbitrate).ToString() + " Mbits/sec\n");
            richTextBox1.AppendText("Length of capture in seconds: " + totalTime.ToString() + "\n");
        }
Esempio n. 51
0
        private void simplePacketReaderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string fname;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                fname = openFileDialog1.SafeFileName;
                greHash.Clear();
                greStreamHash.Clear();

                richTextBox1.Clear();
                packetCount = 0;
                mplsPackets = 0;
                totalMPLSBytes = 0;
                richTextBox1.AppendText("Open file " + openFileDialog1.FileName + "\n");
                startTime = 0;
                lastPaketTime = 0;
                elapsedTime = 0;
                totalIPBytes = 0;
                totalGREBytes = 0;
                totalMPLSBytes = 0;

                OfflinePacketDevice interpreter = new OfflinePacketDevice(openFileDialog1.FileName);
                using (PacketCommunicator communicator = interpreter.Open(250,
                                    PacketDeviceOpenAttributes.Promiscuous,
                                    1000))
                {
                    communicator.ReceivePackets(0, DispatchHandler);

                }
            }
            else
            {
                richTextBox1.AppendText("No file");
                return;
            }

            float totalTime = ((lastPaketTime - startTime) / 10000000.0f);

            float ipbitrate = totalIPBytes * 8.0f / totalTime / 1000000.0f;
            float grebitrate = totalGREBytes * 8.0f / totalTime / 1000000.0f;
            float mplsbitrate = totalMPLSBytes * 8 / totalTime / 1000000.0f;
            richTextBox1.AppendText("\n\n---------------------\n\n\n");

            int substreamCount = 0;
            foreach (string key in greHash.Keys)
            {
                string[] ips = key.Split(',');
                richTextBox1.AppendText("GRE," + ips[0] + ", " + ips[1] + "," + ((Int64)greHash[key] * 8.0f / totalTime / 1000000.0f).ToString() + "," + ((Hashtable)greStreamHash[key]).Keys.Count.ToString() + "\n");

                Hashtable streamHash = (Hashtable)greStreamHash[key];

                foreach (string skey in streamHash.Keys)
                {
                    substreamCount++;
                    Int64 tbytes = (Int64)streamHash[skey];
                    float sbitrate = tbytes * 8.0f / totalTime / 1000000.0f;
                    string[] newips = skey.Split(',');
                    richTextBox1.AppendText("\t " + newips[0]  + ", " + newips[1] + ", " + sbitrate.ToString() + "\n");
                }
            }

            richTextBox1.AppendText("---------------------\n\n\n");
            richTextBox1.AppendText("Capture: " + fname + "\n");
            richTextBox1.AppendText("Total packet count is " + packetCount.ToString() + "\n");
            richTextBox1.AppendText("Total MPLS Packet countis " + mplsPackets.ToString() + "\n");
            richTextBox1.AppendText("Total MPLS Bytes is " + totalMPLSBytes.ToString() + "\n");

            richTextBox1.AppendText("Unique GRE Streams: " + greHash.Keys.Count.ToString());
            richTextBox1.AppendText("Total GRE substreams " + substreamCount.ToString() + "\n");

            richTextBox1.AppendText("Average GRE Tunnel Bitrate = " + (grebitrate / greHash.Keys.Count).ToString() + "\n");
            richTextBox1.AppendText("GRE Bitrate is " + (grebitrate).ToString() + " Mbits/sec \n");
            richTextBox1.AppendText("Average GRE Substream bitrate = " + (grebitrate / substreamCount).ToString() + "\n");

            richTextBox1.AppendText("MPLS Bitrate is " + (mplsbitrate).ToString() + " MBits/Sec\n");
            richTextBox1.AppendText("Non GRE IP Bitrate is " + (ipbitrate).ToString() + " Mbits/sec\n");
            richTextBox1.AppendText("Elapsed is " + totalTime.ToString() + "\n");
        }
Esempio n. 52
0
        public bool ParseCaptureFile(string fileNameAndPath, string fileName, bool includeParsedFileLog)
        {
            bool result = false;

            // Create an offline device for the capture file
            OfflinePacketDevice opd = new OfflinePacketDevice(fileNameAndPath);

            // Create a container to hold the captured packets
            BindingList<Packet> packets = new BindingList<Packet>();

            // Open the capture file (snapshot length, attributes, read timeout)
            using (PacketCommunicator com = opd.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                // Retrieve the packets
                Packet packet;
                string pktResult = string.Empty;

                do
                {
                    PacketCommunicatorReceiveResult rec = com.ReceivePacket(out packet);
                    pktResult = rec.ToString();
                    switch(rec)
                    {
                        case PacketCommunicatorReceiveResult.Timeout:
                            // Timeout elapsed
                            continue;
                        case PacketCommunicatorReceiveResult.Ok:
                            packets.Add(packet);
                            break;
                        case PacketCommunicatorReceiveResult.Eof:
                            break;
                        default:
                            throw new InvalidOperationException("Unknown error occurred while reading packet: " + result);
                    }

                } while (pktResult != "Eof");
            }
            if(packets.Count > 0)
            {
                // We successfully parsed the capture file
                // Note: in future version we may need to compare the number of rows in the file with the number of parsed packets obtained
                result = true;
            }

            // Write packets out to a file
            if (result && includeParsedFileLog)
            {
                int pktno = 0;
                using (StreamWriter sw = new StreamWriter(ParsedFilesDir + "\\ParsePacketTest_" + DateTime.Now.Ticks.ToString() + ".txt"))
                {
                    foreach (Packet pkt in packets)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.AppendFormat("{0}|{1}|{2}", fileName, pktno++, Convert.ToDateTime(pkt.Timestamp).TimeOfDay);
                        sw.WriteLine(sb.ToString());
                    }
                }
            }

            // Check if packets are marked (i.e., flooder was running during packet capture 'd', or unmarked, 'u')
            int marked = fileName.Substring(fileName.Length - 6, 1) == "u" ? 0 : 1;
            int captureBatchId = -1;

            // Write a CaptureBatch record to the database for this file
            if(result)
            {
                try
                {
                    DataImport di = new DataImport(DbConnectionString);
                    captureBatchId = di.CreateCaptureBatch(fileName, marked == 1? true : false);

                    result = captureBatchId > 0 ? true : false;
                }
                catch (Exception ex)
                {
                    throw new Exception("Error creating CaptureBatch record in database for file [" + fileName + "]: " + ex.Message);
                }
            }

            // Write packets to a DataTable and import them into the database
            if (result)
            {
                DataSet packetDs = new DataSet();
                DataTable packetTable = new DataTable();
                PacketDataSet.PacketDataSet pds = new PacketDataSet.PacketDataSet();

                try
                {
                    int pktno = 0;
                    packetTable = pds.CreatePacketDataTable();
                    {
                        foreach (Packet pkt in packets)
                        {
                            DataRow dr = packetTable.NewRow();
                            dr["CaptureBatchId"] = captureBatchId;
                            dr["PacketNumber"] = pktno++;
                            dr["TimeStamp"] = Convert.ToDateTime(pkt.Timestamp).TimeOfDay.ToString();
                            dr["Marked"] = marked;
                            packetTable.Rows.Add(dr);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Error adding packet data row to DataTable: " + ex.Message);
                }

                try
                {
                    // Import into the database
                    COWE.DataLayer.DataImport di = new DataImport(DbConnectionString);
                    bool success = di.LoadPacketData(packetTable);
                }
                catch (Exception ex)
                {
                    throw new Exception("Error importing packet data into database: " + ex.Message);
                }
            }

            return result;
        }
Esempio n. 53
0
        //[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void LoadDataDownSampled(string pcapfile)
        {
            Dictionary<int, Dictionary<string, double[]>> streamParameters = Globals.limitPCAP;
            try
            {
            int pktCnt=0;
            frames = new List<byte[]>();
            using (PacketCommunicator communicator = new OfflinePacketDevice(pcapfile).Open(65536,                                  // portion of the packet to capture
                // 65536 guarantees that the whole packet will be captured on all the link layers
                                    PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                    1000))     // read timeout
            {
                //communicator.ReceiveSomePackets(out pktCnt, 10, parsePacketParrallel);
                communicator.ReceivePackets(0, parsePacketDownSampled);
                //communicator.ReceivePackets(0, parsePacketPTP);
            }

            }
            catch (Exception e)
            {
            MessageBox.Show(String.Format("Cannot open {0} or crashed during parsing, please make sure that file is not in use by other program\nRead the rest of the crash report below\n\n\n{1}",
                pcapfile, e.ToString()));
            }
        }