コード例 #1
0
        private static void Compare(XDocument document, IEnumerable <Packet> packets)
        {
            IEnumerator <Packet> packetEnumerator = packets.GetEnumerator();

            List <Packet> failedPackets  = new List <Packet>();
            StringBuilder failureMessage = new StringBuilder();

            // Parse XML
            int i = 1;

            foreach (var documentPacket in document.Element("pdml").Elements("packet"))
            {
                packetEnumerator.MoveNext();
                Packet packet = packetEnumerator.Current;

                try
                {
                    ComparePacket(packet, documentPacket);
                }
                catch (Exception e)
                {
                    failedPackets.Add(packet);
                    failureMessage.Append(new AssertFailedException("Failed comparing packet " + i + ". " + e.Message, e) + Environment.NewLine);
                }
                ++i;
            }

            if (failedPackets.Any())
            {
                PacketDumpFile.Dump(Path.GetTempPath() + "temp." + 1000 + ".pcap", failedPackets.First().DataLink.Kind, 65536, failedPackets);
                throw new AssertFailedException("Failed comparing " + failedPackets.Count + " packets:" + Environment.NewLine + failureMessage);
            }
        }
コード例 #2
0
        /// <summary>
        /// Setup filter and start capture
        /// Return when an error occurs or StopCapture is called
        /// </summary>
        /// <param name="callback">Callback to handle packets</param>
        /// <param name="ErrorMsg">When return contains the error description</param>
        public void StartCapture(HandlePacket callback, out string ErrorMsg)
        {
            // Check the link layer. We support only Ethernet
            if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
            {
                ErrorMsg = "This program works only on Ethernet networks.";
                return;
            }

            // Compile the filter
            using (BerkeleyPacketFilter filter =
                       communicator.CreateFilter(SnifferConfig.Filter.FilterString)) {
                communicator.SetFilter(filter);
            }

            using (PacketDumpFile dumpFile = communicator.OpenDump(DumpFileName))
            {
                try {
                    // start the capture
                    communicator.ReceivePackets(0,
                                                delegate(Packet packet)
                    {
                        dumpFile.Dump(packet);
                        callback(packet);
                    });
                }
                catch (Exception ex) {
                    ErrorMsg = ex.Message;
                }
            }

            ErrorMsg = null;
        }
コード例 #3
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);
            }
        }
コード例 #4
0
        public void StartCapture()
        {
            var dev = LivePacketDevice.AllLocalMachine.FirstOrDefault(d => d.Name.Equals(Device.Name));

            if (dev == null)
            {
                return;
            }

            var token = Cancellation.Token;

            this.CaptureTask = new Task((state) =>
            {
                DumpOptions option = (DumpOptions)state;

                // Open device
                using (PacketCommunicator communicator = dev.Open(
                           65535, PacketDeviceOpenAttributes.Promiscuous,
                           250
                           ))
                {
                    if (option.Filter != null)
                    {
                        communicator.SetFilter(option.Filter);
                    }

                    using (PacketDumpFile dumpFile = communicator.OpenDump(option.Path))
                    {
                        int count           = 0;
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();

                        while (count < option.Count &&
                               stopwatch.ElapsedMilliseconds < option.Durance.TotalMilliseconds)
                        {
                            token.ThrowIfCancellationRequested();

                            Packet packet;
                            var result = communicator.ReceivePacket(out packet);

                            if (result == PacketCommunicatorReceiveResult.Ok)
                            {
                                dumpFile.Dump(packet);
                                count++;

                                if (option.Callback != null)
                                {
                                    option.Callback(null, new PacketArrivalEventArgs(packet));
                                }
                            }
                        }
                    }
                }
            }, Options, token, TaskCreationOptions.LongRunning);

            CaptureTask.Start();
        }
コード例 #5
0
 public static void DumpDetailsPacket(Packet packet)
 {
     if (detailsDumper == null)
     {
         detailsFile   = Path.GetTempFileName();
         detailsDumper = communicator.OpenDump(detailsFile);
     }
     detailsDumper.Dump(packet);
 }
コード例 #6
0
 private void ReceivePacketHandle(Packet packet)
 {
     if (_packetDumpFile != null)
     {
         _packetDumpFile.Dump(packet);
     }
     if (OnPacketReceived != null)
     {
         OnPacketReceived(packet);
     }
     if (OnPPacketReceived != null)
     {
         OnPPacketReceived(_ppacketManager.CreatePPacket(packet));
     }
 }
コード例 #7
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);
        }
コード例 #8
0
        /// <summary>
        /// Saves one packet to disk on default path
        /// </summary>
        /// <param name="packet"></param>
        public void TrySaveOnePacketToDisk(Packet packet, string fileName = "savedpacket")
        {
            if (packet is null)
            {
                throw new ArgumentNullException(nameof(packet));
            }

            string path = PathProvider.GetDefaultPathToSolution();

            fileName = ConstructFileNameUntilThereIsNoFileWithSameName(fileName, path, ".pcap");

            PacketDumpFile.Dump(path + fileName,
                                packet.DataLink.Kind,
                                packet.Length,
                                new List <Packet> {
                packet
            });
        }
コード例 #9
0
        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 (Exception exception)
            {
                throw new AssertFailedException("Failed comparing packets in file " + pcapFilename + ". " + exception, exception);
            }
        }
コード例 #10
0
 public void SendNullPacketsTest()
 {
     PacketDumpFile.Dump(@"dump.pcap", new PcapDataLink(DataLinkKind.Ethernet), PacketDevice.DefaultSnapshotLength, null);
     Assert.Fail();
 }
コード例 #11
0
ファイル: Test_Winpcap_dn_f.cs プロジェクト: 24/source_04
        public static void Test_DumpPacketsToFile_01()
        {
            // from project CaptureInvalidPackets
            _tr.WriteLine("Test_DumpPacketsToFile_01");

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

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

            PacketDevice device = SelectDevice();

            if (device == null)
            {
                return;
            }
            try
            {
                // Open the device : device.Open()
                //   snapshotLength = 65536, portion of the packet to capture 65536 guarantees that the whole packet will be captured on all the link layers
                //   attributes = PacketDeviceOpenAttributes.Promiscuous, promiscuous mode
                //   readTimeout = 1000
                using (PacketCommunicator communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    _tr.WriteLine("Listening on " + device.Description + "...");

                    if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                    {
                        _tr.WriteLine("This program works only on Ethernet networks.");
                        return;
                    }

                    // start the capture
                    var query = from packet in communicator.ReceivePackets() select packet; // where !packet.IsValid

                    using (PacketDumpFile dump = communicator.OpenDump(dumpFile))
                    {
                        foreach (Packet packet in query)
                        {
                            if (packet.Length <= 60 &&
                                packet.Ethernet.EtherType == EthernetType.IpV4 &&
                                packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp &&
                                packet.Ethernet.IpV4.Tcp.ControlBits == (TcpControlBits.Synchronize | TcpControlBits.Acknowledgment))
                            {
                                _tr.WriteLine("Captured Packet " + packet.Timestamp);
                            }

                            _tr.WriteLine("dump packet " + packet.Timestamp);
                            dump.Dump(packet);
                            if (_rs.IsExecutionAborted())
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _tr.WriteLine(ex.Message);
            }
        }
コード例 #12
0
        public void WritePcapFile()
        {
            string filename = $"websock__{_srcIp}_{_srcPort}__{_dstIp}_{_dstPort}__" + _packets[0].Timestamp.ToString("hh-mm-ss-fff") + ".pcap";

            PacketDumpFile.Dump(filename, DataLinkKind.Ethernet, 65536, _packets);
        }