Пример #1
0
        public virtual void TCPData()
        {
            PcapOfflineDevice dev = Pcap.GetPcapOfflineDevice("../../capture_files/tcp_with_extra_bytes.pcap");

            dev.Open();

            Packet p;

            p = dev.GetNextPacket();

            Assert.IsNotNull(p);

            Console.WriteLine(p.GetType());
            Assert.IsTrue(p is TCPPacket);

            TCPPacket t = (TCPPacket)p;

            // even though the packet has 6 bytes of extra data, the ip packet shows a size of
            // 40 and the ip header has a length of 20. The TCP header is also 20 bytes so
            // there should be zero bytes in the TCPData value
            int expectedTcpDataLength = 0;

            Assert.AreEqual(expectedTcpDataLength, t.TCPData.Length);

            dev.Close();
        }
Пример #2
0
        public void LibpcapVersionTest()
        {
            var libpcap  = "libpcap version 1.10.0";
            var versions = new[] {
                // https://github.com/nmap/nmap/issues/1566
                "libpcap version 1.9.0 (packet.dll version 0.992)",
                // Npcap
                "Npcap version 0.991, based on libpcap version 1.8.1",
                // Libpcap
                libpcap + " (with TPACKET_V3)",
                libpcap + " (SNF-only)",
                libpcap + " (Septel-only)",
                libpcap + " (DPDK-only)",
                "DOS-" + libpcap,
                // WinPcap (legacy)
                "WinPcap version 4.1.3 (packet.dll version 4.1.0.2980), based on libpcap version 1.0 branch 1_0_rel0b (20091008)",
                // Currently installed
                Pcap.Version
            };

            foreach (var ver in versions)
            {
                var version = Pcap.GetLibpcapVersion(ver);
                Assert.GreaterOrEqual(version, new Version(1, 0));
            }
            Assert.AreEqual(Pcap.GetLibpcapVersion("invalid"), new Version(0, 0));
        }
Пример #3
0
        public void IPv6PacketTestParsing()
        {
            PcapOfflineDevice dev = Pcap.GetPcapOfflineDevice("../../capture_files/ipv6_icmpv6_packet.pcap");

            dev.Open();

            Packet p;
            int    packetIndex = 0;

            while ((p = dev.GetNextPacket()) != null)
            {
                Console.WriteLine("got packet");
                switch (packetIndex)
                {
                case 0:
                    VerifyPacket0(p);
                    break;

                default:
                    Assert.Fail("didn't expect to get to packetIndex " + packetIndex);
                    break;
                }

                packetIndex++;
            }

            dev.Close();
        }
Пример #4
0
 public Form1()
 {
     InitializeComponent();
     InitializeBackgroundWorker();
     comboBox3.DataSource    = Pcap.GetAllDevices();
     comboBox3.DisplayMember = "Description";
 }
Пример #5
0
        public void ParsingArpPacketRequestResponse()
        {
            PcapOfflineDevice dev = Pcap.GetPcapOfflineDevice("../../capture_files/arp_request_response.pcap");

            dev.Open();

            Packet p;
            int    packetIndex = 0;

            while ((p = dev.GetNextPacket()) != null)
            {
                Console.WriteLine("got packet");
                Console.WriteLine("{0}", p.ToString());
                switch (packetIndex)
                {
                case 0:
                    VerifyPacket0(p);
                    break;

                case 1:
                    VerifyPacket1(p);
                    break;

                default:
                    Assert.Fail("didn't expect to get to packetIndex " + packetIndex);
                    break;
                }

                packetIndex++;
            }

            dev.Close();
        }
Пример #6
0
        public void UDPData()
        {
            Packet    p;
            UDPPacket u;

            PcapOfflineDevice dev = Pcap.GetPcapOfflineDevice("../../capture_files/udp_dns_request_response.pcap");

            dev.Open();

            // check the first packet
            p = dev.GetNextPacket();

            Assert.IsNotNull(p);
            Assert.IsTrue(p is UDPPacket);

            u = (UDPPacket)p;
            Assert.AreEqual(41 - u.UDPHeader.Length, u.UDPData.Length, "UDPData.Length mismatch");


            // check the second packet
            p = dev.GetNextPacket();

            Assert.IsNotNull(p);
            Assert.IsTrue(p is UDPPacket);

            u = (UDPPacket)p;
            Assert.AreEqual(356 - u.UDPHeader.Length, u.UDPData.Length, "UDPData.Length mismatch");

            Console.WriteLine("u is {0}", u.ToString());

            dev.Close();
        }
        private void FillComboBoxDevices()
        {
            // Retrieve the device list and set it as the combo box data source
            comboBoxDevices.DataSource = Pcap.GetAllDevices();

            // Set the combo box display member
            comboBoxDevices.DisplayMember = "Description";
        }
Пример #8
0
        public static void Main(string[] args)
        {
            string ver = SharpPcap.Version.VersionString;

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, Example2.ArpResolve.cs", ver);
            Console.WriteLine();

            /* Retrieve the device list */
            List <PcapDevice> devices = Pcap.GetAllDevices();

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

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

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
                i++;
            }

            Console.WriteLine();
            Console.Write("-- Please choose a device for sending the ARP request: ");
            i = int.Parse(Console.ReadLine());

            string device = devices[i].Name;

            System.Net.IPAddress ip;

            while (true)
            {
                Console.Write("-- Please enter IP address to be resolved by ARP: ");
                if (System.Net.IPAddress.TryParse(Console.ReadLine(), out ip))
                {
                    break;
                }
                Console.WriteLine("Bad IP address format, please try again");
            }

            //Create a new ARP resolver
            //(for more info, see:
            //http://www.tamirgal.com/home/SourceView.aspx?Item=SharpPcap&File=ARP.cs)
            ARP arper = new ARP(device);

            //print the resolved address
            Console.WriteLine(ip + " is at: " + arper.Resolve(ip));
        }
Пример #9
0
        private IEnumerable <LabeledPacketData> PrepareSinglePacketData(string[] packetFiles, string[] maliciousIps)
        {
            Stopwatch stopwatch = new Stopwatch();

            Console.WriteLine("=============== Preparing Single Packet Data ===============");
            Console.WriteLine();
            Console.WriteLine($"Start data prep using {packetFiles.Length} packet files, {maliciousIps.Length} malicious Ips.");
            Console.WriteLine($"Files Being Processed:");

            foreach (var file in packetFiles)
            {
                Console.WriteLine($"\t{file}");
            }

            stopwatch.Start();

            var ipv4Packets = packetFiles
                              .SelectMany(x => Pcap.FromFile(x).Packets)
                              .Where(x => x.Body is EthernetFrame && ((EthernetFrame)x.Body).EtherType == EthernetFrame.EtherTypeEnum.Ipv4)
                              .Select(x => (TimeStamp: x.TsSec, Packet: ((Ipv4Packet)((EthernetFrame)x.Body).Body)))
                              .ToArray();

            var largestPacketSize = ipv4Packets.Max(x => x.Packet.M_RawBody.Length);

            Console.WriteLine($"Largest Packet Size: {largestPacketSize} bytes.");

            var packets = ipv4Packets
                          .Select(x =>
            {
                var labeledPacket = new LabeledPacketData()
                {
                    SrcIp        = x.Packet.SrcIpAddrStr,
                    IsMalicious  = maliciousIps.Contains(x.Packet.SrcIpAddrStr),
                    PacketLength = x.Packet.M_RawBody.Length,
                    PacketBody   = new byte[largestPacketSize]
                };

                Array.Copy(x.Packet.M_RawBody, labeledPacket.PacketBody, x.Packet.M_RawBody.Length);

                return(labeledPacket);
            });


            stopwatch.Stop();
            Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
            Console.WriteLine("=============== End of data prep ===============");


            return(packets);
        }
Пример #10
0
        private void button3_Click(object sender, EventArgs e)
        {
            PS4RemotePlayData remotePlayData = _settingManager.GetRemotePlayData();

            if (remotePlayData != null)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = @"PCAP files|*.pcap";
                DialogResult result = openFileDialog.ShowDialog(); // Show the dialog.
                if (result == DialogResult.OK)                     // Test result.
                {
                    ClearPcapOutputLogOutput();
                    string file = openFileDialog.FileName;
                    try
                    {
                        var packets              = Pcap.ReadFile(file).TrySelect(record => PacketParser.Parse(new ArraySegment <byte>(record.Data.Skip(14).ToArray())));
                        var ipPackets            = packets as IpPacket[] ?? packets.ToArray();
                        var tcpRemotePlayPackets = ipPackets.
                                                   Where(p => p != null).
                                                   Where(p => p.ProtocolType == ProtocolType.Tcp).
                                                   Where(p =>
                        {
                            var packetData         = p.PacketData.AsByteArraySegment();
                            ushort sourcePort      = p.PacketData.Array.ReadNetOrderUShort(packetData.Offset);
                            ushort destinationPort = p.PacketData.Array.ReadNetOrderUShort(2 + packetData.Offset);
                            return(sourcePort == 9295 || destinationPort == 9295);
                        }).
                                                   ToArray();

                        var udpRemotePlayPackets = ipPackets.
                                                   Where(p => p != null).
                                                   Where(p => p.ProtocolType == ProtocolType.Udp).
                                                   Select(p => p.ToUdpDatagram()).
                                                   Where(p => p.UdpDatagramHeader.SourcePort == 9296 ||
                                                         p.UdpDatagramHeader.DestinationPort == 9296).
                                                   ToArray();

                        Session session = CheckForConnectionAesKey(tcpRemotePlayPackets);
                        CheckForBigBangPayload(udpRemotePlayPackets, session);
                    }
                    catch (IOException)
                    {
                    }
                }
            }
            else
            {
                MessageBox.Show("Could not search for AES keys. No register data is available.", "No PS4 Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #11
0
        public void TestParsingKnownPackets()
        {
            PcapOfflineDevice dev = Pcap.GetPcapOfflineDevice("../../capture_files/test_stream.pcap");

            dev.Open();

            Packet p;
            int    packetIndex = 0;

            while ((p = dev.GetNextPacket()) != null)
            {
                Console.WriteLine("got packet");
                switch (packetIndex)
                {
                case 0:
                    VerifyPacket0(p);
                    break;

                case 1:
                    VerifyPacket1(p);
                    break;

                case 2:
                    VerifyPacket2(p);
                    break;

                case 3:
                    VerifyPacket3(p);
                    break;

                case 4:
                    VerifyPacket4(p);
                    break;

                case 5:
                    VerifyPacket5(p);
                    break;

                default:
                    Assert.Fail("didn't expect to get to packetIndex " + packetIndex);
                    break;
                }

                packetIndex++;
            }

            dev.Close();
        }
Пример #12
0
        public static void Run(string[] args)
        {
            int       lLen        = EthernetFields_Fields.ETH_HEADER_LEN;
            const int MIN_PKT_LEN = 42;

            byte[] data  = System.Text.Encoding.ASCII.GetBytes("HELLO");
            byte[] bytes = new byte[MIN_PKT_LEN + data.Length];
            Array.Copy(data, 0, bytes, MIN_PKT_LEN, data.Length);

            List <PcapDevice> devices = Pcap.GetAllDevices();
            PcapDevice        device  = devices[2];

            UDPPacket packet = new UDPPacket(lLen, bytes);

            //Ethernet Fields
            packet.DestinationHwAddress = PhysicalAddress.Parse("001122334455");
            // NOTE: the source hw address will be filled in by the network stack or the
            //       network hardware
//          packet.SourceHwAddress = device.MacAddress;
            packet.EthernetProtocol = EthernetPacket.EtherType.IP;

            //IP Fields
            packet.DestinationAddress = System.Net.IPAddress.Parse("58.100.187.167");

            // NOTE: the source address will be filled in by the network stack based on
            //       the device used for sending
//          packet.SourceAddress = System.Net.IPAddress.Parse(device.IpAddress);
            packet.IPProtocol          = IPProtocol.IPProtocolType.UDP;
            packet.TimeToLive          = 20;
            packet.ipv4.Id             = 100;
            packet.IPVersion           = IPPacket.IPVersions.IPv4;
            packet.ipv4.IPTotalLength  = bytes.Length - lLen;
            packet.ipv4.IPHeaderLength = IPv4Fields_Fields.IP_HEADER_LEN;

            //UDP Fields
            packet.DestinationPort = 9898;
            packet.SourcePort      = 80;
            //TODO: checksum methods are disabled due to unfinished ipv4/ipv6 work
            throw new System.NotImplementedException();
//          packet.ComputeIPChecksum();
//          packet.ComputeUDPChecksum();

            device.Open();
            device.SendPacket(packet);
            device.Close();
        }
Пример #13
0
        static void Main(string[] args)
        {
            var pcap = new Pcap();

            pcap.Open(ConfigurationManager.AppSettings["Adapter"]);

            var address = IPAddress.Parse(ConfigurationManager.AppSettings["Address"]);
            var port    = UInt16.Parse(ConfigurationManager.AppSettings["Port"]);

            Packet packet = null;

            long tx = 0, rx = 0;

            while (true)
            {
                if ((packet = pcap.Next()) != null)
                {
                    var eth = new EthernetHeader(packet.Data);
                    if (eth.Protocol == (int)EthernetProtocol.IP)
                    {
                        var ip = new IPHeader(eth);
                        if (ip.Protocol == IPProtocol.Tcp)
                        {
                            var tcp = new TcpHeader(ip);
                            if (ip.SourceIp.Equals(address) && tcp.SourcePort == port)
                            {
                                rx += tcp.Length;
                            }
                            else if (ip.DestinationIp.Equals(address) && tcp.DestinationPort == port)
                            {
                                tx += tcp.Length;
                            }
                        }
                    }
                }

                if (KeyPressed())
                {
                    Console.WriteLine("{0},{1}", tx, rx);
                    tx = 0;
                    rx = 0;
                }
            }
        }
Пример #14
0
        public void PcapGetAllDevicesTest()
        {
            List <PcapDevice> devices = Pcap.GetAllDevices();

            if (devices.Count == 0)
            {
                Console.WriteLine("No pcap supported devices found, are you running" +
                                  " as a user with access to adapters (root on Linux)?");
            }
            else
            {
                Console.WriteLine("Found {0} devices", devices.Count);
            }

            foreach (PcapDevice d in devices)
            {
                Console.WriteLine(d.ToString());
            }
        }
Пример #15
0
        // This starts the capturing
        public void Start()
        {
            // DISABLED
            return;

            List <PcapDevice> devices = Pcap.GetAllDevices();

            if (devices.Count < 1)
            {
                General.Fail("No network devices connected.");
                return;
            }

            // Find the device we want to track traffic on
            foreach (PcapDevice dev in devices)
            {
                // Just pick any device that has an address
                if (dev.Addresses.Count > 0)
                {
                    trackdevice = dev;
                }
            }

            string addrstr = "";

            for (int i = 0; i < trackdevice.Addresses.Count; i++)
            {
                if (trackdevice.Addresses[i].Addr.type != SharpPcap.Containers.Sockaddr.Type.HARDWARE)
                {
                    if (addrstr.Length > 0)
                    {
                        addrstr += ", ";
                    }
                    addrstr += "'" + trackdevice.Addresses[i].Addr.ipAddress + "'";
                }
            }
            General.WriteLogLine("Tracking network on device '" + trackdevice.Description.Trim() + "' with address " + addrstr);

            // Start capturing packets
            trackdevice.Open(true, 1000);
            trackdevice.OnPacketArrival += PacketHandler;
            trackdevice.StartCapture();
        }
Пример #16
0
        public static void Main1(string[] args)
        {
            string ver = SharpPcap.Version.VersionString;

            /* Print SharpPcap version */
            Console.WriteLine("SharpPcap {0}, SendTcpSynExample.cs", ver);
            Console.WriteLine();

            /* Retrieve the device list */
            List <PcapDevice> devices = Pcap.GetAllDevices();

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

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

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.Description);
                i++;
            }

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

            PcapDevice device = devices[i];

            SendTcpSyn(device);
        }
Пример #17
0
        public override CommandResult Execute()
        {
            var datagrams = Pcap.ReadFile(PcapFile).
                            TrySelect(record =>
                                      Tx.Network.PacketParser.Parse(record.Data.Skip(14).ToArray())).
                            Where(p => p != null).
                            Where(p => p.ProtocolType == ProtocolType.Udp).
                            Select(p => p.ToUdpDatagram()).
                            Where(p => p.UdpDatagramHeader.SourcePort == Port ||
                                  p.UdpDatagramHeader.DestinationPort == Port).
                            ToArray();

            var cryptoBlob = SharedSecret.HexToBytes();

            var decryptor = new MessageAnalyzer(cryptoBlob);

            foreach (var datagram in datagrams)
            {
                var messageInfo = decryptor.ReadMessage(datagram.UdpData.ToArray());
                Console.WriteLine($"From: {datagram.UdpDatagramHeader.SourcePort}, To: {datagram.UdpDatagramHeader.DestinationPort}");
                Console.WriteLine($"Message Type: {messageInfo.MessageType}");
                Console.WriteLine($"Request Ack: {messageInfo.RequestAcknowledge}");
                Console.WriteLine($"Version: {messageInfo.Version}");
                Console.WriteLine($"ChannelId: {messageInfo.ChannelId}");

                if (!String.IsNullOrEmpty(messageInfo.Json))
                {
                    Console.WriteLine($"Json: {messageInfo.Json}");
                }
                else
                {
                    Console.WriteLine($"Binary: {messageInfo.Data.ToHex()}");
                }

                Console.WriteLine();
            }

            return(CommandResult.Success);
        }
Пример #18
0
        public virtual void Checksum()
        {
            PcapOfflineDevice dev = Pcap.GetPcapOfflineDevice("../../capture_files/tcp.pcap");

            dev.Open();

            Packet p;

            p = dev.GetNextPacket();

            Assert.IsNotNull(p);

            Console.WriteLine(p.GetType());
            Assert.IsTrue(p is TCPPacket);

            TCPPacket t = (TCPPacket)p;

            Console.WriteLine("Checksum: " + t.Checksum.ToString("X"));
            Assert.IsTrue(t.ValidChecksum);

            dev.Close();
        }
Пример #19
0
        public void TCPChecksumIPv6()
        {
            PcapOfflineDevice dev = Pcap.GetPcapOfflineDevice("../../capture_files/ipv6_http.pcap");

            dev.Open();

            Packet p;

            // checksums from wireshark of the capture file
            int[] expectedChecksum = { 0x41a2,
                                       0x4201,
                                       0x5728,
                                       0xf448,
                                       0xee07,
                                       0x939c,
                                       0x63e4,
                                       0x4590,
                                       0x3725,
                                       0x3723 };

            int packetIndex = 0;

            while ((p = dev.GetNextPacket()) != null)
            {
                Assert.IsTrue(p is TCPPacket);
                TCPPacket t = (TCPPacket)p;
                Assert.IsTrue(t.ValidChecksum);

                // compare the computed checksum to the expected one
                Assert.AreEqual(expectedChecksum[packetIndex],
                                t.ComputeTCPChecksum());

                packetIndex++;
            }

            dev.Close();
        }
Пример #20
0
        /// <summary>
        /// Resolves the MAC address of the specified IP address
        /// </summary>
        /// <param name="destIP">The IP address to resolve</param>
        /// <param name="deviceName">The local network device name on which to send the ARP request</param>
        /// <returns>The MAC address that matches to the given IP address</returns>
        public PhysicalAddress Resolve(System.Net.IPAddress destIP, string deviceName)
        {
            PhysicalAddress localMAC = LocalMAC;

            System.Net.IPAddress localIP = LocalIP;
            //NetworkDevice device = new NetworkDevice(DeviceName);
            PcapDevice device = Pcap.GetPcapDevice(DeviceName);

            //FIXME: PcapDevices don't have IpAddress
            //       These were present under Windows specific network adapters
            //       and may be present in pcap in the future with pcap-ng
            // if no local ip address is specified use the one from the
            // local device
#if false
            if (localIP == null)
            {
                localIP = device.IpAddress;
            }
#endif

            // if no local mac address is specified use the one from the device
            if (LocalMAC == null)
            {
                localMAC = device.Interface.MacAddress;
            }

            //Build a new ARP request packet
            ARPPacket request = BuildRequest(destIP, localMAC, localIP);

            //create a "tcpdump" filter for allowing only arp replies to be read
            String arpFilter = "arp and ether dst " + localMAC.ToString();

            //open the device with 20ms timeout
            device.Open(true, 20);
            //set the filter
            device.SetFilter(arpFilter);
            //inject the packet to the wire
            device.SendPacket(request);

            ARPPacket reply;

            while (true)
            {
                //read the next packet from the network
                reply = (ARPPacket)device.GetNextPacket();
                if (reply == null)
                {
                    continue;
                }

                //if this is the reply we're looking for, stop
                if (reply.ARPSenderProtoAddress.Equals(destIP))
                {
                    break;
                }
            }
            //free the device
            device.Close();
            //return the resolved MAC address
            return(reply.ARPSenderHwAddress);
        }
Пример #21
0
        private IEnumerable <SummaryPacketData> PrepareSummaryData(string[] packetFiles, int[] includedPorts, string[] maliciousIps, int windowSize = 5)
        {
            Stopwatch stopwatch = new Stopwatch();

            Console.WriteLine("=============== Preparing Summary Window Packet Data ===============");
            Console.WriteLine();
            Console.WriteLine($"Start data prep using {packetFiles.Length} packet files, {includedPorts.Length} included ports, {maliciousIps?.Length ?? 0} malicious Ips and window size of {windowSize} seconds.");
            Console.WriteLine($"Files Being Processed:");

            foreach (var file in packetFiles)
            {
                Console.WriteLine($"\t{file}");
            }

            stopwatch.Start();

            var ipv4Packets = packetFiles
                              .SelectMany(x => Pcap.FromFile(x).Packets)
                              .Where(x => x.Body is EthernetFrame && ((EthernetFrame)x.Body).EtherType == EthernetFrame.EtherTypeEnum.Ipv4)
                              .Select(x => (TimeStamp: x.TsSec, Packet: ((Ipv4Packet)((EthernetFrame)x.Body).Body)))
                              .ToArray();

            Console.WriteLine($"Done Extracting Packets for cap files. Found {ipv4Packets.Length} IPv4 packets");

            var dataTimeSpan = (Min : ipv4Packets.Select(x => x.TimeStamp).Min(), Max : ipv4Packets.Select(x => x.TimeStamp).Max());
            var totalWindows = Math.Ceiling((float)((dataTimeSpan.Max - dataTimeSpan.Min) / windowSize));

            Console.WriteLine($"Date time range for packets is {dataTimeSpan.Min} - {dataTimeSpan.Max} ({totalWindows} total window chunks)");

            var uniqueIps = ipv4Packets
                            .SelectMany(x => new[] { x.Packet.SrcIpAddrStr, x.Packet.DstIpAddrStr })
                            .Distinct();

            Console.WriteLine($"{uniqueIps.Count()} unique IP's found in the data. Starting packet summarization");

            var data = ipv4Packets
                       .GroupBy((x => (x.TimeStamp - dataTimeSpan.Min - ((x.TimeStamp - dataTimeSpan.Min) % windowSize)) / windowSize))
                       .AsParallel()
                       .SelectMany(window =>
                                   window
                                   .SelectMany(x => new[] { x.Packet.SrcIpAddrStr, x.Packet.DstIpAddrStr })
                                   .Distinct()
                                   .AsParallel()
                                   .Select(ip =>
            {
                var packetData = window.Where(x => x.Packet.DstIpAddrStr == ip || x.Packet.SrcIpAddrStr == ip);
                var portData   = includedPorts.SelectMany(x =>
                {
                    var portPackets = packetData.Where(y => Convert.ToInt32(y.Packet.Protocol) == x);

                    return(portPackets.Any() ? new[]
                    {
                        (float)x,
                        ((float)portPackets.Average(p => p.Packet.TotalLength)),
                        (float)portPackets.Where(p => p.Packet.DstIpAddrStr == ip).Count(),
                        (float)portPackets.Where(p => p.Packet.SrcIpAddrStr == ip).Count()
                    } : new[] { 0.0f, 0.0f, 0.0f, 0.0f });
                }).ToArray();

                return((packetData.Count() == 0 || portData.Sum() == 0) ? null : new SummaryPacketData()
                {
                    WindowSize = windowSize,
                    Ip = ip,
                    IsMalicious = maliciousIps != null ? maliciousIps.Contains(ip) : false,
                    PortData = portData
                });
            })
                                   )
                       .Where(x => x != null)
                       .ToArray();

            if (maliciousIps != null)
            {
                var malIps = data.Where(x => x.IsMalicious).Count();
                Console.WriteLine($"Data summarization done, Labels found. {malIps} packet windows out of {data.Count()} labels as malicious.");
            }

            stopwatch.Stop();
            Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
            Console.WriteLine("=============== End of data prep ===============");

            return(data);
        }
Пример #22
0
 private void FillComboBoxDevices()
 {
     comboBoxDevices.DataSource    = Pcap.GetAllDevices();
     comboBoxDevices.DisplayMember = "Description";
     comboBoxDevices.SelectedIndex = -1;
 }
Пример #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PacketCapture"/> class.
 /// </summary>
 public PacketCapture()
 {
     TraceFactory.Logger.Info("New instance created");
     _networkPackets = new Pcap();
 }
Пример #24
0
        /// <summary>
        /// Resolves the MAC address of the specified IP address
        /// </summary>
        /// <param name="destIP">The IP address to resolve</param>
        /// <param name="deviceName">The local network device name on which to send the ARP request</param>
        /// <returns>The MAC address that matches to the given IP address</returns>
        public PhysicalAddress Resolve(System.Net.IPAddress destIP, string deviceName)
        {
            PhysicalAddress localMAC = LocalMAC;

            System.Net.IPAddress localIP = LocalIP;
            //NetworkDevice device = new NetworkDevice(DeviceName);
            PcapDevice device = Pcap.GetPcapDevice(DeviceName);

            //FIXME: PcapDevices don't have IpAddress
            //       These were present under Windows specific network adapters
            //       and may be present in pcap in the future with pcap-ng
            // if no local ip address is specified use the one from the
            // local device
#if false
            if (localIP == null)
            {
                localIP = device.IpAddress;
            }
#endif

            // if no local mac address is specified use the one from the device
            if (LocalMAC == null)
            {
                localMAC = device.Interface.MacAddress;
            }

            //Build a new ARP request packet
            ARPPacket request = BuildRequest(destIP, localMAC, localIP);

            //create a "tcpdump" filter for allowing only arp replies to be read
            //String arpFilter = "arp and ether dst 00:1E:33:A6:FA:52";
            String arpFilter = "arp and ether dst ";
            byte[] mac       = localMAC.GetAddressBytes();
            for (int i = 0; i < mac.Length; i++)
            {
                // Display the physical address in hexadecimal.
                arpFilter += mac[i].ToString("X2");
                // Insert a hyphen after each byte, unless we are at the end of the
                // address.
                if (i != mac.Length - 1)
                {
                    arpFilter += ":";
                }
            }
            // arpFilter += mac;


            //open the device with 20ms timeout
            device.Open(true, 20);
            //set the filter
            device.SetFilter(arpFilter);
            //inject the packet to the wire
            device.SendPacket(request);

            ARPPacket reply;

            while (true)
            {
                //read the next packet from the network
                reply = (ARPPacket)device.GetNextPacket();
                if (reply == null)
                {
                    continue;
                }

                //if this is the reply we're looking for, stop
                if (reply.ARPSenderProtoAddress.Equals(destIP))
                {
                    break;
                }
            }
            //free the device
            device.Close();
            //return the resolved MAC address
            return(reply.ARPSenderHwAddress);
        }