Exemple #1
0
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = comboBox1.SelectedIndex;

            dev = devices[index];
            this.propertyGrid1.SelectedObject = (dev as NetworkDevice);
        }
Exemple #2
0
        /// <summary>
        /// 使用函数构造UDP数据包
        /// </summary>
        /// <param name="device"></param>
        /// <param name="dst_mac"></param>
        /// <param name="dst_ip"></param>
        /// <param name="src_port"></param>
        /// <param name="dst_port"></param>
        /// <param name="send_data"></param>
        /// <returns></returns>
        private byte[] GenUDPPacket(PcapDevice device, PhysicalAddress dst_mac, IPAddress dst_ip, int src_port,
                                    int dst_port, string send_data)
        {
            // 构造UDP部分数据报
            UdpPacket udp_pkg = new UdpPacket((ushort)src_port, (ushort)dst_port);

            udp_pkg.PayloadData = strToToHexByte(send_data);
            udp_pkg.UpdateCalculatedValues();
            // 构造IP部分数据报
            IPv4Packet ip_pkg = new IPv4Packet(device.Interface.Addresses[1].Addr.ipAddress, dst_ip);

            ip_pkg.Protocol    = IPProtocolType.UDP;
            ip_pkg.Version     = IpVersion.IPv4;
            ip_pkg.PayloadData = udp_pkg.Bytes;
            ip_pkg.TimeToLive  = 10;
            ip_pkg.UpdateCalculatedValues();
            ip_pkg.UpdateIPChecksum();
            // 构造以太网帧
            EthernetPacket net_pkg = new EthernetPacket(device.MacAddress, dst_mac, EthernetPacketType.IpV4);

            net_pkg.Type        = EthernetPacketType.IpV4;
            net_pkg.PayloadData = ip_pkg.Bytes;
            net_pkg.UpdateCalculatedValues();

            return(net_pkg.Bytes);
        }
Exemple #3
0
 public void SetDevice(PcapDevice dev)
 {
     lock (_lock)
     {
         _device = dev;
     }
 }
Exemple #4
0
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var index = this.comboBox1.SelectedIndex;

            this.dev = this.devices[index];
            this.propertyGrid1.SelectedObject = this.dev as NetworkDevice;
        }
Exemple #5
0
        public static IPAddressInfo GetIPAddressInfo(PcapDevice device)
        {
            PcapAddress pcap_address = null;

            pcap_address = device.Interface.Addresses
                           .Where(a => a.Addr.type == Sockaddr.AddressTypes.AF_INET_AF_INET6 &&
                                  a.Addr.ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                           .FirstOrDefault();

            if (pcap_address == null)
            {
                throw new InvalidOperationException("IP address not found");
            }

            IPAddressInfo ipaddressinfo = new IPAddressInfo
            {
                IPAddress = pcap_address.Addr.ipAddress,
                Mask      = pcap_address.Netmask.ipAddress,
                Gateway   = device.Interface.GatewayAddresses?.FirstOrDefault()
            };

            ipaddressinfo.IPNetwork   = GetNetworkAddress(ipaddressinfo.Mask, ipaddressinfo.IPAddress);
            ipaddressinfo.IPBroadcast = GetBroadcastAddress(ipaddressinfo.Mask, ipaddressinfo.IPAddress);

            return(ipaddressinfo);
        }
Exemple #6
0
 public void StopCapture()
 {
     lock (_lock)
     {
         if (!IsCapturing)
         {
             return;
         }
         //if device exists and opened - close it
         if (_device != null && _device.PcapOpened)
         {
             _device.PcapClose();
         }
         IsCapturing = false;
         _device     = null;
         DeviceName  = null;
         try
         {
             _runningThread.Abort();
         }
         finally
         {
             _runningThread = null;
         }
     }
 }
Exemple #7
0
        private void MainForm_Load(object pSender, EventArgs pArgs)
        {
            if (new SetupForm().ShowDialog(this) != DialogResult.OK)
            {
                Close(); return;
            }
            foreach (PcapDevice device in new PcapDeviceList())
            {
                if (device.Interface.FriendlyName == Config.Instance.Interface)
                {
                    mDevice = device;
                    break;
                }
            }
            mDevice.Open(true, 1);
            mDevice.SetFilter(string.Format("tcp portrange {0}-{1}", Config.Instance.LowPort, Config.Instance.HighPort));
            mTimer.Enabled = true;

            mSearchForm.Show(mDockPanel);
            mDataForm.Show(mDockPanel);
            mStructureForm.Show(mDockPanel);
            mPropertyForm.Show(mDockPanel);
            DockPane rightPane1 = new DockPane(mStructureForm, DockState.DockRight, true);
            DockPane rightPane2 = new DockPane(mPropertyForm, DockState.DockRight, true);

            rightPane1.Show();
            rightPane2.Show();
        }
Exemple #8
0
 private void button1_Click(object sender, EventArgs e)
 {
     textBox4.Clear();
     button1.Enabled = false;
     try
     {
         _scannerType = comboBox1.SelectedItem.ToString();
         _scanMethod  = comboBox2.SelectedItem.ToString();
         portFrom     = Convert.ToInt32(textBox1.Text);
         if (textBox2.Enabled)
         {
             portTo = Convert.ToInt32(textBox2.Text);
         }
         dev = (PcapDevice)comboBox3.SelectedItem;
         //Matching selected interface with .NET's facilities in order to get gateway's ip address
         //that is a property of the network interface of interest.
         foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces())
         {
             if (dev.Interface.Name.Contains(f.Id))
             {
                 gateway = f.GetIPProperties().GatewayAddresses[0].Address;
                 break;
             }
         }
         backgroundWorker1.RunWorkerAsync();
     }
     catch (Exception ex)
     {
         textBox4.Text   = "You have to insert all appropriate parameters.\n";
         textBox4.Text   = ex.Message;
         button1.Enabled = true;
     }
 }
Exemple #9
0
        private void mFileCaptureMenu_Click(object pSender, EventArgs pArgs)
        {
            if (mCaptureDevice != null)
            {
                mCaptureDevice.Close();
                mCaptureDevice = null;
                return;
            }
            SetupForm frmSetup = new SetupForm();

            if (frmSetup.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }

            foreach (PcapDevice device in new PcapDeviceList())
            {
                if (device.Interface.FriendlyName == Config.Instance.Interface)
                {
                    mCaptureDevice = device;
                    break;
                }
            }
            mCaptureDevice.Open(true, 1);
            mCaptureDevice.SetFilter(string.Format("tcp portrange {0}-{1}", Config.Instance.LowPort, Config.Instance.HighPort));
        }
        public ChooseDeviceForm(PcapDevice device)
        {
            InitializeComponent();

            nics = NetworkInterface.GetAllNetworkInterfaces();

            FillComboBoxDevices();

            comboBoxDevices.SelectedIndexChanged += new EventHandler(comboBoxDevices_SelectedIndexChanged);

            if (comboBoxDevices.Items.Count > 0)
            {
                comboBoxDevices.SelectedItem = device;

                if (device != null)
                {
                    buttonStart.Enabled = !device.Started;
                    buttonStop.Enabled  = device.Started;
                }
                else
                {
                    buttonStart.Enabled = false;
                    buttonStop.Enabled  = false;
                }
            }
            else
            {
                buttonStart.Enabled = false;
                buttonStop.Enabled  = false;
            }
        }
Exemple #11
0
        public PcapDevice GetActualDevice(string interfaceFriendlyName)
        {
            List <PcapDevice> allDevices = GetCurrentDevices();

            PcapDevice result = allDevices.FirstOrDefault(newDevice => newDevice.Interface.FriendlyName == interfaceFriendlyName);

            return(result);
        }
Exemple #12
0
        private void StopCapture(object state)
        {
            PcapDevice dev = (PcapDevice)state;

            dev.PcapStopCapture();
            dev.PcapClose();
            dev.PcapDumpFlush();
            dev.PcapDumpClose();
        }
        public void SwitchDevice(PcapDevice device)
        {
            if (IsActive)
            {
                Stop();
            }

            _device = device;
        }
Exemple #14
0
        public void FilterMethods()
        {
            using var device = TestHelper.GetPcapDevice();
            device.Open();

            var filterExpression = "arp";
            var mask             = (uint)0;
            var result           = PcapDevice.CompileFilter(device.PcapHandle, filterExpression, mask, out IntPtr bpfProgram, out string errorString);

            Assert.IsTrue(result);

            var arp           = new ARP(device);
            var destinationIP = new System.Net.IPAddress(new byte[] { 8, 8, 8, 8 });

            // Note: We don't care about the success or failure here
            arp.Resolve(destinationIP);

            // retrieve some packets, looking for the arp
            var header        = IntPtr.Zero;
            var data          = IntPtr.Zero;
            var foundBpfMatch = false;
            var packetsToTry  = 10;
            var sw            = System.Diagnostics.Stopwatch.StartNew();

            while (packetsToTry > 0)
            {
                if (sw.ElapsedMilliseconds > 2000)
                {
                    break;
                }

                var retval = device.GetNextPacketPointers(ref header, ref data);

                if (retval == 1)
                {
                    packetsToTry--;

                    Assert.AreNotEqual(IntPtr.Zero, header);
                    Assert.AreNotEqual(IntPtr.Zero, data);

                    // and test it against the bpf filter to confirm an exception is not thrown
                    Assert.DoesNotThrow(() =>
                    {
                        // we expect a match as we are sending an arp packet
                        if (PcapDevice.RunBpfProgram(bpfProgram, header, data))
                        {
                            foundBpfMatch = true;
                        }
                    }
                                        );
                }
            }

            Assert.IsTrue(foundBpfMatch);

            PcapDevice.FreeBpfProgram(bpfProgram);
        }
Exemple #15
0
        public void TestFilters()
        {
            // test a known failing filter
            string errorString;

            Assert.IsFalse(PcapDevice.CheckFilter("some bogus filter", out errorString));

            // test a known working filter
            Assert.IsTrue(PcapDevice.CheckFilter("port 23", out errorString));
        }
Exemple #16
0
 // Disposer
 public void Dispose()
 {
     if (trackdevice != null)
     {
         // Stop capturing packets
         try { trackdevice.StopCapture(); } catch (Exception) { };
         try { trackdevice.Close(); } catch (Exception) { };
         trackdevice = null;
     }
 }
Exemple #17
0
        private void Start()
        {
            PcapDeviceList _PcapDeviceList = SharpPcap.GetAllDevices();
            PcapDevice     _PcapDevice     = _PcapDeviceList[0];

            _PcapDevice.PcapOnPacketArrival += new SharpPcap.PacketArrivalEvent(_PcapDevice_PcapOnPacketArrival);
            _PcapDevice.PcapOpen(false);
            _PcapDevice.PcapSetFilter("tcp and ip");
            _PcapDevice.PcapCapture(-1);
        }
Exemple #18
0
 private void mFileImportMenu_Click(object pSender, EventArgs pArgs)
 {
     if (mImportDialog.ShowDialog(this) != DialogResult.OK)
     {
         return;
     }
     device = new CaptureFileReaderDevice(mImportDialog.FileName);
     device.Open();
     new Thread(ParseImportedFile).Start();
 }
        private void buttonInject_Click(object sender, EventArgs e)
        {
            bool isEthernetHeaderCorrect =
                ethernetHeaderUserControl.ValidateUserInput();
            bool isIPv4HeaderCorrect =
                iPv4HeaderUserControl.ValidateUserInput();
            bool isTcpHeaderCorrect =
                tcpHeaderUserControl.ValidateUserInput();
            bool isDeviceChosen =
                chooseDeviceUserControl.ValidateChosenDevice();

            if (!isEthernetHeaderCorrect ||
                !isIPv4HeaderCorrect ||
                !isTcpHeaderCorrect ||
                !isDeviceChosen)
            {
                return;
            }

            EthernetPacket ethernetHeader =
                ethernetHeaderUserControl.CreateEthernetPacket(0);

            IPv4Packet ipv4Packet =
                iPv4HeaderUserControl.CreateIPv4Packet(ethernetHeader);

            TCPPacket tcpPacket =
                tcpHeaderUserControl.CreateTcpPacket(ipv4Packet);

            PcapDevice device = chooseDeviceUserControl.Device;

            bool isDeviceOpenedInThisForm = false;

            try
            {
                if (!device.Opened)
                {
                    device.Open();
                    isDeviceOpenedInThisForm = true;
                }

                // Send the packet out the network device
                device.SendPacket(tcpPacket);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (isDeviceOpenedInThisForm)
                {
                    device.Close();
                }
            }
        }
        /// <summary>
        /// Dumps each received packet to a pcap file
        /// </summary>
        private static void device_PcapOnPacketArrival(object sender, PcapCaptureEventArgs e)
        {
            PcapDevice device = (PcapDevice)sender;

            //if device has a dump file opened
            if (device.DumpOpened)
            {
                //dump the packet to the file
                device.Dump(e.Packet);
                Console.WriteLine("Packet dumped to file.");
            }
        }
Exemple #21
0
 public bool TestDevice(PcapDevice device)
 {
     try
     {
         device.PcapOpen();
         device.PcapClose();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Exemple #22
0
        public static PhysicalAddress GetPhysicalAddress(PcapDevice device)
        {
            PhysicalAddress physicalAddress = null;

            if (device.Interface.Addresses.Count > 0)
            {
                physicalAddress = device.Interface.Addresses
                                  .Where(a => a.Addr.type == Sockaddr.AddressTypes.HARDWARE)
                                  .Select(b => b.Addr.hardwareAddress).Single();
            }

            return(physicalAddress);
        }
Exemple #23
0
        private void devicesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (ChooseDeviceForm chooseDeviceForm = new ChooseDeviceForm(device))
            {
                chooseDeviceForm.ButtonStopPressed += new EventHandler(chooseDeviceForm_ButtonStopPressed);

                if (chooseDeviceForm.ShowDialog() == DialogResult.OK)
                {
                    device = chooseDeviceForm.Device;
                    StartCapture();
                }
            }
        }
Exemple #24
0
        /// <summary>
        /// The purpose of this method is to stop the sniffer.
        /// </summary>
        public void StopSniffing()
        {
            if (!started)
            {
                throw new Exception("Not Sniffing");
            }

            if (pcapDevice != null)
            {
                pcapDevice.PcapClose();
                pcapDevice = null;
                started    = false;
            }
        }
Exemple #25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="adapter"></param>
        /// <param name="payload"></param>
        /// <returns></returns>
        private bool SendRawPacket(NetworkInterface adapter, Packet payload)
        {
            Debug.WriteLine("Sending RAW packet", EventLogEntryType.Information);

            PcapDevice device = (PcapDevice)CaptureDeviceList.Instance.Where(x => x.MacAddress.Equals(adapter.GetPhysicalAddress())).First();

            if (device.Opened)
            {
                device.SendPacket(payload);
                return(true);
            }

            return(false);
        }
Exemple #26
0
        private string GetStatistics(PcapDevice device)
        {
            StringBuilder statBuilder = new StringBuilder();

            statBuilder.Append("Pcap Statistics\n");
            statBuilder.Append("=====================================\n");
            statBuilder.AppendFormat(" Received Packets .............. : {0}\n",
                                     device.Statistics().ReceivedPackets);
            statBuilder.AppendFormat(" Dropped Packets ............... : {0}\n",
                                     device.Statistics().DroppedPackets);
            statBuilder.AppendFormat(" Interface Dropped Packets ..... : {0}\n",
                                     device.Statistics().InterfaceDroppedPackets);

            return(statBuilder.ToString());
        }
        private void buttonInject_Click(object sender, EventArgs e)
        {
            bool isEthernetHeaderCorrect =
                ethernetHeaderUserControl.ValidateUserInput();
            bool isPacketLengthValid = ValidatePacketLength();
            bool isDeviceChosen      =
                chooseDeviceUserControl.ValidateChosenDevice();

            if (!isEthernetHeaderCorrect ||
                !isPacketLengthValid ||
                !isDeviceChosen)
            {
                return;
            }

            int payloadLength = packetLength - EthernetFields_Fields.ETH_HEADER_LEN;

            // Create an Ethernet packet.
            EthernetPacket ethernetPacket =
                ethernetHeaderUserControl.CreateEthernetPacket(payloadLength);

            PcapDevice device = chooseDeviceUserControl.Device;

            bool isDeviceOpenedInThisForm = false;

            try
            {
                if (!device.Opened)
                {
                    device.Open();
                    isDeviceOpenedInThisForm = true;
                }

                // Send the packet out the network device
                device.SendPacket(ethernetPacket);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (isDeviceOpenedInThisForm)
                {
                    device.Close();
                }
            }
        }
Exemple #28
0
        /// <summary>
        /// Stellt eine Klasse da die das Sniffen von Packets regelt
        /// </summary>
        /// <param name="port">Der Port auf den der TCPStreamAssembler horchen soll</param>
        public L2NetSniffer(PcapDevice device, int dst_port)
        {
            this.dst_port = dst_port;
            this.device   = device;

            /*
             * (((ip.src == 192.168.100.150) && (tcp.dstport == 7777) ) || ((ip.src == 78.46.33.43) && (tcp.dstport == 52784)))
             */
            this.tcpDumpFilter = "port " + dst_port;

            this.clientStr = new L2NetStream();
            this.serverStr = new L2NetStream();
            // TODO: wenn keine devices gefunden wurden, Meldung

            this.Init();
        }
Exemple #29
0
        private void StopCapture(object state)
        {
            PcapDevice device = (PcapDevice)state;

            device.StopCaptureTimeout = new TimeSpan(0, 0, 0, 0, 500);
            try
            {
                device.StopCapture();
            }
            catch
            {
                Log.Warn("Terminals needed more than 500 milliseconds to abort the PCap thread.");
            }

            device.Close();
        }
Exemple #30
0
        private static Dictionary <ComboBoxItem, ICaptureDevice> GetDevicesList()
        {
            var devices    = CaptureDeviceList.Instance;
            var dictionary = new Dictionary <ComboBoxItem, ICaptureDevice>();

            foreach (var device in devices)
            {
                PcapDevice dev  = (PcapDevice)device;
                var        item = new ComboBoxItem
                {
                    Content = dev.Interface.FriendlyName
                };
                dictionary.Add(item, device);
            }
            return(dictionary);
        }
Exemple #31
0
		public void Initialize()
		{
			pcapDevice = null;
			started = false;

			/* Retrieve the device list */
			PcapDeviceList devices = SharpPcap.SharpPcap.GetAllDevices();

			if( devices.Count < 1 )
			{
				return;
			}

			/* Scan the list printing every entry */
			foreach( PcapDevice dev in devices )
			{
				if( dev.PcapIpAddress.Equals( ipAddress ) )
				{
					pcapDevice = dev;
					break;
				}
			}
		}
Exemple #32
0
 private void mFileImportMenu_Click(object pSender, EventArgs pArgs)
 {
     if (mImportDialog.ShowDialog(this) != DialogResult.OK) return;
     device = new CaptureFileReaderDevice(mImportDialog.FileName);
     device.Open();
     new Thread(ParseImportedFile).Start();
 }
Exemple #33
0
        private void MainForm_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (var file in files)
            {
                if (!System.IO.File.Exists(file)) continue;

                switch (System.IO.Path.GetExtension(file))
                {
                    case ".msb":
                        {
                            SessionForm session = NewSession();
                            session.OpenReadOnly(file);
                            session.Show(mDockPanel, DockState.Document);
                            mSearchForm.RefreshOpcodes(false);
                            break;
                        }
                    case ".pcap":
                        {
                            device = new CaptureFileReaderDevice(file);
                            device.Open();
                            ParseImportedFile();
                            break;
                        }
                }
            }
        }
Exemple #34
0
		/// <summary>
		/// The purpose of this method is to stop the sniffer.
		/// </summary>
		public void StopSniffing()
		{
			if( !started )
			{
				throw new Exception( "Not Sniffing" );
			}

			if( pcapDevice != null )
			{
				pcapDevice.PcapClose();
				pcapDevice = null;
				started = false;
			}
		}