示例#1
0
 public static void GetReady()
 {
     try
     {
         CaptureDeviceList capturedevicelist = CaptureDeviceList.Instance;
         ICaptureDevice    capturedevice;
         capturedevicelist.Refresh();
         capturedevice = (from devicex in capturedevicelist where ((SharpPcap.WinPcap.WinPcapDevice)devicex).Interface.FriendlyName == NetStalker.Properties.Settings.Default.friendlyname select devicex).ToList()[0];
         Properties.Settings.Default.AdapterName = capturedevice.Name;
         Properties.Settings.Default.Save();
     }
     catch (Exception)
     {
     }
 }
示例#2
0
        public void GetReady()
        {
            if (!CaptureDeviceConfigured)
            {
                metroTextBox2.BeginInvoke(new Action(() =>
                {
                    metroTextBox2.Text += "Preparing network adapter..." + Environment.NewLine;
                }));

                CaptureDeviceList capturedevicelist = CaptureDeviceList.Instance;
                capturedevicelist.Refresh();
                capturedevice           = CaptureDeviceList.New()[NetStalker.Properties.Settings.Default.AdapterName];
                CaptureDeviceConfigured = true;

                metroTextBox2.BeginInvoke(new Action(() =>
                {
                    metroTextBox2.Text += "Ready" + Environment.NewLine;
                }));
            }
        }
示例#3
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
        }
示例#4
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
        }
示例#5
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
        }