Пример #1
1
 private void _Receive(int count = 0)
 {
     //using (_communicator = _device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
     //{
     //    _ppacketManager = new PPacketManager();
     //    if (_filter != null)
     //        _communicator.SetFilter(_filter);
     //    _communicator.ReceivePackets(0, ReceivePacketHandle);
     //}
     try
     {
         _communicator = _device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000);
         if (_dumpFile != null)
             _packetDumpFile = _communicator.OpenDump(_dumpFile);
         _ppacketManager = new PPacketManager();
         if (_filter != null)
             _communicator.SetFilter(_filter);
         _communicator.ReceivePackets(count, ReceivePacketHandle);
     }
     finally
     {
         if (_communicator != null)
         {
             _communicator.Dispose();
             _communicator = null;
         }
         if (_packetDumpFile != null)
         {
             _packetDumpFile.Dispose();
             _packetDumpFile = null;
         }
     }
 }
Пример #2
1
            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the TAP interface
                PacketDevice selectedDevice = null;
                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.Contains(Guid))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Byte Counter", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Byte Counter: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Byte Counter: Listening on " + Name + "...");
                        communicator.SetFilter("((ether dst " + ifHardwareAddressString + " or ether src " + ifHardwareAddressString + ") and ip and (tcp or udp))");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!threadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            Table.CheckPacket(packet, ifHardwareAddress);
                        });
                    }
                }
                catch (Exception e)
                {
                    if (threadActive.IsSet)
                    {
                        threadActive.Reset();
                        Global.WriteLog("Byte Counter: Could not capture traffic from " + Name);
                        if (Global.Config.Gadget.Debug)
                            Global.WriteLog(e.ToString());
                        Global.ShowTrayTip("Byte Counter", "Could not capture traffic from " + Name, System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
Пример #3
1
            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the TAP interface
                PacketDevice selectedDevice = null;
                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.ToUpper().Contains(Guid.ToString().ToUpper()))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Load Balancer", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Load Balancer: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Load Balancer: Listening on " + Name + "...");
                        communicator.SetFilter("(ether dst " + ownHardwareAddressString + " and ((ip and (tcp or udp or icmp)) or arp)) or (ether dst FF:FF:FF:FF:FF:FF and arp)");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!ThreadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            if (packet.Ethernet.EtherType == EthernetType.Arp)
                            {
                                if (packet.Ethernet.Arp.TargetProtocolAddress.SequenceEqual(ownProtocolAddressByte) && packet.Ethernet.Arp.Operation == ArpOperation.Request)
                                {
                                    EthernetLayer ethernetLayer = new EthernetLayer
                                    {
                                        Source = ownHardwareAddress,
                                        Destination = packet.Ethernet.Source,
                                        EtherType = EthernetType.None,
                                    };

                                    ArpLayer arpLayer = new ArpLayer
                                    {
                                        ProtocolType = EthernetType.IpV4,
                                        Operation = ArpOperation.Reply,
                                        SenderHardwareAddress = ownHardwareAddressByte.AsReadOnly(),
                                        SenderProtocolAddress = packet.Ethernet.Arp.TargetProtocolAddress,
                                        TargetHardwareAddress = packet.Ethernet.Arp.SenderHardwareAddress,
                                        TargetProtocolAddress = packet.Ethernet.Arp.SenderProtocolAddress,
                                    };

                                    PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
                                    SendPacket(builder.Build(DateTime.Now));
                                }
                            }
                            else if (packet.Ethernet.EtherType.ToString() == "IpV4")
                            {

                                if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.DoNotFragment ||
                                    packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset == 0)
                                {
                                    IpV4Handler(packet);
                                }
                                else if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.MoreFragments ||
                                    packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset > 0)
                                {
                                    // TODO: fix warning spam
                                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                                        Global.ShowTrayTip("Load Balancer", "IP fragmentation detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                                    Global.WriteLog("Load Balancer: IP fragmentation detected on " + Name);
                                    //fragments = fragBuffer.Add(packet);
                                    //if (fragments != null)
                                    //    for (int i = 0; i < fragments.Count; i++)
                                    //    {
                                    //        IpV4Handler(fragments[i], fragments);
                                    //    }
                                }
                            }
                        });
                    }
                }
                catch (Exception e)
                {
                    if (ThreadActive.IsSet)
                    {
                        ThreadActive.Reset();
                        Global.WriteLog("Load Balancer: " + Name + " has disconnected");
                        if (Global.Config.Gadget.Debug)
                            Global.WriteLog(e.ToString());
                        Global.ShowTrayTip("Load Balancer", Name + " has disconnected", System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
Пример #4
0
        private static void preparePcap()
        {
            var source = new MacAddress(getClientMAC());
            var dest   = new MacAddress(getRouterMAC());

            device       = LivePacketDevice.AllLocalMachine[0];
            communicator = device.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000);

            EthernetLayer ethLayer = new EthernetLayer {
                Source = source, Destination = dest
            };

            ipLayer = new IpV4Layer {
                Source = new IpV4Address(LocalIPAddress()), Ttl = 128
            };
            icmpLayer   = new IcmpEchoLayer();
            icmpBuilder = new PacketBuilder(ethLayer, ipLayer, icmpLayer);

            TCPLayer   = new TcpLayer();
            TCPBuilder = new PacketBuilder(ethLayer, ipLayer, TCPLayer);

            if (!TCPMode)
            {
                communicator.SetFilter("icmp[0] = 0");
            }
            else
            {
                //tcp[13] = 18
                communicator.SetFilter("tcp[13] = 18 and port " + TCPPort);
            }
        }
Пример #5
0
        public void Start()
        {
            // Start scanning WoW packets
            // Retrieve the device list from the local machine
            IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Logger.Warn("No interfaces found! Can't scan WoW packets.");
                return;
            }

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices.First();

            // Open the device
            _communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 40);
            Logger.Debug("Listening on " + selectedDevice.Description + " for WoW packets");

            // Compile the filter
            using (var filter = _communicator.CreateFilter("tcp"))
            {
                // Set the filter
                _communicator.SetFilter(filter);
            }

            Task.Run(() => ReceivePackets());
        }
        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;
                    }
                }
            }
        }
Пример #7
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);
            }
        }
Пример #8
0
        private static void TestGetSomePackets(int numPacketsToSend, int numPacketsToGet, int numPacketsToBreakLoop,
                                               PacketCommunicatorReceiveResult expectedResult, int expectedNumPackets,
                                               double expectedMinSeconds, double expectedMaxSeconds)
        {
            string testDescription = "NumPacketsToSend=" + numPacketsToSend + ". NumPacketsToGet=" + numPacketsToGet +
                                     ". NumPacketsToBreakLoop=" + numPacketsToBreakLoop;

            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

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

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

                if (numPacketsToBreakLoop == 0)
                {
                    communicator.Break();
                }
                PacketHandler handler = new PacketHandler(expectedPacket, expectedMinSeconds, expectedMaxSeconds, communicator, numPacketsToBreakLoop);

                int numPacketsGot;
                PacketCommunicatorReceiveResult result = communicator.ReceiveSomePackets(out numPacketsGot, numPacketsToGet, handler.Handle);
                Assert.AreEqual(expectedResult, result);
                Assert.AreEqual(expectedNumPackets, numPacketsGot, "NumPacketsGot. Test: " + testDescription);
                Assert.AreEqual(expectedNumPackets, handler.NumPacketsHandled, "NumPacketsHandled. Test: " + testDescription);
            }
        }
        public void StartHijack()
        {
            Task.Run(delegate {
                IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                if (allDevices.Count == 0)
                {
                    MessageBox.Show("未找到网卡。请确认已安装WinPcap。");
                    return;
                }

                foreach (var selectedDevice in allDevices)
                {
                    Task.Run(delegate
                    {
                        PacketCommunicator communicator =
                            selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000);
                        if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                        {
                            return;
                        }

                        using (BerkeleyPacketFilter filter = communicator.CreateFilter("tcp and dst port 80"))
                        {
                            communicator.SetFilter(filter);
                        }
                        communicator.ReceivePackets(0, PacketHandler);
                    });
                }

                this.BeginInvoke(new EventHandler(delegate {
                    lbMsg.Text = "监听已启动";
                }));
            });
        }
Пример #10
0
        /// <summary>
        /// Captures packets via the selected device
        /// </summary>
        void ReadPackets(PacketDevice selectedDevice)
        {
            // Open the device
            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
            {
                // Check the link layer. We support only Ethernet for simplicity.
                if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                {
                    throw new FormatException("This program works only on Ethernet networks.");
                }

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

                // start the capture
                try
                {
                    communicator.ReceivePackets(0, PacketHandler);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Communicator: " + ex.Message);
                    return;
                }
            }
        }
 public void BadFilterErrorTest()
 {
     using (PacketCommunicator communicator = LivePacketDeviceTests.OpenLiveDevice())
     {
         communicator.SetFilter("illegal filter string");
     }
 }
Пример #12
0
        private void CapturePacket()
        {
            int deviceIndex = 0;

            try
            {
                deviceIndex = Int32.Parse(comboBoxInterfaces.SelectedValue.ToString());
            }
            catch
            {
            }


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

            // Open the device
            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
            {
                labelDescription.Text = "Listening on " + InterFaces.Rows[deviceIndex - 1]["Description"] + "...";
                using (BerkeleyPacketFilter filter = communicator.CreateFilter("icmp"))
                {
                    // Set the filter
                    communicator.SetFilter(filter);
                }
                // start the capture
                communicator.ReceivePackets(0, DevicePingHandler);
            }
        }
Пример #13
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);
            }
        }
Пример #14
0
        public static string GetRouterMacAddress(string thisMachineLocalIp, string routerLocalIp, PacketDevice captureDevice, int maxTries)
        {
            using (PacketCommunicator Communicator =
                       captureDevice.Open(65536,
                                          PacketDeviceOpenAttributes.None,
                                          1000))
                using (PacketCommunicator inputCommunicator =
                           captureDevice.Open(65536,
                                              PacketDeviceOpenAttributes.None,
                                              1000))
                {
                    inputCommunicator.SetFilter($"ether proto \\arp and dst host \\{thisMachineLocalIp}");

                    Communicator.SendPacket(BuildArpPacket(thisMachineLocalIp, routerLocalIp));

                    for (int trie = 0; trie < maxTries; ++trie)
                    {
                        inputCommunicator.ReceivePacket(out var receivedPacket);

                        if (receivedPacket == null)
                        {
                            continue;
                        }

                        var arpDataGram = receivedPacket.Ethernet.Arp;

                        if (arpDataGram.Operation.HasFlag(ArpOperation.Reply))
                        {
                            return(string.Join(":", (from z in arpDataGram.SenderHardwareAddress select z.ToString("X2")).ToArray()));
                        }
                    }

                    return(null);
                }
        }
        public void Run()
        {
            if (selectedDevice != null)
            {
                using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    // Check the link layer. We support only Ethernet for simplicity.
                    if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                    {
                        CLI.PrintQueueLog(Channel.Zero, "이더넷 프로토콜에서만 작동합니다..", ConsoleColor.White);
                        return;
                    }
                    // Compile the filter
                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and tcp and (port 80 or portrange 8000-9000)"))
                    {
                        // Set the filter
                        communicator.SetFilter(filter);
                    }

                    CLI.PrintQueueLog(Channel.Zero, "패킷 읽기 시작!", ConsoleColor.Yellow);
                    CLI.ShowToast("PCAP", "통발 블랙박스", "패킷 파싱을 시작합니다.", "");

                    // start the capture
                    communicator.ReceivePackets(0, PacketHandler);
                }
            }
            else
            {
                CLI.PrintQueueLog(Channel.Zero, "장치가 선택되지 않았습니다.", ConsoleColor.White);
            }
        }
Пример #16
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;
        }
Пример #17
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;
                }
            }
        }
Пример #18
0
        public void ReceiveSomePacketsGcCollectTest()
        {
            const string SourceMac      = "11:22:33:44:55:66";
            const string DestinationMac = "77:88:99:AA:BB:CC";

            const int NumPackets = 2;

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

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

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

                int numGot;
                PacketCommunicatorReceiveResult result = communicator.ReceiveSomePackets(out numGot, NumPackets,
                                                                                         delegate
                {
                    GC.Collect();
                });
                Assert.AreEqual(PacketCommunicatorReceiveResult.Ok, result);
                Assert.AreEqual(NumPackets, numGot);
            }
        }
Пример #19
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);
            }
        }
Пример #20
0
        private void PaketYakala(String filtre = "ip")
        {
            for (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
            }

            selectedDevice = allDevices[deviceIndex - 1];
            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
            {
                // Check the link layer. We support only Ethernet for simplicity.
                if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                {
                    Console.WriteLine("This program works only on Ethernet networks.");
                    return;
                }

                // Compile the filter
                using (BerkeleyPacketFilter filter = communicator.CreateFilter(filtre))
                {
                    // Set the filter
                    communicator.SetFilter(filter);
                }

                label2.Text = selectedDevice.Description;

                // start the capture
                communicator.ReceivePackets(0, PacketHandler);
            }
        }
Пример #21
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);*/
        }
Пример #22
0
        private void CreateListener()
        {
            IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Debug.WriteLine("No Network Interface Found! Please make sure WinPcap is properly installed.");
                return;
            }
            for (int i = 0; i != allDevices.Count; i++)
            {
                LivePacketDevice device = allDevices[i];
                if (device.Description != null)
                {
                    Debug.WriteLine(" (" + device.Description + ")");
                }
                else
                {
                    Debug.WriteLine(" (Unknown)");
                }
            }
            using (List <LivePacketDevice> .Enumerator enumerator = allDevices.ToList <LivePacketDevice>().GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    PacketDevice selectedDevice = enumerator.Current;
                    if (selectedDevice.Attributes == DeviceAttributes.Loopback)
                    {
                        continue;
                    }
                    new Thread(delegate()
                    {
                        try
                        {
                            using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                            {
                                if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                                {
                                    Debug.WriteLine("This program works only on Ethernet networks.");
                                }
                                else
                                {
                                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and udp"))
                                    {
                                        communicator.SetFilter(filter);
                                    }
                                    Console.WriteLine("Capturing on " + selectedDevice.Description + "...");
                                    communicator.ReceivePackets(0, new HandlePacket(photonPacketHandler.PacketHandler));
                                }
                            }
                        }
                        catch (NotSupportedException ex)
                        {
                            Console.WriteLine($"Error listening on {selectedDevice.Description} because of {ex.Message}. Skipping this device. If it still works you can ignore this");
                        }
                    }).Start();
                }
            }
        }
Пример #23
0
        static void Main(string[] args)
        {
            // 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];

            // Open the output adapter
            using (
                PacketCommunicator communicator = selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous,
                                                                            1000))
            {
                // Compile and set the filter
                communicator.SetFilter("tcp");

                // Put the interface in statstics mode
                communicator.Mode = PacketCommunicatorMode.Statistics;

                Console.WriteLine("TCP traffic summary:");

                // Start the main loop
                communicator.ReceiveStatistics(0, StatisticsHandler);
            }
        }
Пример #24
0
 public void SetNullFilterTest()
 {
     using (PacketCommunicator communicator = OpenLiveDevice())
     {
         communicator.SetFilter(null as BerkeleyPacketFilter);
     }
     Assert.Fail();
 }
Пример #25
0
 public void listen()
 {
     using (PacketCommunicator communicator = this.device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
     {
         communicator.SetFilter(this.filter);
         communicator.ReceivePackets(0, NAEHandler.PacketHandler);
     }
 }
Пример #26
0
            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the TAP interface
                PacketDevice selectedDevice = null;

                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.Contains(Guid))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Byte Counter", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Byte Counter: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Byte Counter: Listening on " + Name + "...");
                        communicator.SetFilter("((ether dst " + ifHardwareAddressString + " or ether src " + ifHardwareAddressString + ") and ip and (tcp or udp))");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!threadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            Table.CheckPacket(packet, ifHardwareAddress);
                        });
                    }
                }
                catch (Exception e)
                {
                    if (threadActive.IsSet)
                    {
                        threadActive.Reset();
                        Global.WriteLog("Byte Counter: Could not capture traffic from " + Name);
                        if (Global.Config.Gadget.Debug)
                        {
                            Global.WriteLog(e.ToString());
                        }
                        Global.ShowTrayTip("Byte Counter", "Could not capture traffic from " + Name, System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
Пример #27
0
        private void createListener()
        {
            IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                MessageBox.Show("No interfaces found! Make sure WinPcap is installed.");
                return;
            }
            // Print the list
            for (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];

                if (device.Description != null)
                {
                    Console.WriteLine(" (" + device.Description + ")");
                }
                else
                {
                    Console.WriteLine(" (No description available)");
                }
            }

            foreach (PacketDevice selectedDevice in allDevices.ToList())
            {
                // Open the device
                Thread t = new Thread(() =>
                {
                    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
                    {
                        // Check the link layer. We support only Ethernet for simplicity.
                        if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                        {
                            Console.WriteLine("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);
                        }

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

                        // start the capture
                        communicator.ReceivePackets(0, photonPacketHandler.PacketHandler);
                    }
                });
                t.Start();
            }
        }
Пример #28
0
        static void Main(string[] args)
        {
            // Lista urządzeń
            IList <LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

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

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

            int deviceIndex = 0;

            //wprowadzanie numeru urzadzenia
            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);

            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Ustawiamy komunikator do przechwytywania z urządzenia
            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
            {
                // Filter
                Console.WriteLine("If you want, you can specify filter now");
                using (BerkeleyPacketFilter filter = communicator.CreateFilter(Console.ReadLine()))
                {
                    communicator.SetFilter(filter);
                }

                Console.WriteLine("Listening on " + selectedDevice.Description + "...");
                // przechwytywanie
                communicator.ReceivePackets(0, PacketHandler);
            }
        }
Пример #29
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();
                    }
                }
            }
        }
Пример #30
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();
        }
Пример #31
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;
                    }
                }
            }
        }
Пример #32
0
        //Captures packets while issuing concurrent calls to update the GUI
        /// <summary>
        /// Capture packets and stores their information
        /// </summary>
        private void CapturePackets()
        {
            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[this.deviceIndex];
            int          prevInd        = 0;

            // Open the device
            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(filter);
                while (captFlag)
                {
                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out Packet packet);
                    byte[] packetInfo;

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

                    case PacketCommunicatorReceiveResult.Ok:
                        IpV4Datagram ipv4 = packet.Ethernet.IpV4;
                        IpV4Protocol i    = ipv4.Protocol;

                        CougarPacket cp = new CougarPacket(packet.Timestamp.ToString("hh:mm:ss.fff"),
                                                           ++packetNumber,
                                                           packet.Length,
                                                           ipv4.Source.ToString(),
                                                           ipv4.Destination.ToString());

                        packetInfo = Encoding.ASCII.GetBytes(cp.ToString() + "\n");
                        packetBytes.Add(packetInfo);

                        this.Invoke((MethodInvoker)(() =>
                        {
                            packetView.Items.Add(new ListViewItem(cp.toPropertyArray()));

                            ++prevInd;
                            if (chkAutoScroll.Checked && prevInd > 12)
                            {
                                packetView.Items[packetView.Items.Count - 1].EnsureVisible();
                                prevInd = 0;
                            }
                        }));
                        break;

                    default:
                        throw new InvalidOperationException("The result " + result + " should never be reached here");
                    }
                }
            }
        }
Пример #33
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            using (PacketCommunicator communicator = selectedAdapter.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
            {
                // Check the link layer.
                if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                {
                    MessageBox.Show("This program works only on Ethernet networks!");

                    return;
                }


                //Deallocation is  necessary
                if (_tcp.Checked && (!_udp.Checked))//just tcp
                {
                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("tcp"))
                    {
                        // Set the filter
                        communicator.SetFilter(filter);
                    }
                }

                else if (_udp.Checked && !(_tcp.Checked))//just udp
                {
                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("udp"))
                    {
                        // Set the filter
                        communicator.SetFilter(filter);
                    }
                }

                else if (_tcp.Checked && (_udp.Checked))//tcp and udp
                {
                    using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and udp"))
                    {
                        // Set the filter
                        communicator.SetFilter(filter);
                    }
                }
                // Begin the capture
                communicator.ReceivePackets(0, PacketHandler);
            }
        }
Пример #34
0
        public static void Test_NetworkStatistics_01()
        {
            // from project GatheringStatisticsOnTheNetworkTraffic
            _tr.WriteLine("Test_NetworkStatistics_01");

            PacketDevice device = SelectDevice();
            if (device == null)
                return;
            __communicator = null;
            //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution);
            _rs.OnAbortExecution = OnAbortExecution;
            try
            {
                // Open the device : device.Open()
                //   snapshotLength = 100 ???
                //   attributes = PacketDeviceOpenAttributes.Promiscuous, promiscuous mode
                //   readTimeout = 1000
                using (__communicator = device.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    _tr.WriteLine("Listening on " + device.Description + "...");

                    // Compile and set the filter
                    __communicator.SetFilter("tcp");

                    // Put the interface in statstics mode
                    __communicator.Mode = PacketCommunicatorMode.Statistics;

                    _tr.WriteLine("TCP traffic summary:");

                    // Start the main loop
                    __communicator.ReceiveStatistics(0, StatisticsHandler);
                }
            }
            catch (Exception ex)
            {
                _tr.WriteLine(ex.Message);
            }
            finally
            {
                //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution);
            }
        }
Пример #35
0
        private static void preparePcap()
        {
            var source = new MacAddress(getClientMAC());
            var dest = new MacAddress(getRouterMAC());

            device = LivePacketDevice.AllLocalMachine[0];
            communicator = device.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000);

            EthernetLayer ethLayer = new EthernetLayer { Source = source, Destination = dest };
            ipLayer = new IpV4Layer { Source = new IpV4Address(LocalIPAddress()), Ttl = 128 };
            icmpLayer = new IcmpEchoLayer();
            icmpBuilder = new PacketBuilder(ethLayer, ipLayer, icmpLayer);

            TCPLayer = new TcpLayer();
            TCPBuilder = new PacketBuilder(ethLayer, ipLayer, TCPLayer);

            if (!TCPMode)
            {
                communicator.SetFilter("icmp[0] = 0");
            }
            else
            {
                //tcp[13] = 18
                communicator.SetFilter("tcp[13] = 18 and port " + TCPPort);
            }
        }
Пример #36
0
		void tsbStart_Click(object sender, EventArgs e) {
			stop = false;

			tsbStart.Enabled = tscbNet.Enabled = false;
			tsbPause.Enabled = tsbStop.Enabled = true;

			this.Text = "Ostara - Logging";

			if (paused) {
				paused = false;
				return;
			}

			if (Settings.I.ClearOnStart)
				flvPackets.ClearObjects();

			packets = new Queue<PacketClass>();
			clientCrypt = new Dictionary<ushort, Cryption.Client>();
			serverCrypt = new Dictionary<ushort, Cryption.Server>();

			int ni = tscbNet.SelectedIndex;

			device = LivePacketDevice.AllLocalMachine[ni];
			comm = device.Open(65536, PacketDeviceOpenAttributes.None, 500);
			comm.SetFilter(Ports.I.Filter);

			foreach (var a in device.Addresses) {
				if (a.Address.Family == SocketAddressFamily.Internet) {
					address = ((IpV4SocketAddress)a.Address).Address.ToValue();
					break;
				}
			}

			Task.Run(() => { GetPackets(); });
		}
Пример #37
0
        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);
        }
Пример #38
0
            //public Packet CreateDhcpPacket(int optionsSize, byte[] options, bool firstPacket, byte[] clientIp = null)
            //{
            //    EthernetLayer ethernetLayer = new EthernetLayer
            //    {
            //        Source = ifHardwareAddress,
            //        Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //        EtherType = EthernetType.None,
            //    };

            //    IpV4Layer ipV4Layer = new IpV4Layer
            //    {
            //        Source = new IpV4Address("0.0.0.0"),
            //        CurrentDestination = new IpV4Address("255.255.255.255"),
            //        Fragmentation = IpV4Fragmentation.None,
            //        HeaderChecksum = null, // Will be filled automatically.
            //        Identification = ipID,
            //        Options = IpV4Options.None,
            //        Protocol = null,
            //        Ttl = 128,
            //        TypeOfService = 0,
            //    };

            //    UdpLayer udpLayer = new UdpLayer
            //    {
            //        SourcePort = 68,
            //        DestinationPort = 67,
            //        Checksum = null, // Will be filled automatically.
            //        CalculateChecksumValue = true,
            //    };

            //    Dhcp dhcpLayer = new Dhcp(optionsSize);
            //    if (firstPacket)
            //        dhcpId = dhcpLayer.Id;
            //    else
            //        dhcpLayer.Id = dhcpId;
            //    if (clientIp != null)
            //        dhcpLayer.ClientIp = clientIp;
            //    dhcpLayer.ClientHardwareAddress = ifHardwareAddressByte;
            //    dhcpLayer.Options = options;


            //    PayloadLayer payloadLayer = new PayloadLayer
            //    {
            //        Data = new Datagram(dhcpLayer.toByteArray()),
            //    };

            //    PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);
            //    return builder.Build(DateTime.Now);
            //}
            //public void SendArp()
            //{
            //    EthernetLayer ethernetLayer = new EthernetLayer
            //    {
            //        Source = ifHardwareAddress,
            //        Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //        EtherType = EthernetType.None,
            //    };

            //    ArpLayer arpLayer = new ArpLayer
            //    {
            //        ProtocolType = EthernetType.IpV4,
            //        Operation = ArpOperation.Request,
            //        SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
            //        SenderProtocolAddress = ownProtocolAddressByte.AsReadOnly(),
            //        TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),
            //        TargetProtocolAddress = gatewayProtocolAddressByte.AsReadOnly(),
            //    };

            //    PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
            //    SendPacket(builder.Build(DateTime.Now));
            //}
            //public void ReceiveIpAddress()
            //{
            //    int retries = 0;
            //    int timewait = 0;
            //    dhcpState = 0;
            //    arpState = 0;

            //    byte[] options;
            //    while (true)
            //    {
            //        if (dhcpState == 1 && retries > 1 ||
            //            dhcpState == 3 && retries > 1)
            //        {
            //            dhcpState = 6;
            //            offeredIp = BitConverter.GetBytes(ifProtocolAddress.ToValue() & ifProtocolMask.ToValue() + 1).Reverse().ToArray();
            //        }
            //        if (dhcpState == 0 || dhcpState == 1 && timewait > 10)
            //        {
            //            options = new byte[]
            //        { 
            //            53, 1, 1,
            //            61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId,
            //            12, 4, 78, 77, 76, 66,
            //            60, 8, 0x4d, 0x53, 0x46, 0x54, 0x20, 0x35, 0x2e, 0x30,
            //            255,
            //            0, 0, 0,
            //        };
            //            SendPacket(CreateDhcpPacket(32, options, true));
            //            if (dhcpState == 0)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            dhcpState = 1;
            //        }
            //        else if (dhcpState == 2 || dhcpState == 3 && timewait > 10)
            //        {
            //            options = new byte[]
            //        { 
            //            53, 1, 3,
            //            61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId,
            //            12, 4, 78, 77, 76, 66,
            //            50, 4, offeredIp[0], offeredIp[1], offeredIp[2], offeredIp[3],
            //            54, 4, dhcpServer[0], dhcpServer[1], dhcpServer[2], dhcpServer[3],
            //            60, 8, 0x4d, 0x53, 0x46, 0x54, 0x20, 0x35, 0x2e, 0x30,
            //            255,
            //            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            //        };
            //            SendPacket(CreateDhcpPacket(60, options, false));
            //            if (dhcpState == 2)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            dhcpState = 3;
            //        }
            //        else if (dhcpState == 4 && arpState == 1 && retries > 1)
            //        {
            //            if ((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1 & ifProtocolMask.ToValue()) !=
            //                (ifProtocolAddress.ToValue() & ifProtocolMask.ToValue()))
            //            {
            //                Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " is in a different network!");
            //                offeredIp = BitConverter.GetBytes(ifProtocolAddress.ToValue() & ifProtocolMask.ToValue() + 1).Reverse().ToArray();
            //                dhcpState = 6;
            //                arpState = 0;
            //                continue;
            //            }
            //            dhcpState = 5;
            //            arpState = 0;
            //            Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " OK!");
            //            dhcpClientId++;
            //            ownProtocolAddressByte = offeredIp;
            //            ownProtocolAddressString = ownProtocolAddressByte.SequenceToString(".");
            //            ownProtocolAddress = new IpV4Address(ownProtocolAddressString);
            //            SendArp();
            //            break;
            //        }
            //        else if (dhcpState == 4 && arpState == 0 || dhcpState == 4 && arpState == 1 && timewait > 10)
            //        {
            //            EthernetLayer ethernetLayer = new EthernetLayer
            //            {
            //                Source = ifHardwareAddress,
            //                Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //                EtherType = EthernetType.None,
            //            };

            //            ArpLayer arpLayer = new ArpLayer
            //            {
            //                ProtocolType = EthernetType.IpV4,
            //                Operation = ArpOperation.Request,
            //                SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
            //                SenderProtocolAddress = new byte[] { 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetProtocolAddress = offeredIp.AsReadOnly(),
            //            };

            //            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
            //            SendPacket(builder.Build(DateTime.Now));
            //            if (arpState == 0)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            arpState = 1;
            //        }
            //        else if (dhcpState == 4 && arpState == 2)
            //        {
            //            Global.WriteLog("DHCP: IP " + offeredIp.SequenceToString(".") + " is already used!");
            //            options = new byte[]
            //        { 
            //            53, 1, 4,
            //            61, 7, 1, 0x0A, 0x03, 0x03, 0x03, 0x03, (byte)dhcpClientId,
            //            50, 4, offeredIp[0], offeredIp[1], offeredIp[2], offeredIp[3],
            //            54, 4, dhcpServer[0], dhcpServer[1], dhcpServer[2], dhcpServer[3],
            //            255,
            //            //0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
            //        };
            //            SendPacket(CreateDhcpPacket(25, options, false, offeredIp));
            //            arpState = 0;
            //            dhcpState = 0;
            //        }
            //        else if (dhcpState == 6 && arpState == 1 && retries > 1)
            //        {
            //            dhcpState = 5;
            //            arpState = 0;
            //            Global.WriteLog("IPAlloc: IP " + offeredIp.SequenceToString(".") + " OK!");
            //            dhcpClientId++;
            //            ownProtocolAddressByte = offeredIp;
            //            ownProtocolAddressString = ownProtocolAddressByte.SequenceToString(".");
            //            ownProtocolAddress = new IpV4Address(ownProtocolAddressString);
            //            SendArp();
            //            break;
            //        }
            //        else if (dhcpState == 6 && arpState == 0 || dhcpState == 6 && arpState == 1 && timewait > 10)
            //        {
            //            EthernetLayer ethernetLayer = new EthernetLayer
            //            {
            //                Source = ifHardwareAddress,
            //                Destination = new MacAddress("FF:FF:FF:FF:FF:FF"),
            //                EtherType = EthernetType.None,
            //            };

            //            ArpLayer arpLayer = new ArpLayer
            //            {
            //                ProtocolType = EthernetType.IpV4,
            //                Operation = ArpOperation.Request,
            //                SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
            //                SenderProtocolAddress = new byte[] { 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetHardwareAddress = new byte[] { 0, 0, 0, 0, 0, 0 }.AsReadOnly(),
            //                TargetProtocolAddress = offeredIp.AsReadOnly(),
            //            };

            //            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
            //            SendPacket(builder.Build(DateTime.Now));
            //            if (arpState == 0)
            //                retries = 0;
            //            else
            //                retries++;
            //            timewait = 0;
            //            arpState = 1;
            //        }
            //        else if (dhcpState == 6 && arpState == 2)
            //        {
            //            if ((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1 & ifProtocolMask.ToValue()) !=
            //                (ifProtocolAddress.ToValue() & ifProtocolMask.ToValue()))
            //            {
            //                Global.WriteLog("IPAlloc: Couldn't allocate IP address!");
            //                break;
            //            }
            //            Global.WriteLog("IPAlloc: IP " + offeredIp.SequenceToString(".") + " is already used!");
            //            offeredIp = BitConverter.GetBytes((BitConverter.ToUInt32(offeredIp.Reverse().ToArray(), 0) + 1)).Reverse().ToArray();
            //            arpState = 0;
            //        }
            //        Thread.Sleep(100);
            //        timewait++;
            //    }
            //}

            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the interface
                PacketDevice selectedDevice = null;
                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.ToUpper().Contains(Guid.ToString().ToUpper()))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Load Balancer", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Load Balancer: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Load Balancer: Listening on " + Name + "...");
                        //communicator.SetFilter("(ether dst " + ifHardwareAddressString + " and (ip or arp)) or (ether dst FF:FF:FF:FF:FF:FF and arp)");
                        communicator.SetFilter("(ether dst " + ifHardwareAddressString + " and ip and (udp or icmp))");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!ThreadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            //if (ownProtocolAddressString == null)
                            //{
                            //    if (packet.Ethernet.IpV4.Udp.SourcePort == 67 && packet.Ethernet.IpV4.Udp.DestinationPort == 68 && (PublicVars.dhcpState == 1 || PublicVars.dhcpState == 3))
                            //    {
                            //        Dhcp dhcpReply = new Dhcp(packet.Ethernet.IpV4.Udp.Payload.ToArray());
                            //        if (PublicVars.dhcpId == dhcpReply.Id && dhcpReply.MessageType == 2)
                            //        {
                            //            if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 2)
                            //            {
                            //                PublicVars.offeredIp = dhcpReply.YourIp;
                            //                PublicVars.dhcpServer = dhcpReply.getOption((int)DhcpOptionCode.DhcpServerId);
                            //                PublicVars.dhcpState = 2;
                            //            }
                            //            else if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 5)
                            //            {
                            //                PublicVars.dhcpState = 4;
                            //            }
                            //            else if (dhcpReply.getOption((int)DhcpOptionCode.DhcpMsgType)[0] == 6)
                            //            {
                            //                PublicVars.offeredIp = null;
                            //                PublicVars.dhcpState = 0;
                            //                PublicVars.dhcpId = 0;
                            //            }
                            //        }
                            //    }
                            //    else if (packet.Ethernet.EtherType == EthernetType.Arp && PublicVars.arpState == 1)
                            //    {
                            //        if (packet.Ethernet.Arp.SenderProtocolAddress.SequenceEqual(PublicVars.offeredIp))
                            //            PublicVars.arpState = 2;
                            //    }
                            //}
                            //if (packet.Ethernet.EtherType == EthernetType.Arp)
                            //{
                            //    if (packet.Ethernet.Arp.TargetProtocolAddress.SequenceEqual(ownProtocolAddressByte) &&
                            //        packet.Ethernet.Arp.Operation == ArpOperation.Request)
                            //    {
                            //        EthernetLayer ethernetLayer = new EthernetLayer
                            //        {
                            //            Source = ifHardwareAddress,
                            //            Destination = packet.Ethernet.Source,
                            //            EtherType = EthernetType.None,
                            //        };

                            //        ArpLayer arpLayer = new ArpLayer
                            //        {
                            //            ProtocolType = EthernetType.IpV4,
                            //            Operation = ArpOperation.Reply,
                            //            SenderHardwareAddress = ifHardwareAddressByte.AsReadOnly(),
                            //            SenderProtocolAddress = packet.Ethernet.Arp.TargetProtocolAddress,
                            //            TargetHardwareAddress = packet.Ethernet.Arp.SenderHardwareAddress,
                            //            TargetProtocolAddress = packet.Ethernet.Arp.SenderProtocolAddress,
                            //        };

                            //        PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
                            //        communicator.SendPacket(builder.Build(DateTime.Now));
                            //    }
                            //}
                            if (tapWorker.Initialized.IsSet)
                            {
                                if (packet.Ethernet.IpV4.Length > MTU) // only UDP and ICMP
                                {
                                    EthernetLayer ethernetLayer = new EthernetLayer
                                    {
                                        Source = ifHardwareAddress,
                                        Destination = packet.Ethernet.Source,
                                        EtherType = EthernetType.None,
                                    };
                                    IpV4Layer ipV4Layer = new IpV4Layer
                                    {
                                        Source = packet.Ethernet.IpV4.Destination,
                                        CurrentDestination = packet.Ethernet.IpV4.Source,
                                        Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                        HeaderChecksum = null, // Will be filled automatically.
                                        Identification = 123,
                                        Options = packet.Ethernet.IpV4.Options,
                                        Protocol = packet.Ethernet.IpV4.Protocol,
                                        Ttl = packet.Ethernet.IpV4.Ttl,
                                        TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                    };
                                    IcmpDestinationUnreachableLayer icmpLayer = new IcmpDestinationUnreachableLayer
                                    {
                                        Code = IcmpCodeDestinationUnreachable.FragmentationNeededAndDoNotFragmentSet,
                                        NextHopMaximumTransmissionUnit = (ushort)MTU,
                                    };

                                    PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);
                                    SendPacket(builder.Build(DateTime.Now));
                                    // TODO: fix warning spam
                                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                                        Global.ShowTrayTip("Load Balancer", "IP packet larger than the MTU detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                                    Global.WriteLog("Load Balancer: IP packet larger than the MTU detected on " + Name);
                                    return;
                                }
                                if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.DoNotFragment ||
                                packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset == 0)
                                {
                                    if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.InternetControlMessageProtocol)
                                    {

                                        if (packet.Ethernet.IpV4.Destination == ifProtocolAddress)
                                            if ((packet.Ethernet.IpV4.Icmp.MessageType == IcmpMessageType.EchoReply || packet.Ethernet.IpV4.Fragmentation.Offset > 0))
                                            {
                                                EthernetLayer ethernetLayer = new EthernetLayer
                                                {
                                                    Source = tapWorker.ownHardwareAddress,
                                                    Destination = tapWorker.ifHardwareAddress,
                                                    EtherType = EthernetType.None,
                                                };
                                                IpV4Layer ipV4Layer = new IpV4Layer
                                                {
                                                    Source = packet.Ethernet.IpV4.Source,
                                                    CurrentDestination = tapWorker.ifProtocolAddress,
                                                    Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                                    HeaderChecksum = null, // Will be filled automatically.
                                                    Identification = packet.Ethernet.IpV4.Identification,
                                                    Options = packet.Ethernet.IpV4.Options,
                                                    Protocol = packet.Ethernet.IpV4.Protocol,
                                                    Ttl = packet.Ethernet.IpV4.Ttl,
                                                    TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                                };
                                                PayloadLayer payloadLayer = new PayloadLayer
                                                {
                                                    Data = new Datagram(packet.Ethernet.IpV4.Payload.ToArray()),
                                                };
                                                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer);
                                                tapWorker.SendPacket(builder.Build(DateTime.Now));
                                            }
                                    }
                                    //else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
                                    //{
                                    //    if (packet.Ethernet.IpV4.Destination == ifProtocolAddress)
                                    //    {
                                    //        lock (RoutingTable.lockObj)
                                    //            routingObject = RoutingTable.TranslateBack(packet);
                                    //        if (routingObject.ifIndex == -1)
                                    //            return;
                                    //        EthernetLayer ethernetLayer = new EthernetLayer
                                    //        {
                                    //            Source = TapWorker.ownHardwareAddress,
                                    //            Destination = TapWorker.ifHardwareAddress,
                                    //            EtherType = packet.Ethernet.EtherType,
                                    //        };
                                    //        IpV4Layer ipV4Layer = new IpV4Layer
                                    //        {
                                    //            Source = packet.Ethernet.IpV4.Source,
                                    //            CurrentDestination = TapWorker.ifProtocolAddress,
                                    //            Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                    //            HeaderChecksum = null, // Will be filled automatically.
                                    //            Identification = packet.Ethernet.IpV4.Identification,
                                    //            Options = packet.Ethernet.IpV4.Options,
                                    //            Protocol = packet.Ethernet.IpV4.Protocol,
                                    //            Ttl = packet.Ethernet.IpV4.Ttl,
                                    //            TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                    //        };
                                    //        TcpLayer tcpLayer = new TcpLayer
                                    //        {
                                    //            SourcePort = packet.Ethernet.IpV4.Tcp.SourcePort,
                                    //            DestinationPort = routingObject.localPort,
                                    //            Checksum = null, // Will be filled automatically.
                                    //            SequenceNumber = packet.Ethernet.IpV4.Tcp.SequenceNumber,
                                    //            AcknowledgmentNumber = routingObject.ack,
                                    //            ControlBits = packet.Ethernet.IpV4.Tcp.ControlBits,
                                    //            Window = packet.Ethernet.IpV4.Tcp.Window,
                                    //            UrgentPointer = packet.Ethernet.IpV4.Tcp.UrgentPointer,
                                    //            Options = packet.Ethernet.IpV4.Tcp.Options,
                                    //        };
                                    //        PayloadLayer payloadLayer = new PayloadLayer
                                    //        {
                                    //            Data = new Datagram(packet.Ethernet.IpV4.Tcp.Payload.ToArray()),
                                    //        };
                                    //        PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);
                                    //        MainThread.tapWorker.SendPacket(builder.Build(DateTime.Now));
                                    //    }
                                    //}
                                    else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Udp)
                                    {
                                        if (packet.Ethernet.IpV4.Destination == ifProtocolAddress)
                                        {
                                            phyRoutingObject = RoutingTable.IsUdpConn(packet);
                                            if (phyRoutingObject.ifIndex == -1)
                                                return;
                                            EthernetLayer ethernetLayer = new EthernetLayer
                                            {
                                                Source = tapWorker.ownHardwareAddress,
                                                Destination = tapWorker.ifHardwareAddress,
                                                EtherType = packet.Ethernet.EtherType,
                                            };
                                            IpV4Layer ipV4Layer = new IpV4Layer
                                            {
                                                Source = packet.Ethernet.IpV4.Source,
                                                CurrentDestination = tapWorker.ifProtocolAddress,
                                                Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                                HeaderChecksum = null, // Will be filled automatically.
                                                Identification = packet.Ethernet.IpV4.Identification,
                                                Options = packet.Ethernet.IpV4.Options,
                                                Protocol = packet.Ethernet.IpV4.Protocol,
                                                Ttl = packet.Ethernet.IpV4.Ttl,
                                                TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                            };
                                            UdpLayer udpLayer = new UdpLayer
                                            {
                                                SourcePort = packet.Ethernet.IpV4.Udp.SourcePort,
                                                DestinationPort = packet.Ethernet.IpV4.Udp.DestinationPort,
                                                Checksum = null, // Will be filled automatically.
                                                CalculateChecksumValue = packet.Ethernet.IpV4.Udp.IsChecksumOptional,
                                            };
                                            PayloadLayer payloadLayer = new PayloadLayer
                                            {
                                                Data = new Datagram(packet.Ethernet.IpV4.Udp.Payload.ToArray()),
                                            };
                                            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);
                                            tapWorker.SendPacket(builder.Build(DateTime.Now));
                                        }
                                    }
                                }
                                else if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.MoreFragments ||
                                    packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset > 0)
                                {
                                    // TODO: fix warning spam
                                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                                        Global.ShowTrayTip("Load Balancer", "IP fragmentation detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                                    Global.WriteLog("Load Balancer: IP fragmentation detected on " + Name);
                                    //fragments = fragBuffer.Add(packet);
                                    //if (fragments != null)
                                    //    for (int i = 0; i < fragments.Count; i++)
                                    //    {
                                    //        IpV4Handler(fragments[i], fragments);
                                    //    }
                                }
                            }
                        });
                    }
                }
                catch (Exception e)
                {
                    if (ThreadActive.IsSet)
                    {
                        ThreadActive.Reset();
                        Global.WriteLog("Load Balancer: " + Name + " has disconnected");
                        if (Global.Config.Gadget.Debug)
                            Global.WriteLog(e.ToString());
                        Global.ShowTrayTip("Load Balancer", Name + " has disconnected", System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
Пример #39
0
        public static void Test_InterpretingThePackets_01()
        {
            // from project InterpretingThePackets
            _tr.WriteLine("Test_InterpretingThePackets_01");
            PacketDevice device = SelectDevice();
            if (device == null)
                return;
            __communicator = null;
            //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution);
            _rs.OnAbortExecution = OnAbortExecution;
            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 (__communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    // Check the link layer. We support only Ethernet for simplicity.
                    if (__communicator.DataLink.Kind != DataLinkKind.Ethernet)
                    {
                        _tr.WriteLine("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);
                    }

                    _tr.WriteLine("Listening on " + device.Description + "...");

                    // start the capture
                    __communicator.ReceivePackets(0, InterpretingPacketHandler);
                }
            }
            catch (Exception ex)
            {
                _tr.WriteLine(ex.Message);
            }
            finally
            {
                //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution);
            }
        }
Пример #40
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;
			}

		}