Exemple #1
0
        public void SetSamplingMethodOneEveryNTest()
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
                communicator.SetSamplingMethod(new SamplingMethodOneEveryCount(5));
                for (int i = 0; i != 20; ++i)
                {
                    Packet expectedPacket = _random.NextEthernetPacket(60 * (i + 1), SourceMac, DestinationMac);
                    communicator.SendPacket(expectedPacket);
                }

                Packet packet;
                PacketCommunicatorReceiveResult result;
                for (int i = 0; i != 4; ++i)
                {
                    result = communicator.ReceivePacket(out packet);
                    Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                    Assert.AreEqual(60 * 5 * (i + 1), packet.Length);
                }
                result = communicator.ReceivePacket(out packet);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Timeout, result);
                Assert.IsNull(packet);
            }
        }
Exemple #2
0
        public void OpenOfflineMultipleTimes()
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";
            const int    NumPackets     = 10;
            Packet       expectedPacket = _random.NextEthernetPacket(100, SourceMac, DestinationMac);
            PacketDevice device         = GetOfflineDevice(NumPackets, expectedPacket);

            // TODO: Fix so we can go beyond 509.
            //       See http://www.winpcap.org/pipermail/winpcap-bugs/2012-December/001547.html
            for (int j = 0; j != 100; ++j)
            {
                using (PacketCommunicator communicator = device.Open())
                {
                    PacketCommunicatorReceiveResult result;
                    Packet actualPacket;
                    for (int i = 0; i != NumPackets; ++i)
                    {
                        result = communicator.ReceivePacket(out actualPacket);
                        Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                        Assert.AreEqual(expectedPacket, actualPacket);
                        MoreAssert.IsInRange(expectedPacket.Timestamp.AddSeconds(-0.05), expectedPacket.Timestamp.AddSeconds(0.05),
                                             actualPacket.Timestamp);
                    }

                    result = communicator.ReceivePacket(out actualPacket);
                    Assert.AreEqual(PacketCommunicatorReceiveResult.Eof, result);
                    Assert.IsNull(actualPacket);
                }
            }
        }
Exemple #3
0
        public void SetSamplingMethodFirstAfterIntervalTest()
        {
            const int NumPackets = 10;

            Packet expectedPacket = _random.NextEthernetPacket(100);

            using (PacketCommunicator communicator = OpenOfflineDevice(NumPackets, expectedPacket, TimeSpan.FromSeconds(1)))
            {
                communicator.SetSamplingMethod(new SamplingMethodFirstAfterInterval(TimeSpan.FromSeconds(2)));

                PacketCommunicatorReceiveResult result;
                Packet packet;
                for (int i = 0; i != 5; ++i)
                {
                    result = communicator.ReceivePacket(out packet);
                    Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                    Assert.AreEqual(expectedPacket, packet);
                    DateTime expectedTimestamp = expectedPacket.Timestamp.AddSeconds(i * 2);
                    MoreAssert.IsInRange(expectedTimestamp.AddSeconds(-0.01), expectedTimestamp.AddSeconds(0.01), packet.Timestamp);
                }
                result = communicator.ReceivePacket(out packet);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Eof, result);
                Assert.IsNull(packet);
            }
        }
Exemple #4
0
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        private static void TestOpenMultipleTimes(int numTimes, string filename)
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";
            const int    NumPackets     = 10;
            Packet       expectedPacket = _random.NextEthernetPacket(100, SourceMac, DestinationMac);
            PacketDevice device         = GetOfflineDevice(NumPackets, expectedPacket, TimeSpan.Zero, Path.GetTempPath() + @"dump.pcap", Path.GetTempPath() + filename);

            for (int j = 0; j != numTimes; ++j)
            {
                using (PacketCommunicator communicator = device.Open())
                {
                    PacketCommunicatorReceiveResult result;
                    Packet actualPacket;
                    for (int i = 0; i != NumPackets; ++i)
                    {
                        result = communicator.ReceivePacket(out actualPacket);
                        Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                        Assert.AreEqual(expectedPacket, actualPacket);
                        MoreAssert.IsInRange(expectedPacket.Timestamp.AddSeconds(-0.05), expectedPacket.Timestamp.AddSeconds(0.05),
                                             actualPacket.Timestamp);
                    }

                    result = communicator.ReceivePacket(out actualPacket);
                    Assert.AreEqual(PacketCommunicatorReceiveResult.Eof, result);
                    Assert.IsNull(actualPacket);
                }
            }
        }
Exemple #5
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);
                }
            }
        }
Exemple #6
0
        public void GetPacketTest()
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";
            const int    NumPackets     = 10;

            Packet expectedPacket = _random.NextEthernetPacket(100, SourceMac, DestinationMac);

            using (PacketCommunicator communicator = OpenOfflineDevice(NumPackets, expectedPacket))
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                PacketCommunicatorReceiveResult result;
                Packet actualPacket;
                for (int i = 0; i != NumPackets; ++i)
                {
                    result = communicator.ReceivePacket(out actualPacket);
                    Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                    Assert.AreEqual(expectedPacket, actualPacket);
                    MoreAssert.IsInRange(expectedPacket.Timestamp.AddSeconds(-0.05), expectedPacket.Timestamp.AddSeconds(0.05),
                                         actualPacket.Timestamp);
                }

                result = communicator.ReceivePacket(out actualPacket);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Eof, result);
                Assert.IsNull(actualPacket);
            }
        }
        public void ResolveDestinationMacFor(ScanningOptions options, CancellationToken ct)
        {
            using (PacketCommunicator communicator = options.Device.Open(65535, PacketDeviceOpenAttributes.None, 100))
            {
                Packet request = ArpPacketFactory.CreateRequestFor(options);
                communicator.SetFilter("arp and src " + options.TargetIP + " and dst " + options.SourceIP);
                communicator.SendPacket(request);

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        return;
                    }

                    Packet responce;
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out responce);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        communicator.SendPacket(request);
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        options.TargetMac = ParseSenderMacFrom(responce);
                        return;
                    }
                }
            }
        }
Exemple #8
0
        public void Handler()
        {
            var          devices        = GetDevices();
            PacketDevice selectedDevice = devices[4];


            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,
                                           PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                           1000))                                  // read timeout
            {
                communicator.SetFilter("tcp port 443");

                Console.WriteLine("Listening on " + selectedDevice.Description + "...");

                Packet packet;
                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" +
                                          packet.Length);
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                    }
                } while (true);
            }
        }
        public static void CapturePacket(IList <LivePacketDevice> allDevices)
        {
            PacketDevice selectedDevice = SelectDevice(allDevices);

            // Open the device
            using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                Console.WriteLine("Listening on " + selectedDevice.Description + "...");

                // Retrieve the packets
                Packet packet;
                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" +
                                          packet.Length);
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                    }
                } while (true);
            }
        }
Exemple #10
0
        /// <summary>
        /// Loop to receive packets (blocking).
        /// </summary>
        private void ReceivePackets()
        {
            Packet packet;

            while (Running)
            {
                var result = Communicator.ReceivePacket(out packet);
                switch (result)
                {
                case PacketCommunicatorReceiveResult.Timeout:
                    continue;

                case PacketCommunicatorReceiveResult.Ok:     //Only handle a packet if it was successfully received
                    HandlePacket(packet);
                    break;

                default:
                    break;
                }

                //If we have received both necesarry packets, construct URL and stop listening
                if (!(ReplayServerAddr.Equals("") || DemoName.Equals("")))
                {
                    URL = string.Format("http://{0}{1}", ReplayServerAddr, DemoName);
                    Stop();
                }
            }
        }
Exemple #11
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);
            }
        }
Exemple #12
0
        public void StartCapturing()
        {
            using (PacketCommunicator communicator = CurrentDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                Packet packet;
                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        PacketBuffer.Enqueue(packet);
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                    }

                    if (PacketBuffer.Count == 1000)
                    {
                        if (queueIsFull != null)
                        {
                            queueIsFull();
                        }
                    }
                } while (true);
            }
        }
Exemple #13
0
        public void Receive(Action <Packet> callback)
        {
            // Open the device
            using (PacketCommunicator communicator =
                       _packetDevice.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
            {
                Console.WriteLine("Listening on " + _packetDevice.Description + "...");

                // Retrieve the packets
                Packet packet;
                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        callback(packet);
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                    }
                } while (true);
            }
        }
Exemple #14
0
        async void ReceiveResposnes()
        {
            await Task.Run(() =>
            {
                Packet pck;

                do
                {
                    if (!receiveTask)
                    {
                        return;
                    }


                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out pck);



                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        {
                            if (pck.DataLink.Kind != DataLinkKind.Ethernet)
                            {
                                continue;
                            }
                            EthernetDatagram ed = pck.Ethernet;

                            if (ed.EtherType != EthernetType.Arp)
                            {
                                continue;
                            }
                            ArpDatagram arppck = ed.Arp;

                            if (arppck.Operation != ArpOperation.Reply)
                            {
                                continue;
                            }


                            NetworkHost host = new NetworkHost {
                                IP = arppck.SenderProtocolIpV4Address.ToString(), MAC = ed.Source.ToString()
                            };
                            OnCaptureHost?.Invoke(host);



                            continue;
                        }

                    default:
                        throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                    }
                } while (true);
            });
        }
Exemple #15
0
 public void GetPacketOnStatisticsModeErrorTest()
 {
     using (PacketCommunicator communicator = OpenLiveDevice())
     {
         communicator.Mode = PacketCommunicatorMode.Statistics;
         Packet packet;
         communicator.ReceivePacket(out packet);
     }
 }
        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();
        }
Exemple #17
0
        private void buttonAgKesfi_Click(object sender, EventArgs e) // Ağda bulunan ciahzların mac adresleri bu fonksiyon yardımıyla arp paketleri gönderilerek elde edilir.
        {
            byte altdeger = Convert.ToByte(textBox2.Text);           //Ağ keşfi için kullanılacak sınır ipler belirlendi.
            byte ustdeger = Convert.ToByte(textBox3.Text);           //Ağ keşfi için kullanılacak sınır ipler belirlendi.
            IList <LivePacketDevice> allDevices     = LivePacketDevice.AllLocalMachine;
            PacketDevice             selectedDevice = allDevices[2]; //Cihaz seçimi. Manuel olarak atanmıştır.

            using (PacketCommunicator communicator = selectedDevice.Open(100,
                                                                         PacketDeviceOpenAttributes.Promiscuous,
                                                                         1000))
            {
                //****************************** Ağ keşfi ******************************
                for (byte i = altdeger; i < ustdeger; i++) // Ağdaki istenilen ip aralığına arp paketleri gönderiir. Örn: "192.168.1.i"
                {
                    EthernetLayer ethernetLayer =
                        new EthernetLayer                                  //Ethernet Katmanı
                    {
                        Source      = new MacAddress(MacAdresim()),        //Kaynak mac adresi. Fonksiyondan çekildi.
                        Destination = new MacAddress("ff:ff:ff:ff:ff:ff"), //Hedef mac adresi. Broadcast yayın yapıldı.
                        EtherType   = EthernetType.None,
                    };

                    ArpLayer arpLayer =
                        new ArpLayer //Arp Katmanı
                    {
                        ProtocolType          = EthernetType.IpV4,
                        Operation             = ArpOperation.Request,
                        SenderHardwareAddress = new byte[] { 0x28, 0xd2, 0x44, 0x49, 0x7e, 0x2b }.AsReadOnly(),                                                                                          // Kaynak ac adresi.
                             SenderProtocolAddress = new byte[] { Convert.ToByte(IpParcala(0)), Convert.ToByte(IpParcala(1)), Convert.ToByte(IpParcala(2)), Convert.ToByte(IpParcala(3)) }.AsReadOnly(), // Kaynak Ip adresi IpParcala fonksiyonundan bloklar halinde çekildi.
                             TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),                                                                                                       // Hedef Mac Adresi. Öğrenilmek istenen parametre. Request paketlerinde 00:00:00:00:00:00
                             TargetProtocolAddress = new byte[] { Convert.ToByte(IpParcala(0)), Convert.ToByte(IpParcala(1)), Convert.ToByte(IpParcala(2)), i }.AsReadOnly(),                            // Hedef Ip adresi IpParcala fonksiyonundan bulunulan ağın ilk 3 bloğu alındı. Son blok i değeri ile döngüye sokuldu.
                    };

                    PacketBuilder builder   = new PacketBuilder(ethernetLayer, arpLayer);
                    Packet        arppacket = builder.Build(DateTime.Now); // Katmanlar paketlendi.
                    communicator.SendPacket(arppacket);                    // Arp paketi yayınlandı.


                    //****************************** ARP Paket dinleme ******************************
                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("arp")) // Filtre uygulandı.
                    {
                        communicator.SetFilter(filter);
                    }
                    Packet packet;
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Ok:
                        if (!listBox1.Items.Contains(packet.Ethernet.Source + "\t\t\t@" + packet.Ethernet.Arp.SenderProtocolIpV4Address.ToString())) // Listbox'da oluşabilecek veri tekrarı önlendi.
                        {
                            listBox1.Items.Add(packet.Ethernet.Source + "\t\t\t@" + packet.Ethernet.Arp.SenderProtocolIpV4Address.ToString());       // Gelen Arp Paketlerinin Ethernet Katmanındna Source MAC Addres verisi çekildi.
                        }
                        break;
                    }
                }
            }
        }
Exemple #18
0
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            IPDict = new Dictionary <IpV4Address, int>();

            using (PacketCommunicator communicator = selectedDevice.Open(1024, PacketDeviceOpenAttributes.Promiscuous, 200))
            {
                Packet packet;

                using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and udp"))
                {
                    communicator.SetFilter(filter);
                }
                for (int i = 0; i < 10; i++)
                {
                    if (packetCaptureWorker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        IpV4Datagram ip = packet.Ethernet.IpV4;
                        if (ip.Source.ToString() == localIP.ToString())
                        {
                            if (IPDict.ContainsKey(ip.Destination))
                            {
                                IPDict[ip.Destination]++;
                            }
                            else
                            {
                                IPDict.Add(ip.Destination, 1);
                            }
                        }
                        else if (ip.Destination.ToString() == localIP.ToString())
                        {
                            if (IPDict.ContainsKey(ip.Source))
                            {
                                IPDict[ip.Source]++;
                            }
                            else
                            {
                                IPDict.Add(ip.Source, 1);
                            }
                        }
                        break;

                    default:
                        throw new InvalidOperationException();
                    }
                }
            }
        }
        public void SendAndReceievePacketTest()
        {
            const string SourceMac        = "11:22:33:44:55:66";
            const string DestinationMac   = "77:88:99:AA:BB:CC";
            const int    NumPacketsToSend = 10;

            using (PacketCommunicator communicator = OpenLiveDevice(100))
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);

                Packet   packet;
                DateTime startWaiting = DateTime.Now;
                PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                DateTime finishedWaiting = DateTime.Now;

                Assert.AreEqual(PacketCommunicatorReceiveResult.Timeout, result);
                Assert.AreEqual <uint>(0, communicator.TotalStatistics.PacketsCaptured);
                MoreAssert.IsInRange(TimeSpan.FromSeconds(0.99), TimeSpan.FromSeconds(1.075), finishedWaiting - startWaiting);

                Packet sentPacket = _random.NextEthernetPacket(200, 300, SourceMac, DestinationMac);

                DateTime startSendingTime = DateTime.Now;

                for (int i = 0; i != NumPacketsToSend; ++i)
                {
                    communicator.SendPacket(sentPacket);
                }

                DateTime endSendingTime = DateTime.Now;

                for (int i = 0; i != NumPacketsToSend; ++i)
                {
                    result = communicator.ReceivePacket(out packet);

                    Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                    Assert.AreEqual(100, packet.Length);
                    Assert.AreEqual <uint>(200, packet.OriginalLength);
                    MoreAssert.IsInRange(startSendingTime - TimeSpan.FromSeconds(1), endSendingTime + TimeSpan.FromSeconds(30), packet.Timestamp);
                }
                Assert.AreEqual <uint>(NumPacketsToSend, communicator.TotalStatistics.PacketsCaptured);
            }
        }
Exemple #20
0
        public void SetSamplingMethodOneEveryNTest()
        {
            Packet expectedPacket = _random.NextEthernetPacket(100);

            using (PacketCommunicator communicator = OpenOfflineDevice(101, expectedPacket))
            {
                communicator.SetSamplingMethod(new SamplingMethodOneEveryCount(10));
                PacketCommunicatorReceiveResult result;
                Packet packet;
                for (int i = 0; i != 10; ++i)
                {
                    result = communicator.ReceivePacket(out packet);
                    Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                    Assert.AreEqual(expectedPacket, packet);
                }
                result = communicator.ReceivePacket(out packet);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Eof, result);
                Assert.IsNull(packet);
            }
        }
Exemple #21
0
        private void StartCapturing()
        {
            using (PacketCommunicator communicator = CurrentDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                Packet packet;
                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);

                    if (Filter != null)
                    {
                        communicator.SetFilter(Filter);
                    }

                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        PacketBuffer.Enqueue((new CustomPacket(packet)).ToString());
                        //PacketBuffer.Enqueue(SuspiciousPacketGenerator.GenerateSample(36, "0", rand, false));

                        int randomNumber = rand.Next(10);

                        if (randomNumber % 5 == 0)
                        {
                            PacketBuffer.Enqueue(SuspiciousPacketGenerator.GenerateSample(36, "0", rand, false));
                        }
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " should never be reached here");
                    }

                    lock (PacketBuffer)
                    {
                        if (PacketBuffer.Count >= PACKETS_COUNT_CONSTRAINT && !Pause)
                        {
                            string[] data = GetLastPackets();

                            if (queueIsFull != null)
                            {
                                queueIsFull(data);
                            }
                        }
                    }
                } while (true);
            }
        }
Exemple #22
0
        public static void Test_CapturingThePacketsWithoutTheCallback_01()
        {
            // from project CapturingThePacketsWithoutTheCallback
            _tr.WriteLine("Test_CapturingThePacketsWithoutTheCallback_01");
            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 + "...");

                    // Retrieve the packets
                    Packet packet;
                    do
                    {
                        PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                        switch (result)
                        {
                        case PacketCommunicatorReceiveResult.Timeout:
                            // Timeout elapsed
                            continue;

                        case PacketCommunicatorReceiveResult.Ok:
                            _tr.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);
                            break;

                        default:
                            throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                        }
                        if (_rs.IsExecutionAborted())
                        {
                            break;
                        }
                    } while (true);
                }
            }
            catch (Exception ex)
            {
                _tr.WriteLine(ex.Message);
            }
        }
        private static void TestFilter(PacketCommunicator communicator, BerkeleyPacketFilter filter, Packet expectedPacket, Packet unexpectedPacket)
        {
            communicator.SetFilter(filter);
            for (int i = 0; i != 5; ++i)
            {
                communicator.SendPacket(expectedPacket);
                communicator.SendPacket(unexpectedPacket);
            }

            Packet packet;
            PacketCommunicatorReceiveResult result;

            for (int i = 0; i != 5; ++i)
            {
                result = communicator.ReceivePacket(out packet);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                Assert.AreEqual(expectedPacket, packet);
            }

            result = communicator.ReceivePacket(out packet);
            Assert.AreEqual(PacketCommunicatorReceiveResult.Timeout, result);
            Assert.IsNull(packet);
        }
Exemple #24
0
        public void SetSmallKernelBufferSizeGetPacketErrorTest()
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
                communicator.SetKernelBufferSize(10);
                Packet packet = _random.NextEthernetPacket(100, SourceMac, DestinationMac);
                communicator.SendPacket(packet);
                communicator.ReceivePacket(out packet);
            }
            Assert.Fail();
        }
Exemple #25
0
        // rewrite of the former method, implemented using ReceivePacket()
        // use this method in a timer, filter based on timer (active or not)
        private void FilterPortPacket(PacketCommunicator pm, string prot = "UDP")
        {
            Packet packet;
            PacketCommunicatorReceiveResult result = pm.ReceivePacket(out packet);

            switch (result)
            {
            case PacketCommunicatorReceiveResult.Ok:
                Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);
                break;

            default:
                throw new InvalidOperationException("The result " + result + " should never be reached here");
            }
        }
Exemple #26
0
        private void OpenDevice(PacketDevice selectedDevice)
        {
            // Open the device
            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,
                                           PacketDeviceOpenAttributes.MaximumResponsiveness,
                                           1000))
            {
                if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                {
                    MessageHelper.PrintMessage("This program works only on Ethernet networks.");
                    return;
                }

                // Compile the filter
                using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and udp"))
                {
                    // Set the filter
                    communicator.SetFilter(filter);
                }

                MessageHelper.PrintMessage("Listening on " + selectedDevice.Description + "...");

                // start the capture
                MessageHelper.PrintMessage("Monitoring started. Press any key to stop and save the results into a text file", "warning");

                Packet packet;
                do
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        PacketHandler(packet);
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " should never be reached here");
                    }
                } while (!Console.KeyAvailable);

                repo.SaveMonitoringResultsToTextFile(FileLocation);
            }
        }
Exemple #27
0
        public void SetSamplingMethodFirstAfterIntervalTest()
        {
            Random random = new Random();

            MacAddress sourceMac      = random.NextMacAddress();
            MacAddress destinationMac = random.NextMacAddress();

            using (PacketCommunicator communicator = OpenLiveDevice())
            {
                communicator.SetFilter("ether src " + sourceMac + " and ether dst " + destinationMac);
                communicator.SetSamplingMethod(new SamplingMethodFirstAfterInterval(TimeSpan.FromSeconds(1)));
                int numPacketsGot;
                communicator.ReceiveSomePackets(out numPacketsGot, 100, p => { });

                Packet[] packetsToSend = new Packet[11];
                packetsToSend[0] = _random.NextEthernetPacket(60, sourceMac, destinationMac);
                for (int i = 0; i != 10; ++i)
                {
                    packetsToSend[i + 1] = _random.NextEthernetPacket(60 * (i + 2), sourceMac, destinationMac);
                }

                List <Packet> packets = new List <Packet>(6);
                Thread        thread  = new Thread(() => packets.AddRange(communicator.ReceivePackets(6)));
                thread.Start();

                communicator.SendPacket(packetsToSend[0]);
                Thread.Sleep(TimeSpan.FromSeconds(0.7));
                for (int i = 0; i != 10; ++i)
                {
                    communicator.SendPacket(packetsToSend[i + 1]);
                    Thread.Sleep(TimeSpan.FromSeconds(0.55));
                }

                if (!thread.Join(TimeSpan.FromSeconds(10)))
                {
                    thread.Abort();
                }
                Assert.AreEqual(6, packets.Count, packets.Select(p => (p.Timestamp - packets[0].Timestamp).TotalSeconds + "(" + p.Length + ")").SequenceToString(", "));
                Packet packet;
                for (int i = 0; i != 6; ++i)
                {
                    Assert.AreEqual(60 * (i * 2 + 1), packets[i].Length, i.ToString());
                }
                PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Timeout, result);
                Assert.IsNull(packet);
            }
        }
Exemple #28
0
        // Main method for scanning packets.
        private void scan()
        {
            using (PacketCommunicator communicator = device.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 0))
            {
                Packet       packet;
                long         startTimeMillis = (long)(DateTime.Now - DateTime.MinValue).TotalMilliseconds;
                long         endTimeMillis = startTimeMillis + duration;
                long         second = startTimeMillis;
                long         byteTotal = 0, miniTotal = 0;
                Queue <long> totals = new Queue <long>();

                timer = new Timer(endTimeMillis, main);

                // Sniffs packets until the specified duration has passed.
                while ((DateTime.Now - DateTime.MinValue).TotalMilliseconds < endTimeMillis)
                {
                    communicator.ReceivePacket(out packet);
                    if (packet != null)
                    {
                        byteTotal += packet.Length;
                        miniTotal += packet.Length;

                        // Updates the gui every 0.5 seconds or when the total within a 0.5s period is >= 18000.
                        if ((long)(DateTime.Now - DateTime.MinValue).TotalMilliseconds - second >= 500 || miniTotal > 18000)
                        {
                            totals.Enqueue(miniTotal);
                            main.byteTotal.BeginInvoke((MethodInvoker) delegate
                            {
                                main.upadateBytes(byteTotal);
                                main.addPoint((int)totals.Dequeue());
                            });
                            second    = (long)(DateTime.Now - DateTime.MinValue).TotalMilliseconds;
                            miniTotal = 0;
                        }
                    }
                }

                timer.stop();

                main.byteTotal.BeginInvoke((MethodInvoker) delegate
                {
                    main.upadateBytes(byteTotal);
                });
            }
        }
        private void WaitForResponse(PacketCommunicator communicator)
        {
            communicator.SetFilter("tcp and src " + DestinationIpV4 + " and dst " + SourceIpV4 + " and src port " + _destinationPort + " and dst port " + _sourcePort);
            Packet packet;

            while (true)
            {
                if (communicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok)
                {
                    Console.WriteLine("Expected ack number: " + _expectedAckNumber);
                    Console.WriteLine("Received ack number: " + packet.Ethernet.IpV4.Tcp.AcknowledgmentNumber);
                    if (packet.Ethernet.IpV4.Tcp.AcknowledgmentNumber == _expectedAckNumber)
                    {
                        break;
                    }
                }
                SendGet(communicator);
            }
        }
Exemple #30
0
        public void ReadWriteIso88591FilenameTest()
        {
            const string DumpFilename   = "abc_\u00F9\u00E8.pcap";
            const int    NumPackets     = 10;
            Packet       expectedPacket = PacketBuilder.Build(DateTime.Now, new EthernetLayer {
                EtherType = EthernetType.IpV4
            });

            using (PacketCommunicator communicator = OpenOfflineDevice(NumPackets, expectedPacket, TimeSpan.FromSeconds(0.1), DumpFilename))
            {
                for (int i = 0; i != NumPackets; ++i)
                {
                    Packet actualPacket;
                    Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, communicator.ReceivePacket(out actualPacket));
                    Assert.AreEqual(expectedPacket, actualPacket);
                }
            }

            Assert.IsTrue(File.Exists(DumpFilename), string.Format("File {0} doesn't exist", DumpFilename));
        }
        private static void TestFilter(PacketCommunicator communicator, BerkeleyPacketFilter filter, Packet expectedPacket, Packet unexpectedPacket)
        {
            communicator.SetFilter(filter);
            for (int i = 0; i != 5; ++i)
            {
                communicator.SendPacket(expectedPacket);
                communicator.SendPacket(unexpectedPacket);
            }

            Packet packet;
            PacketCommunicatorReceiveResult result;
            for (int i = 0; i != 5; ++i)
            {
                result = communicator.ReceivePacket(out packet);
                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                Assert.AreEqual(expectedPacket, packet);
            }

            result = communicator.ReceivePacket(out packet);
            Assert.AreEqual(PacketCommunicatorReceiveResult.Timeout, result);
            Assert.IsNull(packet);
        }