Пример #1
0
        // 获取设备的 MAC 地址,如果是 AP 则返回 Null
        public string GetWlanSa(CaptureEventArgs e)
        {
            var      p        = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            MacFrame macFrame = (MacFrame)p.PayloadPacket;

            if (macFrame != null)                                                                            // 只拉取 802.11 的 MAC 帧
            {
                if (macFrame.FrameControl.SubType == FrameControlField.FrameSubTypes.ManagementProbeRequest) // 如果是设备请求 AP 列表
                {
                    ProbeRequestFrame probeReqFrame = (ProbeRequestFrame)macFrame;
                    macaddr = probeReqFrame.SourceAddress.ToString();
                    valid   = true;
                }
                else if (macFrame.FrameControl.SubType == FrameControlField.FrameSubTypes.DataNullFunctionNoData) // 如果是设备发送心跳
                {
                    NullDataFrame nullDataFrame = (NullDataFrame)macFrame;
                    macaddr = nullDataFrame.SourceAddress.ToString();
                    valid   = true;
                }
            }

            if (valid) // 格式化 MAC 地址
            {
                macaddr = Regex.Replace(macaddr, @"^(..)(..)(..)(..)(..)(..)$", "$1-$2-$3-$4-$5-$6");
            }
            else
            {
                return(null); //是 AP 则返回 Null
            }

            return(macaddr);
        }
Пример #2
0
            public void Test_Constructor()
            {
                var dev = new CaptureFileReaderDevice("../../CaptureFiles/80211_probe_request_frame.pcap");

                dev.Open();
                var rawCapture = dev.GetNextPacket();

                dev.Close();

                Packet            p     = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
                ProbeRequestFrame frame = (ProbeRequestFrame)p.PayloadPacket;

                Assert.AreEqual(0, frame.FrameControl.ProtocolVersion);
                Assert.AreEqual(FrameControlField.FrameSubTypes.ManagementProbeRequest, frame.FrameControl.SubType);
                Assert.IsFalse(frame.FrameControl.ToDS);
                Assert.IsFalse(frame.FrameControl.FromDS);
                Assert.IsFalse(frame.FrameControl.MoreFragments);
                Assert.IsFalse(frame.FrameControl.Retry);
                Assert.IsFalse(frame.FrameControl.PowerManagement);
                Assert.IsFalse(frame.FrameControl.MoreData);
                Assert.IsFalse(frame.FrameControl.Protected);
                Assert.IsFalse(frame.FrameControl.Order);
                Assert.AreEqual(0, frame.Duration.Field);  //this need expanding on in the future
                Assert.AreEqual("FFFFFFFFFFFF", frame.DestinationAddress.ToString().ToUpper());
                Assert.AreEqual("0020008AB749", frame.SourceAddress.ToString().ToUpper());
                Assert.AreEqual("FFFFFFFFFFFF", frame.BssId.ToString().ToUpper());
                Assert.AreEqual(0, frame.SequenceControl.FragmentNumber);
                Assert.AreEqual(234, frame.SequenceControl.SequenceNumber);

                Assert.AreEqual(0xD83CB03D, frame.FrameCheckSequence);
                Assert.AreEqual(45, frame.FrameSize);
            }
Пример #3
0
            public void Test_ConstructorWithCorruptBuffer()
            {
                //buffer is way too short for frame. We are just checking it doesn't throw
                byte[]            corruptBuffer = new byte[] { 0x01 };
                ProbeRequestFrame frame         = new ProbeRequestFrame(new ByteArraySegment(corruptBuffer));

                Assert.IsFalse(frame.FCSValid);
            }
Пример #4
0
            public void Test_Constructor_ConstructWithValues()
            {
                InformationElement ssidInfoElement = new InformationElement(InformationElement.ElementId.ServiceSetIdentity,
                                                                            new Byte[] { 0x68, 0x65, 0x6c, 0x6c, 0x6f });
                InformationElement vendorElement = new InformationElement(InformationElement.ElementId.VendorSpecific,
                                                                          new Byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 });


                ProbeRequestFrame frame = new ProbeRequestFrame(PhysicalAddress.Parse("111111111111"),
                                                                PhysicalAddress.Parse("222222222222"),
                                                                PhysicalAddress.Parse("333333333333"),
                                                                new InformationElementList()
                {
                    ssidInfoElement, vendorElement
                });

                frame.FrameControl.ToDS          = false;
                frame.FrameControl.FromDS        = true;
                frame.FrameControl.MoreFragments = true;

                frame.Duration.Field = 0x1234;

                frame.SequenceControl.SequenceNumber = 0x77;
                frame.SequenceControl.FragmentNumber = 0x1;

                frame.UpdateFrameCheckSequence();
                UInt32 fcs = frame.FrameCheckSequence;

                //serialize the frame into a byte buffer
                var bytes = frame.Bytes;
                var bas   = new ByteArraySegment(bytes);

                //create a new frame that should be identical to the original
                ProbeRequestFrame recreatedFrame = MacFrame.ParsePacket(bas) as ProbeRequestFrame;

                recreatedFrame.UpdateFrameCheckSequence();

                Assert.AreEqual(FrameControlField.FrameSubTypes.ManagementProbeRequest, recreatedFrame.FrameControl.SubType);
                Assert.IsFalse(recreatedFrame.FrameControl.ToDS);
                Assert.IsTrue(recreatedFrame.FrameControl.FromDS);
                Assert.IsTrue(recreatedFrame.FrameControl.MoreFragments);

                Assert.AreEqual(0x77, recreatedFrame.SequenceControl.SequenceNumber);
                Assert.AreEqual(0x1, recreatedFrame.SequenceControl.FragmentNumber);

                Assert.AreEqual("111111111111", recreatedFrame.SourceAddress.ToString().ToUpper());
                Assert.AreEqual("222222222222", recreatedFrame.DestinationAddress.ToString().ToUpper());
                Assert.AreEqual("333333333333", recreatedFrame.BssId.ToString().ToUpper());

                Assert.AreEqual(ssidInfoElement, recreatedFrame.InformationElements [0]);
                Assert.AreEqual(vendorElement, recreatedFrame.InformationElements [1]);

                Assert.AreEqual(fcs, recreatedFrame.FrameCheckSequence);
            }
Пример #5
0
         public void Test_Constructor_ConstructWithValues ()
         {
             InformationElement ssidInfoElement = new InformationElement (InformationElement.ElementId.ServiceSetIdentity, 
                                                                        new Byte[] { 0x68, 0x65, 0x6c, 0x6c, 0x6f });
             InformationElement vendorElement = new InformationElement (InformationElement.ElementId.VendorSpecific,
                                                                        new Byte[] {0x01, 0x02, 0x03, 0x04, 0x05});
             
             
             ProbeRequestFrame frame = new ProbeRequestFrame (PhysicalAddress.Parse ("111111111111"),
                                                              PhysicalAddress.Parse ("222222222222"),
                                                              PhysicalAddress.Parse ("333333333333"),
                                                             new InformationElementList (){ssidInfoElement, vendorElement});
             
             frame.FrameControl.ToDS = false;
             frame.FrameControl.FromDS = true;
             frame.FrameControl.MoreFragments = true;
             
             frame.Duration.Field = 0x1234;
             
             frame.SequenceControl.SequenceNumber = 0x77;
             frame.SequenceControl.FragmentNumber = 0x1;
             
             frame.UpdateFrameCheckSequence ();
             UInt32 fcs = frame.FrameCheckSequence;
             
             //serialize the frame into a byte buffer
             var bytes = frame.Bytes;
             var bas = new ByteArraySegment (bytes);
 
             //create a new frame that should be identical to the original
             ProbeRequestFrame recreatedFrame = MacFrame.ParsePacket (bas) as ProbeRequestFrame;
             recreatedFrame.UpdateFrameCheckSequence();
             
             Assert.AreEqual (FrameControlField.FrameSubTypes.ManagementProbeRequest, recreatedFrame.FrameControl.SubType);
             Assert.IsFalse (recreatedFrame.FrameControl.ToDS);
             Assert.IsTrue (recreatedFrame.FrameControl.FromDS);
             Assert.IsTrue (recreatedFrame.FrameControl.MoreFragments);
             
             Assert.AreEqual (0x77, recreatedFrame.SequenceControl.SequenceNumber);
             Assert.AreEqual (0x1, recreatedFrame.SequenceControl.FragmentNumber);
             
             Assert.AreEqual ("111111111111", recreatedFrame.SourceAddress.ToString ().ToUpper ());
             Assert.AreEqual ("222222222222", recreatedFrame.DestinationAddress.ToString ().ToUpper ());
             Assert.AreEqual ("333333333333", recreatedFrame.BssId.ToString ().ToUpper ());
             
             Assert.AreEqual (ssidInfoElement, recreatedFrame.InformationElements [0]);
             Assert.AreEqual (vendorElement, recreatedFrame.InformationElements [1]);
             
             Assert.AreEqual (fcs, recreatedFrame.FrameCheckSequence);
         }
Пример #6
0
        private static void Main()
        {
            // Print SharpPcap version
            var ver = SharpPcap.Version.VersionString;

            Console.WriteLine("PacketDotNet example using SharpPcap {0}", ver);

            // Retrieve the device list
            var devices = AirPcapDeviceList.Instance;

            // If no devices were found print an error
            if (devices.Count < 1)
            {
                Console.WriteLine("No devices were found on this machine");
                return;
            }

            Console.WriteLine();
            Console.WriteLine("The following devices are available on this machine:");
            Console.WriteLine("----------------------------------------------------");
            Console.WriteLine();

            var i = 0;

            // Print out the devices
            foreach (var dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
                i++;
            }

            Console.WriteLine();
            Console.Write("-- Please choose a device to capture: ");
            i = Int32.Parse(Console.ReadLine() ?? throw new InvalidOperationException());

            // Register a cancel handler that lets us break out of our capture loop
            // since we currently need to synchronously receive packets in order to get
            // raw packets. Future versions of SharpPcap are likely to
            // return ONLY raw packets at which time we can simplify this code and
            // use a PcapDevice.OnPacketArrival handler
            Console.CancelKeyPress += HandleCancelKeyPress;

            var device = (AirPcapDevice)devices[i];

            device.Open(DeviceMode.Normal);
            device.FcsValidation   = AirPcapValidationType.ACCEPT_CORRECT_FRAMES;
            _adapterAddress        = device.MacAddress;
            device.AirPcapLinkType = AirPcapLinkTypes._802_11;

            var broadcastAddress = PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF");

            Console.Write("Please enter the SSID to probe for (use empty string for broadcast probe): ");
            var ssid = Console.ReadLine();

            Console.WriteLine();

            //Make the probe packet to send
            var encoding         = new ASCIIEncoding();
            var ssidIe           = new InformationElement(InformationElement.ElementId.ServiceSetIdentity, encoding.GetBytes(ssid ?? throw new InvalidOperationException()));
            var supportedRatesIe = new InformationElement(InformationElement.ElementId.SupportedRates,
                                                          new byte[] { 0x02, 0x04, 0x0b, 0x16, 0x0c, 0x12, 0x18, 0x24 });

            var extendedSupportedRatesIe = new InformationElement(InformationElement.ElementId.ExtendedSupportedRates,
                                                                  new byte[] { 0x30, 0x48, 0x60, 0x6c });

            //Create a broadcast probe
            var probe = new ProbeRequestFrame(device.MacAddress,
                                              broadcastAddress,
                                              broadcastAddress,
                                              new InformationElementList {
                ssidIe, supportedRatesIe, extendedSupportedRatesIe
            });

            var probeBytes = probe.Bytes;

            device.SendPacket(probeBytes, probeBytes.Length - 4);

            while (_stopCapturing == false)
            {
                var rawCapture = device.GetNextPacket();

                // null packets can be returned in the case where
                // the GetNextRawPacket() timed out, we should just attempt
                // to retrieve another packet by looping the while() again
                if (rawCapture == null)
                {
                    // go back to the start of the while()
                    continue;
                }

                // use PacketDotNet to parse this packet and print out
                // its high level information
                if (Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) is MacFrame p && p.FrameControl.SubType == FrameControlField.FrameSubTypes.ManagementProbeResponse)
                {
                    if (p is ProbeResponseFrame probeResponse && probeResponse.DestinationAddress.Equals(_adapterAddress))
                    {
                        var ie = probeResponse.InformationElements.FindFirstById(InformationElement.ElementId.ServiceSetIdentity);
                        Console.WriteLine("Response: {0}, SSID: {1}", probeResponse.SourceAddress, Encoding.UTF8.GetString(ie.Value));
                    }
                }
            }
        }
Пример #7
0
            /// <summary>
            /// Parses the <see cref="Kavprot.Packets.Utils.ByteArraySegment"/> into a MacFrame.
            /// </summary>
            /// <returns>
            /// The parsed MacFrame or null if it could not be parsed.
            /// </returns>
            /// <param name='bas'>
            /// The bytes of the packet. bas.Offset should point to the first byte in the mac frame.
            /// </param>
            /// <remarks>If the provided bytes contain the FCS then call <see cref="MacFrame.ParsePacketWithFcs"/> instead. The presence of the
            /// FCS is usually determined by configuration of the device used to capture the packets.</remarks>
            public static MacFrame ParsePacket(ByteArraySegment bas)
            {
                if (bas.Length < MacFields.FrameControlLength)
                {
                    //there isn't enough data to even try and work out what type of packet it is
                    return(null);
                }
                //this is a bit ugly as we will end up parsing the framecontrol field twice, once here and once
                //inside the packet constructor. Could create the framecontrol and pass it to the packet but I think that is equally ugly
                FrameControlField frameControl = new FrameControlField(
                    EndianBitConverter.Big.ToUInt16(bas.Bytes, bas.Offset));

                MacFrame macFrame = null;

                switch (frameControl.SubType)
                {
                case FrameControlField.FrameSubTypes.ManagementAssociationRequest:
                {
                    macFrame = new AssociationRequestFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ManagementAssociationResponse:
                {
                    macFrame = new AssociationResponseFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ManagementReassociationRequest:
                {
                    macFrame = new ReassociationRequestFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ManagementReassociationResponse:
                {
                    macFrame = new AssociationResponseFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ManagementProbeRequest:
                {
                    macFrame = new ProbeRequestFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ManagementProbeResponse:
                {
                    macFrame = new ProbeResponseFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ManagementReserved0:
                    break; //TODO

                case FrameControlField.FrameSubTypes.ManagementReserved1:
                    break; //TODO

                case FrameControlField.FrameSubTypes.ManagementBeacon:
                {
                    macFrame = new BeaconFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ManagementATIM:
                    break; //TODO

                case FrameControlField.FrameSubTypes.ManagementDisassociation:
                {
                    macFrame = new DisassociationFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ManagementAuthentication:
                {
                    macFrame = new AuthenticationFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ManagementDeauthentication:
                {
                    macFrame = new DeauthenticationFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ManagementAction:
                {
                    macFrame = new ActionFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ManagementReserved3:
                    break; //TODO

                case FrameControlField.FrameSubTypes.ControlBlockAcknowledgmentRequest:
                {
                    macFrame = new BlockAcknowledgmentRequestFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ControlBlockAcknowledgment:
                {
                    macFrame = new BlockAcknowledgmentFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ControlPSPoll:
                    break; //TODO

                case FrameControlField.FrameSubTypes.ControlRTS:
                {
                    macFrame = new RtsFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ControlCTS:
                {
                    macFrame = new CtsFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ControlACK:
                {
                    macFrame = new AckFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ControlCFEnd:
                {
                    macFrame = new ContentionFreeEndFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.ControlCFEndCFACK:
                    break; //TODO

                case FrameControlField.FrameSubTypes.Data:
                case FrameControlField.FrameSubTypes.DataCFACK:
                case FrameControlField.FrameSubTypes.DataCFPoll:
                case FrameControlField.FrameSubTypes.DataCFAckCFPoll:
                {
                    macFrame = new DataDataFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.DataNullFunctionNoData:
                case FrameControlField.FrameSubTypes.DataCFAckNoData:
                case FrameControlField.FrameSubTypes.DataCFPollNoData:
                case FrameControlField.FrameSubTypes.DataCFAckCFPollNoData:
                {
                    macFrame = new NullDataFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.QosData:
                case FrameControlField.FrameSubTypes.QosDataAndCFAck:
                case FrameControlField.FrameSubTypes.QosDataAndCFPoll:
                case FrameControlField.FrameSubTypes.QosDataAndCFAckAndCFPoll:
                {
                    macFrame = new QosDataFrame(bas);
                    break;
                }

                case FrameControlField.FrameSubTypes.QosNullData:
                case FrameControlField.FrameSubTypes.QosCFAck:
                case FrameControlField.FrameSubTypes.QosCFPoll:
                case FrameControlField.FrameSubTypes.QosCFAckAndCFPoll:
                {
                    macFrame = new QosNullDataFrame(bas);
                    break;
                }

                default:
                    //this is an unsupported (and unknown) packet type
                    break;
                }

                return(macFrame);
            }
Пример #8
0
			public void Test_ConstructorWithCorruptBuffer ()
			{
				//buffer is way too short for frame. We are just checking it doesn't throw
				byte[] corruptBuffer = new byte[]{0x01};
				ProbeRequestFrame frame = new ProbeRequestFrame(new ByteArraySegment(corruptBuffer));
				Assert.IsFalse(frame.FCSValid);
			}
Пример #9
0
        static void Main(string[] args)
        {
            // Print SharpPcap version
            string ver = SharpPcap.Version.VersionString;
            Console.WriteLine("PacketDotNet example using SharpPcap {0}", ver);

            // Retrieve the device list
            var devices = AirPcapDeviceList.Instance;

            // If no devices were found print an error
            if (devices.Count < 1)
            {
                Console.WriteLine("No devices were found on this machine");
                return;
            }

            Console.WriteLine();
            Console.WriteLine("The following devices are available on this machine:");
            Console.WriteLine("----------------------------------------------------");
            Console.WriteLine();

            int i = 0;

            // Print out the devices
            foreach (var dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
                i++;
            }

            Console.WriteLine();
            Console.Write("-- Please choose a device to capture: ");
            i = int.Parse(Console.ReadLine());

            // Register a cancle handler that lets us break out of our capture loop
            // since we currently need to synchronously receive packets in order to get
            // raw packets. Future versions of SharpPcap are likely to
            // return ONLY raw packets at which time we can simplify this code and
            // use a PcapDevice.OnPacketArrival handler
            Console.CancelKeyPress += HandleCancelKeyPress;

            var device = (AirPcapDevice)devices[i];
            
            device.Open(DeviceMode.Normal);
            device.FcsValidation = AirPcapValidationType.ACCEPT_CORRECT_FRAMES;
            adapterAddress = device.MacAddress;
            device.AirPcapLinkType = AirPcapLinkTypes._802_11;

            PhysicalAddress broadcastAddress = PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF");

            
            Console.Write("Please enter the SSID to probe for (use empty string for broadcast probe): ");
            String ssid = Console.ReadLine();
            Console.WriteLine();



            //Make the probe packet to send
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            InformationElement ssidIe = new InformationElement(InformationElement.ElementId.ServiceSetIdentity, encoding.GetBytes(ssid));
            InformationElement supportedRatesIe = new InformationElement(InformationElement.ElementId.SupportedRates,
                new byte[] { 0x02, 0x04, 0x0b, 0x16, 0x0c, 0x12, 0x18, 0x24 });
            InformationElement extendedSupportedRatesIe = new InformationElement(InformationElement.ElementId.ExtendedSupportedRates,
                new byte[] { 0x30, 0x48, 0x60, 0x6c });
            //Create a broadcast probe
            ProbeRequestFrame probe = new ProbeRequestFrame(device.MacAddress,
                                                            broadcastAddress,
                                                            broadcastAddress,
                                                            new InformationElementList() {ssidIe, supportedRatesIe, extendedSupportedRatesIe});

            Byte[] probeBytes = probe.Bytes;
            device.SendPacket(probeBytes, probeBytes.Length - 4);


            while (stopCapturing == false)
            {
                var rawCapture = device.GetNextPacket();

                // null packets can be returned in the case where
                // the GetNextRawPacket() timed out, we should just attempt
                // to retrieve another packet by looping the while() again
                if (rawCapture == null)
                {
                    // go back to the start of the while()
                    continue;
                }

                // use PacketDotNet to parse this packet and print out
                // its high level information
                MacFrame p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as MacFrame;
                if (p.FrameControl.SubType == FrameControlField.FrameSubTypes.ManagementProbeResponse)
                {
                    ProbeResponseFrame probeResponse = p as ProbeResponseFrame;
                    if (probeResponse.DestinationAddress.Equals(adapterAddress))
                    {
                        var ie = probeResponse.InformationElements.FindFirstById(InformationElement.ElementId.ServiceSetIdentity);
                        Console.WriteLine("Response: {0}, SSID: {1}", probeResponse.SourceAddress, Encoding.UTF8.GetString(ie.Value)); 
                    }
                }
            }
        }