Example #1
0
 /// <summary>
 /// Prints the time and length of each received packet
 /// </summary>
 private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
 {
     var time = e.Packet.Timeval.Date;
     var len = e.Packet.Data.Length;
     Console.WriteLine("{0}:{1}:{2},{3} Len={4}", 
         time.Hour, time.Minute, time.Second, time.Millisecond, len);
 }
Example #2
0
        /// <summary>
        /// Dumps each received packet to a pcap file
        /// </summary>
        private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {                       
            var device = (ICaptureDevice)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.");
            }
        }
Example #3
0
        /// <summary>
        /// Prints the source and dest MAC addresses of each received Ethernet frame
        /// </summary>
        private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            if(e.Packet.LinkLayerType == PacketDotNet.LinkLayers.Ethernet)
            {
                var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
                var ethernetPacket = (PacketDotNet.EthernetPacket)packet;

                Console.WriteLine("At: {0}:{1}: MAC:{2} -> MAC:{3}",
                                  e.Packet.Timeval.Date.ToString(),
                                  e.Packet.Timeval.Date.Millisecond,
                                  ethernetPacket.SourceHwAddress,
                                  ethernetPacket.DestinationHwAddress);
            }
        }
Example #4
0
        /// <summary>
        /// Prints the time, length, src ip, src port, dst ip and dst port
        /// for each TCP/IP packet received on the network
        /// </summary>
        private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {           
            var time = e.Packet.Timeval.Date;
            var len = e.Packet.Data.Length;

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

            var tcpPacket = PacketDotNet.TcpPacket.GetEncapsulated(packet);
            if(tcpPacket != null)
            {
                var ipPacket = (PacketDotNet.IpPacket)tcpPacket.ParentPacket;
                System.Net.IPAddress srcIp = ipPacket.SourceAddress;
                System.Net.IPAddress dstIp = ipPacket.DestinationAddress;
                int srcPort = tcpPacket.SourcePort;
                int dstPort = tcpPacket.DestinationPort;

                Console.WriteLine("{0}:{1}:{2},{3} Len={4} {5}:{6} -> {7}:{8}", 
                    time.Hour, time.Minute, time.Second, time.Millisecond, len,
                    srcIp, srcPort, dstIp, dstPort);
            }
        }
Example #5
0
        private static void device_OnPacketArrival(object sender, CaptureEventArgs packet)
        {
            //Increment
            numPackets++;

            //Put the packet number in the capture window
            stringPackets += "Packet Number: " + Convert.ToString(numPackets);
            stringPackets += Environment.NewLine;

            //Array to store data
            byte[] data = packet.Packet.Data;

            //Count bytes
            int byteCounter = 0;


            stringPackets += "Destination MAC Address: ";
            //Parsing the packets
            foreach (byte b in data)
            {
                if (byteCounter <= 13)
                {
                    stringPackets += b.ToString("X2") + " ";
                }
                byteCounter++;

                switch (byteCounter)
                {
                case 6: stringPackets += Environment.NewLine;
                    stringPackets     += "Source MAC Address: ";
                    break;

                case 12: stringPackets += Environment.NewLine;
                    stringPackets      += "EtherType: ";
                    break;

                case 14: if (data[12] == 8)
                    {
                        if (data[13] == 0)
                        {
                            stringPackets += "(IP)";
                            if (data[14] == 69)
                            {
                                stringPackets += " Version 4";
                            }
                        }
                        if (data[13] == 6)
                        {
                            stringPackets += "(ARP)";
                        }
                    }
                    break;

                    /** case 22: stringPackets += Environment.NewLine;
                     *   stringPackets += "Time To Live: ";
                     *   break;
                     * case 23: stringPackets += Environment.NewLine;
                     *   stringPackets += "Protocol: ";
                     *   if (data[23] == 6)
                     *   {
                     *       stringPackets += "TCP";
                     *   }
                     *   else if (data[23] == 17)
                     *   {
                     *       stringPackets += "UDP";
                     *   }
                     *   break;**/
                }
            }


            byteCounter    = 0;
            stringPackets += Environment.NewLine + Environment.NewLine + "Raw Data" + Environment.NewLine;

            //Process each byte
            foreach (byte b in data)
            {
                stringPackets += b.ToString("X2") + " ";
                byteCounter++;

                if (byteCounter == 16)
                {
                    byteCounter    = 0;
                    stringPackets += Environment.NewLine;
                }
            }
            stringPackets += Environment.NewLine;
            stringPackets += Environment.NewLine;
        }
Example #6
0
 void HandleOnPacketArrival(object sender, CaptureEventArgs e)
 {
 }
Example #7
0
        /// <summary>
        /// Prints the time and length of each received packet
        /// </summary>
        static void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            var time       = DateTime.Now;
            var len        = e.Packet.Data.Length;
            var packet     = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            var LLDPPacket = (PacketDotNet.LLDPPacket)packet.Extract(typeof(PacketDotNet.LLDPPacket));

            string[] results = new string[5]; // 0: TLVs, 1: name, 2: port, 3: description, 4: chassisID
            results[0] = "";                  // TLVs
            results[1] = "";                  // name
            results[2] = "";                  // port
            results[3] = "";                  // desciption
            results[4] = "";                  // chassisid


            if (LLDPPacket != null)
            {
                //  TLVs={ChassisID|PortID|TimeToLive|PortDescription|SystemName|SystemDescription|SystemCapabilities|ManagementAddress|OrganizationSpecific|OrganizationSpecific|EndOfLLDPDU}
                int TLVs = Convert.ToInt16(LLDPPacket.TlvCollection.Count.ToString());

                if (lldp.Program.opt_json != true)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("{0}:{1}:{2} LLDP Packet received with {5} TLVs",
                                      time.Hour, time.Minute, time.Second, time.Millisecond, len, TLVs);
                    //results[0] = TLVs.ToString();
                    Console.ForegroundColor = ConsoleColor.White;
                }

                foreach (TLV tlv in LLDPPacket.TlvCollection)
                {
                    //Console.WriteLine("Type: " + tlv.GetType().ToString()); // + "=\t" + tlv.ToString());
                    // PacketDotNet.LLDP.PortDescription

                    /*Console.WriteLine(tlv.GetType().ToString());
                     * if (tlv.GetType().Equals(typeof(OrganizationSpecific)))
                     * {
                     *  Console.ForegroundColor = ConsoleColor.Cyan;
                     *  Console.WriteLine("o: " + ((OrganizationSpecific)tlv).ToString());
                     *  Console.ForegroundColor = ConsoleColor.White;
                     * }
                     */
                    // MAC Switch
                    if (tlv.GetType().Equals(typeof(ChassisID)))
                    {
                        if (opt_json != true)
                        {
                            Console.ForegroundColor = ConsoleColor.Cyan;
                            Console.WriteLine("ChassisID: " + ((ChassisID)tlv).ToString());
                            //Console.WriteLine("ChassisID: " +  ChassisSubTypes.MACAddress.ToString());
                            Console.ForegroundColor = ConsoleColor.White;
                        }
                        results[4] = clean4json(((ChassisID)tlv).ToString());
                    }

                    /*if (tlv.GetType().Equals(typeof(PortID)))
                     * {
                     *  Console.ForegroundColor = ConsoleColor.Cyan;
                     *  Console.WriteLine("PortID: " + ((PortID)tlv).ToString());
                     *  Console.ForegroundColor = ConsoleColor.White;
                     * }*/
                    if (tlv.GetType().Equals(typeof(PortDescription)))
                    {
                        //Console.ForegroundColor = ConsoleColor.Cyan;
                        if (opt_json != true)
                        {
                            Console.WriteLine("Port: " + ((PortDescription)tlv).Description);
                        }
                        results[2] = clean4json(((PortDescription)tlv).Description.ToString().Trim());
                        //Console.ForegroundColor = ConsoleColor.White;
                    }
                    if (tlv.GetType().Equals(typeof(SystemName)))
                    {
                        if (opt_json != true)
                        {
                            Console.WriteLine("Name: " + ((SystemName)tlv).Name);
                        }
                        results[1] = clean4json(((SystemName)tlv).Name.ToString().Trim());
                    }
                    if (tlv.GetType().Equals(typeof(SystemDescription)))
                    {
                        /*
                         * Console.ForegroundColor = ConsoleColor.Gray;
                         * Console.WriteLine("Description: " + ((SystemDescription)tlv).Description);
                         * Console.ForegroundColor = ConsoleColor.White;
                         */
                        results[3] = clean4json(((SystemDescription)tlv).Description.ToString());
                    }
                    if (tlv.GetType().Equals(typeof(OrganizationSpecific)))
                    {
                        //Console.WriteLine("\tO:\t" + ((OrganizationSpecific)tlv).OrganizationDefinedSubType.ToString());
                    }
                }
                // Checking if all neccessary information is present, then quit.
                if (results[1] != "" && results[2] != "")
                {
                    if (opt_json == true)
                    {
                        Console.WriteLine("{\"name\":\"" + results[1] + "\",\"port\":\"" + results[2] + "\",\"description\":\"" + results[3] + "\",\"chassisid\":\"" + results[4] + "\"}");
                    }
                    if (opt_quit == true)
                    {
                        Environment.Exit(1);
                    }
                }
            }
        }
Example #8
0
        /// <summary>
        /// Packet arrival event handler, should store all the desired data into some global storage
        /// an array and show each arrived item info on the GUI, note we need to store incoming
        /// data to some array for further investigation
        /// </summary>
        ///
        private void Selected_device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            // Parse the packet
            if (materialCheckBox1.Checked)
            {
                captureFileWriter.Write(e.Packet);
            }
            Packet p = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);

            //p.PayloadData = e.Packet.Data;
            info = p.ToString();
            recieved_data.Add(e.Packet.Data);
            recieved_packets.Add(p);
            //recieved_packets.Add(PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data));
            type = p.GetType().ToString();
            String y = p.ToString();//get all packet data and decompose it to get src ip,dst ip and protocol type

            //Console.WriteLine(y);

            //int src_port = ((TcpPacket)p).SourcePort;
            //if (((TcpPacket)p).SourcePort == 80 || ((TcpPacket)p).DestinationPort == 80)
            //    y = y + "x";
            //Append the recieved packet object to the array

            if (p != null)
            {
                int    j     = 0;
                string h     = " ";
                int    flag1 = 0;
                int    flag2 = 0;
                int    flag3 = 0;
                int    flag4 = 0;
                int    flag5 = 0;
                //this for loop ,loop in all packet string and search for "=" char and take string after this untill it founds "," for example ("sourceAaddress=192.168.7.1,...") we want to take 192.168.7.1 only
                //j is a variable to detect position of "=" of source ip and dst ip and protocol type in packet string(y)
                //you can continue in this loop to get more informatio that will help you in form2 like mac address by adding j=1,2,3...,print y to more understand
                for (int i = 0; i < y.Length - 1; i++)
                {
                    if (y[i] == '=' | j == 4 | j == 5 | j == 7 | j == 9)
                    {
                        if (j == 4 && flag1 == 0)
                        {
                            if (y[i + 1] != ',')
                            {
                                h = h + y[i];
                            }
                            else
                            {
                                h      = h + y[i];
                                source = h;


                                h     = " ";
                                flag1 = 1;
                            }
                        }
                        else if (j == 5 && flag2 == 0)
                        {
                            if (y[i + 1] != ',')
                            {
                                h = h + y[i];
                            }
                            else
                            {
                                h           = h + y[i];
                                destination = h;


                                h     = " ";
                                flag2 = 1;
                            }
                        }
                        else if (j == 7 && flag3 == 0)
                        {
                            if (y[i + 1] != ',')
                            {
                                h = h + y[i];
                            }
                            else
                            {
                                h        = h + y[i];
                                protocol = h;

                                h     = " ";
                                flag3 = 1;
                            }
                        }
                        else if (j == 9 && flag4 == 0)
                        {
                            if (y[i + 1] != ',')
                            {
                                h = h + y[i];
                            }
                            else
                            {
                                h        = h + y[i];
                                src_port = h;

                                h     = " ";
                                flag4 = 1;
                            }
                        }
                        else if (j == 10 && flag5 == 0)
                        {
                            if (y[i + 1] != ',')
                            {
                                h = h + y[i];
                            }
                            else
                            {
                                h        = h + y[i];
                                dst_port = h;

                                h     = " ";
                                flag5 = 1;
                            }
                        }
                        else if (y[i] == '=')
                        {
                            j++;
                        }
                    }
                }
                int len = e.Packet.Data.Length;
                length = len.ToString();
                //source = y.Substring(129, 13);
                // destination = y.Substring(161, 13);
                // protocol = y.Substring(199, 6);
                //info = p.ToString();
                DateTime time = e.Packet.Timeval.Date;
                // s = String.Format("{0}:{1}:{2},{3} Len={4} {5}:{6} -> {7}:{8}",
                // time.Hour, time.Minute, time.Second, time.Millisecond, len,
                // srcIp, srcPort, dstIp, dstPort);
                Number = packet_number.ToString();
                Time   = time.Hour.ToString() + " : " + time.Minute.ToString() + " : " + time.Second.ToString() + " : " + time.Millisecond.ToString();
                packet_number++;
                //DataContainer.data = info;
                //public class its name datacontainer and has global attribute
                //data to share it between form1 and form2
                if (listView1.InvokeRequired)//add items in coloumns in listview
                {
                    listView1.Invoke((MethodInvoker) delegate()
                    {
                        ListViewItem item = new ListViewItem(Number);
                        item.SubItems.Add(Time);
                        item.SubItems.Add(source);
                        item.SubItems.Add(destination);
                        item.SubItems.Add(protocol);
                        item.SubItems.Add(length);
                        item.SubItems.Add(info);
                        if (src_port == "80" || src_port == "443" || src_port == "593")
                        {
                            item.SubItems.Add("HTTP"); item.SubItems.Add("HTTP");
                        }
                        else if (src_port == "49152 " || src_port == "53")
                        {
                            item.SubItems.Add("DNS");
                        }
                        listView1.Items.Add(item);
                    });
                }
            }
        }
Example #9
0
 private void device_OnPacketArrival(object sender, CaptureEventArgs e)
 {
     PcapPorcessContext(e.Packet);
 }
Example #10
0
        /// <summary>
        /// Prints the time, length, src ip, src port, dst ip and dst port
        /// for each TCP/IP packet received on the network
        /// </summary>
        private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            string GetDomainName()
            {
                string _domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;

                Ping ping = new Ping();

                try
                {
                    PingReply reply = ping.Send(_domain);

                    if (reply.Status == IPStatus.Success)
                    {
                        return(_domain);
                    }
                    else
                    {
                        return(reply.Status.ToString());
                    }
                }
                catch (PingException pExp)
                {
                    if (pExp.InnerException.ToString() == "No such host is known")
                    {
                        return("Network not detected!");
                    }

                    return("Ping Exception");
                }
            }

            try
            {
                var time = e.Packet.Timeval.Date;
                var len  = e.Packet.Data.Length;

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

                var tcpPacket = (PacketDotNet.TcpPacket)packet.Extract(typeof(PacketDotNet.TcpPacket));

                if (tcpPacket != null)
                {
                    var ipPacket = (PacketDotNet.IpPacket)tcpPacket.ParentPacket;
                    System.Net.IPAddress srcIp = ipPacket.SourceAddress;
                    System.Net.IPAddress dstIp = ipPacket.DestinationAddress;
                    string protocol            = ipPacket.Protocol.ToString();
                    int    srcPort             = tcpPacket.SourcePort;
                    int    dstPort             = tcpPacket.DestinationPort;



                    //IPHostEntry host;
                    //not working yet
                    //host = Dns.GetHostEntry(srcIp);

                    Console.WriteLine("{0}:{1}:{2},{3} Len={4} {5}:{6} -> {7}:{8}  protocol: {9}",
                                      time.Hour, time.Minute, time.Second, time.Millisecond, len,
                                      srcIp, srcPort, dstIp, dstPort, protocol);
                }
                var udpPacket = (PacketDotNet.UdpPacket)packet.Extract(typeof(PacketDotNet.UdpPacket));
                if (udpPacket != null)
                {
                    var    udppacket   = (PacketDotNet.IpPacket)udpPacket.ParentPacket;
                    int    des_udpport = udpPacket.DestinationPort;
                    int    src_udpport = udpPacket.SourcePort;
                    byte[] udpdata     = udpPacket.PayloadData;


                    string udpleng = udpPacket.Length.ToString();
                    Console.WriteLine("{0}:{1}:{2},{3} Len={4} sourceport: {5} -> {6}  protocol: UDP",
                                      time.Hour, time.Minute, time.Second, time.Millisecond, len,
                                      des_udpport, src_udpport);
                }
            }
            catch (Exception ex)
            {
                var st    = new StackTrace(ex, true);
                var frame = st.GetFrame(0);
                var line  = frame.GetFileLineNumber();
                Console.WriteLine(line);
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
        private void OnPacketArrival(Object sender, CaptureEventArgs captureEventArgs)
        {
            IPv4Packet ipv4Packet = (IPv4Packet)Packet.ParsePacket(LinkLayers.Ethernet, captureEventArgs.Packet.Data).PayloadPacket;

            using (BinaryReader binaryReader = new BinaryReader(new MemoryStream(ipv4Packet.Bytes)))
            {
                //This is not fully functional so we will just try
                try
                {
                    //Read the packet header
                    MW2PacketHeader packetHeader = new MW2PacketHeader(binaryReader);

                    try
                    {
                        //Read the party state header
                        if (packetHeader.packetType == "0partystate")
                        {
                            MW2PartystateHeader partystateHeader = new MW2PartystateHeader(binaryReader);

                            //Read player entries
                            while (binaryReader.BaseStream.Length > binaryReader.BaseStream.Position)
                            {
                                try
                                {
                                    MW2PartystatePlayer partystatePlayer = new MW2PartystatePlayer(binaryReader);

                                    if (partystatePlayer.externalIP == ipv4Packet.SourceAddress ||
                                        partystatePlayer.internalIP == ipv4Packet.SourceAddress)
                                    {
                                        partystatePlayer.IsHost = true;
                                    }

                                    partystatePlayers[partystatePlayer.externalIP] = partystatePlayer;
                                }
                                catch (Exception e)
                                {
#if DEBUG
                                    Program.LogGAF(packetHeader.packetType + "-player-fail-" + DateTime.Now.Ticks + ".bytes", ipv4Packet.Bytes);
                                    Program.LogGAF(packetHeader.packetType + "-player-fail-" + DateTime.Now.Ticks + ".txt", new String[] { e.Message, e.StackTrace });
#endif
                                }
                            }
                        }
#if DEBUG
                        if (packetHeader.packetType == "0partystate")
                        {
                            Program.LogGAF(packetHeader.packetType + "-good-" + DateTime.Now.Ticks + ".bytes", ipv4Packet.Bytes);
                        }
#endif
                    }
                    catch (Exception e)
                    {
#if DEBUG
                        Program.LogGAF(packetHeader.packetType + "-fail-" + DateTime.Now.Ticks + ".bytes", ipv4Packet.Bytes);
                        Program.LogGAF(packetHeader.packetType + "-fail-" + DateTime.Now.Ticks + ".txt", new String[] { e.Message, e.StackTrace });
#endif
                    }
                }
                catch (Exception e)
                {
#if DEBUG
                    Program.LogGAF("header-fail-" + DateTime.Now.Ticks + ".bytes", ipv4Packet.Bytes);
                    Program.LogGAF("header-fail-" + DateTime.Now.Ticks + ".txt", new String[] { e.Message, e.StackTrace });
#endif
                }
            }

            //Invoke the player list to asynchronously update it
            toolUI.playerList.BeginInvoke(new UpdatePlayerListDelegate(UpdatePlayerList), ipv4Packet.SourceAddress, ipv4Packet.DestinationAddress);
        }
Example #12
0
        public void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            var time = e.Packet.Timeval.Date;
            var len  = e.Packet.Data.Length;

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

            var tcpPacket = (PacketDotNet.TcpPacket)packet.Extract(typeof(PacketDotNet.TcpPacket));

            FileStream fs;

            if (tcpPacket != null)
            {
                var ipPacket = (PacketDotNet.IpPacket)tcpPacket.ParentPacket;
                System.Net.IPAddress srcIpP = ipPacket.SourceAddress;
                System.Net.IPAddress dstIpP = ipPacket.DestinationAddress;

                if (srcIpP.Equals(IPAddress.Parse(srcIP)))
                {//&&tcpPacket.DestinationPort==9100) {
                    if (isFin)
                    {
                        fileName = "pcl" + tcpPacket.AcknowledgmentNumber;
                        fileNameSet.Add(fileName);
                        isFin = false;
                    }
                    if (tcpPacket.Fin)
                    {
                        isFin = true;
                    }

                    if ((sequenceNum == -1 && tcpPacket.PayloadData.Length == 0) || (sequenceNum != -1 && tcpPacket.PayloadData.Length == 0))
                    {
                        // do nothing
                    }
                    else if (tcpPacket.PayloadData.Length > 0)
                    {
                        if (File.Exists(fileName))
                        {
                            fs = new FileStream(fileName, FileMode.Append);
                        }
                        else
                        {
                            fs = new FileStream(fileName, FileMode.Create);
                        }
                        BinaryWriter bw = new BinaryWriter(fs);

                        if (sequenceNum == -1 && tcpPacket.PayloadData.Length > 0)
                        {
                            sequenceNum  = tcpPacket.SequenceNumber;
                            sequenceNum += tcpPacket.PayloadData.Length;
                            bw.Write(tcpPacket.PayloadData);
                            label8.Text = "Status: Has Captured Files, Continuing ..";
                        }
                        else if (sequenceNum != -1 && tcpPacket.PayloadData.Length > 0)
                        {
                            if (sequenceNum == tcpPacket.SequenceNumber)
                            {
                                sequenceNum += tcpPacket.PayloadData.Length;
                                bw.Write(tcpPacket.PayloadData);
                            }
                        }
                        bw.Flush();

                        bw.Close();
                        fs.Close();
                    }
                }

                //  if (srcIp.Equals(IPAddress.Parse("192.168.37.130")) && dstIp.Equals(IPAddress.Parse("192.168.37.1"))) {
                //      device.SendPacket(ipPacket);
                //      Console.WriteLine("has send");
                //  }


                int srcPort = tcpPacket.SourcePort;
                int dstPort = tcpPacket.DestinationPort;

                // Console.WriteLine("{0}:{1}:{2},{3} Len={4} {5}:{6} -> {7}:{8}", time.Hour, time.Minute, time.Second, time.Millisecond, len, srcIpP, srcPort, dstIpP, dstPort);
            }
        }
Example #13
0
 private void BeginReceive_Callback(IAsyncResult ar)
 {
     try
     {
         var         state = (SocketState)ar.AsyncState;
         var         isIp6 = state.Socket.AddressFamily == AddressFamily.InterNetworkV6;
         SocketError errorCode;
         int         bytesReceived = state.Socket.EndReceive(ar, out errorCode);
         if (errorCode == SocketError.Success && bytesReceived > 0)
         {
             try
             {
                 var data = new byte[bytesReceived];
                 Array.Copy(state.Buffer, data, bytesReceived);
                 var            sha = new PhysicalAddress(new byte[6]);
                 var            dha = new PhysicalAddress(new byte[6]);
                 EthernetPacket ep  = null;
                 if (state.Socket.LocalEndPoint.AddressFamily == AddressFamily.InterNetwork)
                 {
                     // Create ethernet packet.
                     ep = new EthernetPacket(sha, dha, EthernetPacketType.IpV4);
                     // Add IP packet data.
                     ep.PayloadData = data;
                 }
                 if (state.Socket.LocalEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
                 {
                     // Create missing IP packet.
                     var sa = IPAddress.Any;
                     var da = IPAddress.Any;
                     var la = ((IPEndPoint)state.Socket.LocalEndPoint).Address;
                     if (IpAddresses.Contains(la))
                     {
                         sa = la;
                     }
                     var ip = new IPv6Packet(sa, da);
                     // Add TCP/UDP data
                     ip.PayloadData = data;
                     // Create ethernet packet.
                     ep = new EthernetPacket(sha, dha, EthernetPacketType.IpV6);
                     // Add IP packet data.
                     ep.PayloadData = ip.Bytes;
                 }
                 var ev = OnPacketArrival;
                 if (ev != null && ep != null)
                 {
                     var ti = new PosixTimeval();
                     // Get ethernet packet data.
                     var packet = new RawCapture(LinkLayers.Ethernet, ti, ep.Bytes);
                     var e      = new CaptureEventArgs(packet, this);
                     ev(this, e);
                 }
             }
             catch (Exception ex)
             {
                 LastException = ex;
             }
             // Analyze the bytes received...
             //ParseData(state.Buffer, bytesReceived);
         }
         if (continueMonitoring)
         {
             //Another call to BeginReceive so that we continue to receive the incoming packets.
             state.Socket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, new AsyncCallback(BeginReceive_Callback), state);
         }
     }
     catch (ObjectDisposedException)
     {
     }
     catch (Exception ex)
     {
         LastException = ex;
     }
 }
Example #14
0
 //
 //event handler when a new packet arrives.
 //
 public void packetarrive(object sender, CaptureEventArgs e)
 {
     ProcessContext(e.Packet);
 }
        private void PacketHandle(object sender, CaptureEventArgs e)
        {
            Packet packet    = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            var    udpPacket = packet.Extract <UdpPacket>();
            var    ipPacket  = packet.Extract <IPPacket>();

            if (udpPacket == null)
            {
                return;
            }

            //ILog plog = LogManager.GetLogger("Packet");
            //plog.Debug(string.Format("{0}:{1}->{2}:{3}", ipPacket.SourceAddress, udpPacket.SourcePort, ipPacket.DestinationAddress, udpPacket.DestinationPort));
            String       hexPayloadData = Convert.ToBase64String(udpPacket.PayloadData);
            Protocol16   protocol16     = new Protocol16();
            BinaryReader binaryReader   = new BinaryReader(new MemoryStream(udpPacket.PayloadData));

            try
            {
                IPAddress.NetworkToHostOrder((int)binaryReader.ReadUInt16());
                binaryReader.ReadByte();
                byte commandCount = binaryReader.ReadByte();
                IPAddress.NetworkToHostOrder(binaryReader.ReadInt32());
                IPAddress.NetworkToHostOrder(binaryReader.ReadInt32());
                int commandHeaderLength = 12;
                int signifierByteLength = 1;
                for (int commandIdx = 0; commandIdx < (int)commandCount; commandIdx++)
                {
                    try
                    {
                        byte commandType = binaryReader.ReadByte();
                        binaryReader.ReadByte();
                        binaryReader.ReadByte();
                        binaryReader.ReadByte();
                        int commandLength = IPAddress.NetworkToHostOrder(binaryReader.ReadInt32());
                        IPAddress.NetworkToHostOrder(binaryReader.ReadInt32());
                        switch (commandType)
                        {
                        case 4:
                            goto IL_1E7;

                        case 5:
                            goto IL_1CF;

                        case 6:
                            break;

                        case 7:
                            binaryReader.BaseStream.Position += 4L;
                            commandLength -= 4;
                            break;

                        default:
                            goto IL_1CF;
                        }
                        binaryReader.BaseStream.Position += (long)signifierByteLength;
                        byte         messageType     = binaryReader.ReadByte();
                        int          operationLength = commandLength - commandHeaderLength - 2;
                        StreamBuffer payload         = new StreamBuffer(binaryReader.ReadBytes(operationLength));
                        switch (messageType)
                        {
                        case 2:
                        {
                            //ILog rlog = LogManager.GetLogger("Request");
                            //rlog.Debug(hexPayloadData);
                            OperationRequest requestData = protocol16.DeserializeOperationRequest(payload);
                            Instance.OnRequest(requestData.OperationCode, requestData.Parameters);
                            break;
                        }

                        case 3:
                        {
                            //ILog relog = LogManager.GetLogger("Response");
                            //relog.Debug(hexPayloadData);
                            OperationResponse responseData = protocol16.DeserializeOperationResponse(payload);
                            Instance.OnResponse(responseData.OperationCode, responseData.ReturnCode, responseData.Parameters);
                            break;
                        }

                        case 4:
                        {
                            //ILog elog = LogManager.GetLogger("Event");
                            //elog.Debug(hexPayloadData);
                            EventData eventData = protocol16.DeserializeEventData(payload);
                            Instance.OnEvent(eventData.Code, eventData.Parameters);
                            break;
                        }

                        default:
                            //ILog olog = LogManager.GetLogger("Other");
                            //olog.Debug(hexPayloadData);
                            binaryReader.BaseStream.Position += (long)operationLength;
                            break;
                        }
                        payload.Close();
                        goto IL_1E7;
IL_1CF:
                        binaryReader.BaseStream.Position += (long)(commandLength - commandHeaderLength);
                        IL_1E7 :;
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.StackTrace);
            }
        }
Example #16
0
        /// <summary>
        /// PacketCapture
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnPacketArrival(object sender, CaptureEventArgs e)
        {
            // 0:ver(1fix), 1:Packet number, 2:username, 3, hostname, 4:command, 5:addition
            string[] splitted;
            string[] splittedName;

            int srcPort = (e.Packet.Data[34] << 8) + e.Packet.Data[35];
            int dstPort = (e.Packet.Data[36] << 8) + e.Packet.Data[37];

            if ((srcPort == 2425) && (dstPort == 2425))
            {
                //Invoke(new Action<bool>((b) => btnExit.Enabled = b),false);
                // 必要な変数を宣言する
                DateTime dtNow = DateTime.Now;

                string srcIP = string.Format("{0}.{1}.{2}.{3}",
                                             e.Packet.Data[26], e.Packet.Data[27], e.Packet.Data[28], e.Packet.Data[29]);

                string dstIP = string.Format("{0}.{1}.{2}.{3}",
                                             e.Packet.Data[30], e.Packet.Data[31], e.Packet.Data[32], e.Packet.Data[33]);

                int srcIP_host = e.Packet.Data[29];
                int dstIP_host = e.Packet.Data[33];

                string noticeNameIP = appSettings.ipAddr;

                var segment = new ArraySegment <byte>(e.Packet.Data, 42, e.Packet.Data.Length - 42);

                string stringbyte = System.Text.Encoding.GetEncoding(932).GetString((segment.ToArray()));

                splitted = stringbyte.Split(separator);

                splittedName = splitted[5].Split(separatorName);

                int command = int.Parse(splitted[4]);

                string notice          = "";
                string responseMessage = "…";
                string commandMessage  = splitted[4];
                string nameMessage     = splittedName[0];
                string sendName        = "誰か";
                bool   flg             = false;
                bool   flg2            = false;

                switch (command & 0xff)
                {
                case 0x20:
                    if (srcIP == appSettings.ipAddr)
                    {
                        notice       = string.Format("[{0}] 送信したよ", dtNow.ToLongTimeString());
                        noticeNameIP = srcIP;
                        if (localIPDic.ContainsKey(dstIP))
                        {
                            sendName = localIPDic[dstIP];
                        }
                        responseMessage = sendName + " に送るで";
                        nameMessage     = localIPDic.ContainsKey(noticeNameIP) ? localIPDic[noticeNameIP] : "誰?";
                        flg             = appSettings.sendFlg;
                    }
                    else
                    {
                        // srcIPが自分ではないから相手からの送信

                        // マルチキャスト?
                        if ((command & 0x800) != 0)
                        {
                            appConnectStatus.cast = true;
                        }
                        // 添付あり?
                        if ((command & 0x200000) != 0)
                        {
                            appConnectStatus.attach = true;
                        }
                    }

                    break;

                case 0x30:
                    if (srcIP != appSettings.ipAddr)
                    {
                        notice          = string.Format("[{0}] 開封したよ", dtNow.ToLongTimeString());
                        noticeNameIP    = srcIP;
                        responseMessage = "開けたで";
                        nameMessage     = localIPDic.ContainsKey(noticeNameIP) ? localIPDic[noticeNameIP] : "誰?";
                        flg             = appSettings.openFlg;
                    }

                    break;

                case 0x21:
                    if (srcIP == appSettings.ipAddr)
                    {
                        notice = string.Format("[{0}] 受信したよ", dtNow.ToLongTimeString());

                        if (appConnectStatus.cast)
                        {
                            notice += " [多]";
                            appConnectStatus.cast = false;
                        }

                        if (appConnectStatus.attach)
                        {
                            notice += " [添]";
                            appConnectStatus.attach = false;
                        }

                        noticeNameIP    = dstIP;
                        responseMessage = "から受け取ったで";
                        nameMessage     = localIPDic.ContainsKey(noticeNameIP) ? localIPDic[noticeNameIP] : "誰?";
                        flg             = appSettings.receiveFlg;
                    }

                    break;

                case 0x3:

                    if (!localIPDic.ContainsKey(srcIP))
                    {
                        localIPDic.Add(srcIP, nameMessage);
                    }
                    responseMessage = "おるよー";
                    flg2            = true;
                    break;

                case 0x1:
                    // 自分がブロードキャストした場合statusを初期化する
                    if (srcIP == appSettings.ipAddr)
                    {
                        localIPDic.Clear();
                    }
                    if (!localIPDic.ContainsKey(srcIP))
                    {
                        localIPDic.Add(srcIP, nameMessage);
                    }
                    responseMessage = "おるかー?";
                    flg2            = true;
                    break;

                case 0x2:

                    if (localIPDic.ContainsKey(srcIP))
                    {
                        notice       = string.Format("[{0}] 帰るよ", dtNow.ToLongTimeString());
                        noticeNameIP = srcIP;
                        nameMessage  = localIPDic.ContainsKey(noticeNameIP) ? localIPDic[noticeNameIP] : "誰?";
                        localIPDic.Remove(srcIP);

                        flg = appSettings.leaveFlg;

                        flg2 = true;
                    }
                    responseMessage = "帰るで";
                    break;

                default:
                    //responseMessage = splitted[4];
                    //commandMessage = "";
                    break;
                }

                if (flg)
                {
                    if (ssFlg)
                    {
                        tipStack.Add(string.Format("{0} : {1}", notice, nameMessage));
                    }
                    else
                    {
                        //バルーンヒントのタイトル
                        notifyIcon1.BalloonTipTitle = notice;
                        //バルーンヒントに表示するメッセージ
                        notifyIcon1.BalloonTipText = nameMessage;
                        //バルーンヒントに表示するアイコン
                        notifyIcon1.BalloonTipIcon = ToolTipIcon.None;
                        //バルーンヒントを表示する
                        //表示する時間をミリ秒で指定する
                        notifyIcon1.ShowBalloonTip(300000);
                    }
                }

                if (flg || flg2)
                {
                    Invoke(new Action <string>((msg) => txtDefault.AppendText(msg + Environment.NewLine)),
                           string.Format("[{0}] {1} < {2}",
                                         dtNow.ToLongTimeString(),
                                         nameMessage,
                                         responseMessage));
                }

                Invoke(new Action <string>((msg) => txtDetail.AppendText(msg + Environment.NewLine)),
                       string.Format("[{0}] {1} < {2} < {3}",
                                     dtNow.ToLongTimeString(),
                                     nameMessage,
                                     responseMessage,
                                     commandMessage));

                //Invoke(new Action<bool>((b) => btnExit.Enabled = b),true);
            }
        }
Example #17
0
        private void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            try
            {
                Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);

                if (packet.PayloadPacket != null)
                {
                    if (UDPfilter)
                    {
                        if ((UdpPacket)packet.Extract(typeof(UdpPacket)) != null)
                        {
                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                lbxCapturedPacketList.Items.Add(packet);
                            }));
                        }
                    }
                    else if (TCPfilter)
                    {
                        if ((TcpPacket)packet.Extract(typeof(TcpPacket)) != null)
                        {
                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                lbxCapturedPacketList.Items.Add(packet);
                            }));
                        }
                    }
                    else if (ICMPfilter)
                    {
                        if ((ICMPv4Packet)packet.Extract(typeof(ICMPv4Packet)) != null || (ICMPv6Packet)packet.Extract(typeof(ICMPv6Packet)) != null)
                        {
                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                lbxCapturedPacketList.Items.Add(packet);
                            }));
                        }
                    }
                    else if (Nofilter)
                    {
                        this.Dispatcher.Invoke((Action)(() =>
                        {
                            lbxCapturedPacketList.Items.Add(packet);
                        }));
                    }
                    else
                    {
                        this.Dispatcher.Invoke((Action)(() =>
                        {
                            lbxCapturedPacketList.Items.Add(packet);
                        }));
                    }
                }


                Console.WriteLine(packet);
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0} Exception caught.", ex);
            }
        }
Example #18
0
        private void NotifyHelper_ScreenCaptureDataBind(CaptureEventArgs e)
        {
            if (e.CaptureViewMode != CaptureViewMode.Game &&
                e.CaptureViewMode != CaptureViewMode.HP &&
                e.CaptureViewMode != CaptureViewMode.Mp)
            {
                return;
            }

            foreach (var item in _captureViews)
            {
                item.Hide();
            }
            if (e.CaptureImage == null)
            {
                return;
            }

            var capture = e.CaptureImage;

            if (e.CaptureViewMode == CaptureViewMode.Game)
            {
                canvasCaptureImage.Background = new ImageBrush(capture.ToBitmapSource());
                _bitmap = new Bitmap(capture, capture.Width, capture.Height);
            }
            else if (e.CaptureViewMode == CaptureViewMode.HP)
            {
                var processPosition = new Utils.Infrastructure.Rect();

                NativeHelper.GetWindowRect(_currentProcess.MainWindowHandle, ref processPosition);

                var roiPosition = CalculatorRoiPosition(processPosition, e.Position, e.MonitorInfo);
                if (roiPosition.Equals(_dummyRect))
                {
                    return;
                }

                _hpRoiPosition = new RoiPositionModel()
                {
                    MonitorInfo = e.MonitorInfo,
                    RoiPosition = roiPosition,
                };
                canvasCaptureHp.Background = new ImageBrush(capture.ToBitmapSource());
            }
            else if (e.CaptureViewMode == CaptureViewMode.Mp)
            {
                var processPosition = new Utils.Infrastructure.Rect();

                NativeHelper.GetWindowRect(_currentProcess.MainWindowHandle, ref processPosition);

                var roiPosition = CalculatorRoiPosition(processPosition, e.Position, e.MonitorInfo);
                if (roiPosition.Equals(_dummyRect))
                {
                    return;
                }
                _mpRoiPosition = new RoiPositionModel()
                {
                    MonitorInfo = e.MonitorInfo,
                    RoiPosition = roiPosition,
                };
                canvasCaptureMp.Background = new ImageBrush(capture.ToBitmapSource());
            }

            Application.Current.MainWindow.WindowState = WindowState.Normal;
        }
Example #19
0
 void HandleDeviceOnPacketArrival(object sender, CaptureEventArgs e)
 {
     Console.WriteLine("got packet " + e.Packet.ToString());
     capturedPackets++;
 }
Example #20
0
 public void device_PcapOnPacketArrival(object sender, CaptureEventArgs e)
 {
     lock (QueueLock) {
         PacketQueue.Add(e.Packet);
     }
 }
Example #21
0
 private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
 {
     ParsePacket(e.Packet);
 }
Example #22
0
        private static void device_OnPacketArrival(object sender, CaptureEventArgs packet)
        {
            //Increment the number of packets captured
            numPackets++;

            //Put the packet number in the capture window
            stringPackets += "Packet Number: " + Convert.ToString(numPackets);
            stringPackets += Environment.NewLine;

            //Array to store our data
            byte[] data = packet.Packet.Data;

            //Keep track of the number of bytes displayed per line
            int byteCounter = 0;


            stringPackets += "Destination MAC Address: ";
            //Parsing the packets
            foreach (byte b in data)
            {
                //Add the byte to our string (in hexidecimal)
                if (byteCounter <= 13)
                {
                    stringPackets += b.ToString("X2") + " ";
                }
                byteCounter++;

                switch (byteCounter)
                {
                case 6: stringPackets += Environment.NewLine;
                    stringPackets     += "Source MAC Address: ";
                    break;

                case 12: stringPackets += Environment.NewLine;
                    stringPackets      += "EtherType: ";
                    break;

                case 14: if (data[12] == 8)
                    {
                        if (data[13] == 0)
                        {
                            stringPackets += "(IP)";
                        }
                        if (data[13] == 6)
                        {
                            stringPackets += "(ARP)";
                        }
                    }
                    else if (data[12] == 134)
                    {
                        stringPackets += "(UDP)";
                    }
                    break;
                }
            }


            stringPackets += Environment.NewLine + Environment.NewLine;
            byteCounter    = 0;
            stringPackets += "Raw Data" + Environment.NewLine;
            //Process each byte in our captured packet
            foreach (byte b in data)
            {
                //Add the byte to our string (in hexidecimal)
                stringPackets += b.ToString("X2") + " ";
                byteCounter++;

                if (byteCounter == 16)
                {
                    byteCounter    = 0;
                    stringPackets += Environment.NewLine;
                }
            }
            stringPackets += Environment.NewLine;
            stringPackets += Environment.NewLine;
        }
Example #23
0
        private static void OnPacketArrivalDevice(object sender, CaptureEventArgs e)
        {
            if (!IsCapturing)
            {
                return;
            }
            Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            //ArrayList list = (ArrayList)MainWindow.ListViewPackets.ItemsSource;
            //MainWindow.ListViewPackets.ItemsSource
            var list = MainWindow.Packets;

            while (packet != null)
            {
                Type t = packet.GetType();
                if (t == typeof(UdpPacket))
                {
                    UdpPacket p = (UdpPacket)packet;
                    AddItem(new ArrivedPacket {
                        PacketData = p, Protocol = "UDP", Time = e.Packet.Timeval.ToString(), From = p.DestinationPort.ToString(), To = p.SourcePort.ToString()
                    });
                }
                else if (t == typeof(TcpPacket))
                {
                    TcpPacket p = (TcpPacket)packet;
                    AddItem(new ArrivedPacket {
                        PacketData = p, Protocol = "TCP", Time = e.Packet.Timeval.ToString(), From = p.DestinationPort.ToString(), To = p.SourcePort.ToString()
                    });
                }
                else if (t == typeof(ARPPacket))
                {
                    ARPPacket p = (ARPPacket)packet;
                    AddItem(new ArrivedPacket {
                        PacketData = p, Protocol = "ARP", Time = e.Packet.Timeval.ToString(), From = p.SenderProtocolAddress.ToString(), To = p.TargetProtocolAddress.ToString()
                    });
                }


                else if (t == typeof(IPv4Packet))
                {
                    IPv4Packet p = (IPv4Packet)packet;
                    AddItem(new ArrivedPacket {
                        PacketData = p, Protocol = "IPv4", Time = e.Packet.Timeval.ToString(), From = p.DestinationAddress.ToString(), To = p.SourceAddress.ToString()
                    });
                }
                else if (t == typeof(IPv6Packet))
                {
                    IPv6Packet p = (IPv6Packet)packet;
                    AddItem(new ArrivedPacket {
                        PacketData = p, Protocol = "IPv6", Time = e.Packet.Timeval.ToString(), From = p.DestinationAddress.ToString(), To = p.SourceAddress.ToString()
                    });
                }
                else if (t == typeof(EthernetPacket))
                {
                    EthernetPacket p = (EthernetPacket)packet;
                    AddItem(new ArrivedPacket {
                        PacketData = p, Protocol = "Ethernet", Time = e.Packet.Timeval.ToString(), From = p.DestinationHwAddress.ToString(), To = p.SourceHwAddress.ToString()
                    });
                }
                //else if (t == typeof(ICMPv4Packet))
                //{

                //    ICMPv4Packet p = (ICMPv4Packet)packet;
                //    AddItem(new ArrivedPacket { Protocol = "ICMPv4", Time = e.Packet.Timeval.ToString(), From = p..ToString(), To = p.SourceHwAddress.ToString() });
                //}
                //else
                //{

                //}
                packet = packet.PayloadPacket;
                /*MainWindow.mainWindow.listViewPackets.Items.Add*/;
            }

            //MainWindow.ListViewPackets.Resources.
        }
Example #24
0
        /**
         * Function which Extract Packet
         * take info (about source and destination -> ports, address(which is converted to DN))
         * and at the end of function, there is print function for print sniffed packet
         */
        void gotPacket(object sender, CaptureEventArgs e)
        {
            var time = e.Packet.Timeval.Date;
            var len  = e.Packet.Data.Length;

            var packet    = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            var tcpPacket = packet.Extract <PacketDotNet.TcpPacket>();
            var udpPacket = packet.Extract <PacketDotNet.UdpPacket>();

            countPackets++;
            if (number < countPackets)
            {
                device.Close();
                device.StopCapture();
                Environment.Exit(0);
            }

            /**
             * We detected that we got udp packet, so it execute this part of code
             * which take source and destination address / port
             * also take hostName (if exists) from function findHostName
             * and print it as a info of packet
             */

            if (udpPacket != null)
            {
                var Packet = (PacketDotNet.IPPacket)udpPacket.ParentPacket;

                var src     = Packet.SourceAddress;
                var dst     = Packet.DestinationAddress;
                var srcPort = udpPacket.SourcePort;
                var dstPort = udpPacket.DestinationPort;

                string hostnameSrc = findHostName(src.ToString());;
                string hostnameDst = findHostName(dst.ToString());;

                Console.WriteLine("{0}:{1}:{2}.{3} {4} : {5} > {6} : {7}\n",
                                  time.Hour, time.Minute, time.Second, time.Millisecond, hostnameSrc, srcPort, hostnameDst, dstPort);

                int length = len - udpPacket.PayloadData.Length; //calculate length of header data

                firstNum  = 0;
                secondNum = 0;
                thirdNum  = 0;
                fourthNum = 0;

                /**
                 * THIS PART OF CODE, SEPARATE HEADERS AND
                 * OPTIONS IN PACKET AND PRINT PRINTABLE ASCII CHARACTERS
                 * IF IS NONPRINTABLE CHAR THERE, IT WILL PRINT AS DOT
                 */
                string[] udpfile = fillSeparatedParts(0, length, udpPacket.BytesSegment);
                createAsciiChars(udpfile);
                Console.WriteLine();

                if (udpPacket.PayloadData.Length > 0)
                {
                    string[] udpfile2 = fillSeparatedParts(length, len, udpPacket.PayloadDataSegment);
                    if (udpfile2.Length > 0)
                    {
                        createAsciiChars(udpfile2);
                    }
                    Console.WriteLine();
                }
                Console.WriteLine();
            }

            /**
             * We detected that we got tcp packet, so it execute this part of code
             * which take source and destination address / port
             * also take hostName (if exists) from function findHostName
             * and print it as a info of packet
             */

            if (tcpPacket != null)
            {
                var Packet = (PacketDotNet.IPPacket)tcpPacket.ParentPacket;

                var src     = Packet.SourceAddress;
                var dst     = Packet.DestinationAddress;
                var srcPort = tcpPacket.SourcePort;
                var dstPort = tcpPacket.DestinationPort;

                string hostnameSrc = findHostName(src.ToString());
                string hostnameDst = findHostName(dst.ToString());

                Console.WriteLine("{0}:{1}:{2}.{3} {4} : {5} > {6} : {7}\n",
                                  time.Hour, time.Minute, time.Second, time.Millisecond, hostnameSrc, srcPort, hostnameDst, dstPort);

                /**
                 * THIS PART OF CODE, SEPARATE HEADERS AND
                 * OPTIONS IN PACKET AND PRINT PRINTABLE ASCII CHARACTERS
                 * IF IS NONPRINTABLE CHAR THERE, IT WILL PRINT AS DOT
                 */
                int length = len - tcpPacket.PayloadData.Length; //calculate length of header data

                firstNum  = 0;
                secondNum = 0;
                thirdNum  = 0;
                fourthNum = 0;

                string[] tcpfile = fillSeparatedParts(0, length, tcpPacket.BytesSegment);
                createAsciiChars(tcpfile);
                Console.WriteLine();

                if (tcpPacket.PayloadData.Length > 0)
                {
                    string[] tcpfile2 = fillSeparatedParts(length, len, tcpPacket.PayloadDataSegment);
                    if (tcpfile2.Length > 0)
                    {
                        createAsciiChars(tcpfile2);
                    }
                    Console.WriteLine();
                }
                Console.WriteLine();
            }
        }
Example #25
0
        public static void DeviceOnOnPacketArrival(object sender, CaptureEventArgs captureEventArgs)
        {
            int numberofplayers    = 0;
            var packet             = Packet.ParsePacket(captureEventArgs.Packet.LinkLayerType, captureEventArgs.Packet.Data);
            var eth                = (EthernetPacket)packet;
            var PacketPayloadInHex = BitConverter.ToString(eth.Bytes).Replace("-", string.Empty);
            var DestIP             = new IPAddress(long.Parse(FakeMW2SA.Utils.ReverseBytes(PacketPayloadInHex.Substring(60, 8)), System.Globalization.NumberStyles.AllowHexSpecifier)).ToString();
            var SourceIP           = new IPAddress(long.Parse(FakeMW2SA.Utils.ReverseBytes(PacketPayloadInHex.Substring(52, 8)), System.Globalization.NumberStyles.AllowHexSpecifier)).ToString();

            if (!localipaddresses.Contains(SourceIP))
            {
                FakeMW2SA.Program.Addipaddress(SourceIP);
            }

            if (PacketPayloadInHex.Contains(@"70617274797374617465")) //"partystate" - The partystate packet contains a lot of information including player name, steam ID, reported IP, and score information.
            {
                FakeMW2SA.Program.WriteOnBottomLine("partystate");    //incriment the console partystate count by one
                FakeMW2SA.Utils.SetHost(SourceIP);
                string          playerpatern = @"0{10}.{40}0{48}.{28}";
                MatchCollection matches2;
                Regex           playerregex = new Regex(playerpatern);
                matches2 = playerregex.Matches(PacketPayloadInHex);
                var IDlist = new List <string>();
                for (int ctr = 0; ctr < matches2.Count; ctr++)
                {
                    IDlist.Add(long.Parse(FakeMW2SA.Utils.ReverseBytes(matches2[ctr].Value.Substring(10, 16)), System.Globalization.NumberStyles.HexNumber).ToString());
                }
                for (int ctr = 0; ctr < matches2.Count; ctr++)
                {
                    var partystatesteamid = long.Parse(FakeMW2SA.Utils.ReverseBytes(matches2[ctr].Value.Substring(10, 16)), System.Globalization.NumberStyles.HexNumber).ToString();
                    var partystateip      = new IPAddress(long.Parse(FakeMW2SA.Utils.ReverseBytes(matches2[ctr].Value.Substring(34, 8)), System.Globalization.NumberStyles.AllowHexSpecifier)).ToString();

                    PlayerModel player;
                    //Search the list of players with a matching steam ID
                    if ((FakeMW2SA.Program.players.Find(x => x.steamid == partystatesteamid) == null))
                    {
                        //If the player isn't found, we're going to add them to the list of players, and increment the playerID variable for the next player
                        player = new PlayerModel(partystateip, partystatesteamid, false)
                        {
                            playerprimaryid = FakeMW2SA.Program.playerID
                        };
                        FakeMW2SA.Program.playerID++;
                        FakeMW2SA.Program.players.Add(player);
                    }
                    else
                    {
                        player = FakeMW2SA.Program.players.Find(x => x.steamid == partystatesteamid);
                    }
                    if ((FakeMW2SA.Program.players.Find(x => x.unknown1 == int.Parse(matches2[ctr].Value.Substring(98, 8), System.Globalization.NumberStyles.HexNumber)) == null))
                    {
                        player.partyID = FakeMW2SA.Utils.FindPartyID();
                    }
                    else
                    {
                        if (int.Parse(matches2[ctr].Value.Substring(98, 8), System.Globalization.NumberStyles.HexNumber) == 0)
                        {
                            player.partyID = FakeMW2SA.Utils.FindPartyID();
                        }
                        else
                        {
                            player.partyID = (FakeMW2SA.Program.players.Find(x => x.unknown1 == int.Parse(matches2[ctr].Value.Substring(98, 8), System.Globalization.NumberStyles.HexNumber))).partyID;
                        }
                    }
                    TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
                    int      secondsSinceEpoch = (int)t.TotalSeconds;
                    player.updated     = false;
                    player.lastupdated = Utils.GetEpochSeconds();
                    //There are two different parsing systems used here, depending on whether a mystery byte is missing. This is a sanity check to determine which one to use.
                    if (int.Parse(matches2[ctr].Value.Substring(120, 2), System.Globalization.NumberStyles.HexNumber) + 1 <= 70 &&                                         //Level must be 70 or below
                        int.Parse(matches2[ctr].Value.Substring(122, 2), System.Globalization.NumberStyles.HexNumber) + 1 <= 11 &&                                         //Presteige must be 11 or below
                        int.Parse(matches2[ctr].Value.Substring(118, 2), System.Globalization.NumberStyles.HexNumber) < 50 &&                                              //Deaths must be 50 or below
                        int.Parse((matches2[ctr].Value.Substring(116, 2) + matches2[ctr].Value.Substring(114, 2)), System.Globalization.NumberStyles.HexNumber) < 10000 && //Score must be 10,000 or below
                        int.Parse((matches2[ctr].Value.Substring(116, 2) + matches2[ctr].Value.Substring(114, 2)), System.Globalization.NumberStyles.HexNumber) % 10 == 0) //Score must be divisable by 10
                    {
                        numberofplayers += 1;
                        player.level     = int.Parse(matches2[ctr].Value.Substring(120, 2), System.Globalization.NumberStyles.HexNumber).ToString();
                        player.presteige = int.Parse(matches2[ctr].Value.Substring(122, 2), System.Globalization.NumberStyles.HexNumber).ToString();
                        player.deaths    = int.Parse(matches2[ctr].Value.Substring(118, 2), System.Globalization.NumberStyles.HexNumber);
                        player.score     = int.Parse((matches2[ctr].Value.Substring(116, 2) + matches2[ctr].Value.Substring(114, 2)), System.Globalization.NumberStyles.HexNumber);
                        player.missing   = 1;
                    }
                    else
                    {
                        numberofplayers += 1;
                        player.level     = int.Parse(matches2[ctr].Value.Substring(122, 2), System.Globalization.NumberStyles.HexNumber).ToString();
                        player.presteige = int.Parse(matches2[ctr].Value.Substring(124, 2), System.Globalization.NumberStyles.HexNumber).ToString();
                        player.deaths    = int.Parse(matches2[ctr].Value.Substring(120, 2), System.Globalization.NumberStyles.HexNumber);
                        player.score     = int.Parse((matches2[ctr].Value.Substring(118, 2) + matches2[ctr].Value.Substring(116, 2)), System.Globalization.NumberStyles.HexNumber);
                        player.missing   = 0;
                    }
                    //these two bytes are used in the party ID
                    player.unknown1 = int.Parse(matches2[ctr].Value.Substring(98, 8), System.Globalization.NumberStyles.HexNumber);
                    player.unknown2 = int.Parse(FakeMW2SA.Utils.ReverseBytes(matches2[ctr].Value.Substring(106, 8)), System.Globalization.NumberStyles.HexNumber);
                }
                FakeMW2SA.Program.WriteOnBottomLine(numberofplayers.ToString());
                //We've extracted all the player information from the packet as needed. We're going to call on some external web APIs to obtain more information.
                FakeMW2SA.Utils.CallApis();
            }

            if (PacketPayloadInHex.Contains(@"6D656D62"))//"memberjoin" We log the header IP and player name from these packets, to defeat IP spoofers.
            {
                FakeMW2SA.Program.WriteOnBottomLine("memberjoin");
                string PlayerNameInHex;
                Match  match = Regex.Match(PacketPayloadInHex, @"(?:[0-9a-fA-F][0-9a-fA-F])+?0{48}.{16}([0-9a-fA-F]+?)0000");
                while (match.Success)
                {
                    if (match.Groups[1].Value.Length % 2 != 0)
                    {
                        PlayerNameInHex = match.Groups[1].Value + "0";
                    }
                    else
                    {
                        PlayerNameInHex = match.Groups[1].Value;
                    }
                    byte[] dBytes      = FakeMW2SA.Utils.StringToByteArray(PlayerNameInHex);
                    string ASCIIresult = System.Text.Encoding.ASCII.GetString(dBytes);
                    string utf8result  = System.Text.Encoding.UTF8.GetString(dBytes);
                    match = match.NextMatch();
                    PlayerModel player;
                    player = new PlayerModel(SourceIP, "0", true)
                    {
                        playerprimaryid = FakeMW2SA.Program.playerID, personaname = utf8result
                    };
                    if ((FakeMW2SA.Program.players.Find(x => x.ip == SourceIP) == null))
                    {
                        FakeMW2SA.Program.playerID++;
                        player.partyID = FakeMW2SA.Utils.FindPartyID();
                        FakeMW2SA.Program.players.Add(player);
                    }
                }
            }
        }
Example #26
0
        public void Device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            DateTime time = e.Packet.Timeval.Date;

            time_str = (time.Hour + 1) + ":" + time.Minute + ":" + time.Second + ":" + time.Millisecond;
            length   = e.Packet.Data.Length.ToString();
            Packet   packet   = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            IpPacket ipPacket = (IpPacket)packet.Extract(typeof(IpPacket));

            if (ipPacket != null)
            {
                System.Net.IPAddress srcIp = ipPacket.SourceAddress;
                System.Net.IPAddress dstIp = ipPacket.DestinationAddress;
                protocol_type = ipPacket.Protocol.ToString();
                sourceIP      = srcIp.ToString();
                destinationIP = dstIp.ToString();

                if (!string.IsNullOrEmpty(TargetIP) && (sourceIP == TargetIP || destinationIP == TargetIP))
                {
                    packetNumber += 1;
                    capturedPackets_list.Add(packetNumber, packet);

                    Packet protocolPacket = ipPacket.PayloadPacket;

                    ListViewItem item = new ListViewItem(packetNumber.ToString());
                    item.SubItems.Add(time_str);
                    item.SubItems.Add(sourceIP);
                    item.SubItems.Add(destinationIP);
                    item.SubItems.Add(protocol_type);
                    item.SubItems.Add(length);
                    captureFileWriter.Write(e.Packet);

                    try
                    {
                        Action action = () => listView1.Items.Add(item);
                        listView1.Invoke(action);
                    }
                    catch
                    {
                        Environment.Exit(1);
                    }
                }
                else if (string.IsNullOrEmpty(TargetIP))
                {
                    packetNumber += 1;
                    capturedPackets_list.Add(packetNumber, packet);

                    Packet protocolPacket = ipPacket.PayloadPacket;

                    ListViewItem item = new ListViewItem(packetNumber.ToString());
                    item.SubItems.Add(time_str);
                    item.SubItems.Add(sourceIP);
                    item.SubItems.Add(destinationIP);
                    item.SubItems.Add(protocol_type);
                    item.SubItems.Add(length);
                    captureFileWriter.Write(e.Packet);

                    try
                    {
                        Action action = () => listView1.Items.Add(item);
                        listView1.Invoke(action);
                    }
                    catch
                    {
                        Environment.Exit(1);
                    }
                }
            }
        }
Example #27
0
        private static void Device_OnPacketArrivalRecv(object sender, CaptureEventArgs e)
        {
            var len = e.Packet.Data.Length;

            ProcInfo.NetRecvBytes += len;
        }
Example #28
0
        private static void device_OnPacketArrival(object sender, CaptureEventArgs packet)
        {
            var time = packet.Packet.Timeval.Date;
            var len  = packet.Packet.Data.Length;

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

            //Gathering the TCP packet data
            var tcpPacket = PacketDotNet.TcpPacket.GetEncapsulated(packetx);

            if (tcpPacket != null)
            {
                var ipPacket = (PacketDotNet.IpPacket)tcpPacket.ParentPacket;
                System.Net.IPAddress srcIp = ipPacket.SourceAddress;
                System.Net.IPAddress dstIp = ipPacket.DestinationAddress;
                int srcPort = tcpPacket.SourcePort;
                int dstPort = tcpPacket.DestinationPort;

                //Print source and destination port
                stringInfo += "PACKET NUMBER: " + numPackets + " | " + "The TCP source port is: " + Convert.ToString(srcPort) + " and the TCP destination port is : " + Convert.ToString(dstPort);
                stringInfo += Environment.NewLine;

                //Print destination IP address
                stringInfo += "PACKET NUMBER: " + numPackets + " | " + "The TCP destination address is: " + Convert.ToString(dstIp);
                stringInfo += Environment.NewLine;

                //Print length of packet
                stringInfo += "PACKET NUMBER: " + numPackets + " | " + "The length of the packet is: " + len;
                stringInfo += Environment.NewLine;

                //Limit the number of location requests since the API only allows for 150 requests/min
                if (numPackets % 30 == 0)
                {
                    //Returns the location of the source IP address and time of arrival
                    string strTCPIP = Convert.ToString(srcIp);
                    if (strTCPIP.Contains("."))
                    {
                        stringLocation += "PACKET NUMBER: " + numPackets + " | " + "TCP IP: " + strTCPIP + " " + GetCountryByIP(strTCPIP) + " packet arrived at: " + time;
                        stringLocation += Environment.NewLine;
                    }
                }
            }
            //Gathering the UDP packet data
            var udpPacket = PacketDotNet.UdpPacket.GetEncapsulated(packetx);

            if (udpPacket != null)
            {
                var ipPacket = (PacketDotNet.IpPacket)udpPacket.ParentPacket;
                System.Net.IPAddress srcIp = ipPacket.SourceAddress;
                System.Net.IPAddress dstIp = ipPacket.DestinationAddress;
                int srcPort = udpPacket.SourcePort;
                int dstPort = udpPacket.DestinationPort;

                //Print source and destination port
                stringInfo += "PACKET NUMBER: " + numPackets + " | " + "The UDP source port is: " + Convert.ToString(srcPort) + " and the UDP destination port is : " + Convert.ToString(dstPort);
                stringInfo += Environment.NewLine;

                //Print destination IP address
                stringInfo += "PACKET NUMBER: " + numPackets + " | " + "The UDP destination address is: " + Convert.ToString(dstIp);
                stringInfo += Environment.NewLine;

                //Print length of packet
                stringInfo += "PACKET NUMBER: " + numPackets + " | " + "The length of the packet is: " + len;
                stringInfo += Environment.NewLine;

                //Limits the number of location requests since the API only allows for 150 requests/min
                if (numPackets % 30 == 0)
                {
                    //Returns the location of the source IP addresses and time of arrival
                    string strUDPIP = Convert.ToString(srcIp);
                    if (strUDPIP.Contains("."))
                    {
                        stringLocation += "PACKET NUMBER: " + numPackets + "| " + "UDP IP: " + strUDPIP + " " + GetCountryByIP(strUDPIP) + " packet arrived at: " + time;
                        stringLocation += Environment.NewLine;
                    }
                }
            }

            //Increment the number of packets captured
            numPackets++;

            //Put the packet number in the capture window
            stringPackets += "Packet Number: " + Convert.ToString(numPackets);
            stringPackets += Environment.NewLine;

            //Array to store our data
            byte[] data = packet.Packet.Data;


            //Keep track of the number of bytes displayed per line
            int byteCounter = 0;


            stringPackets += "Destination Mac Address";
            //Parsing the packets

            stringPackets += Environment.NewLine;
            foreach (byte b in data)
            {
                //Add the byte to our string (in hexadecimal)
                if (byteCounter <= 13)
                {
                    stringPackets += b.ToString("X2") + " ";
                }
                byteCounter++;

                switch (byteCounter)
                {
                case 6: stringPackets += Environment.NewLine;
                    stringPackets     += "Source MAC Address: ";
                    break;

                case 12: stringPackets += Environment.NewLine;
                    stringPackets      += "EtherType: ";
                    break;

                case 14: if (data[12] == 8)
                    {
                        if (data[13] == 0)
                        {
                            numUDP++;
                            stringPackets += "(IP)";
                        }
                        if (data[13] == 6)
                        {
                            numARP++;
                            stringPackets += "(ARP)";
                        }
                    }

                    stringPackets += Environment.NewLine;
                    break;
                }
            }



            stringPackets += Environment.NewLine + Environment.NewLine;
            byteCounter    = 0;
            stringPackets += "Raw Data" + Environment.NewLine;
            //Process each byte in our captured packet
            foreach (byte b in data)
            {
                //Add the byte to our string (in hexadecimal)
                stringPackets += b.ToString("X2") + " ";
                byteCounter++;


                //adds a new line so it doesn't run over
                if (byteCounter == 16)
                {
                    byteCounter    = 0;
                    stringPackets += Environment.NewLine;
                }
            }
            stringPackets += Environment.NewLine;
            stringPackets += Environment.NewLine;
        }
Example #29
0
        void Device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);

            if (packet == null || !(packet is EthernetPacket))
            {
                return;
            }

            EthernetPacket et = (EthernetPacket)packet;

            if (et.PayloadPacket == null || !(packet.PayloadPacket is IpPacket))
            {
                return;
            }

            IpPacket ip = (IpPacket)et.PayloadPacket;

            if (ip == null || ip.PayloadPacket == null)
            {
                return;
            }

            packet = ip.PayloadPacket;
            switch (ip.Protocol)
            {
            case IPProtocolType.TCP:
            {
                TcpPacket  p      = (TcpPacket)packet;
                IPEndPoint source = new IPEndPoint(ip.SourceAddress, p.SourcePort);
                IPEndPoint dest   = new IPEndPoint(ip.DestinationAddress, p.DestinationPort);

                if (_HasFilters && !IsAllowedPacket(source, dest, IPProtocolType.TCP))
                {
                    return;
                }
                OnPacket?.Invoke(this, ip.Protocol, et);

                if (_SyncPackets.Count > 45000)
                {
                    GC.Collect();
                    Thread.Sleep(1);
                }

                _SyncPackets.TryAdd(new TcpStreamStack.ResumePacket()
                    {
                        Date = e.Packet.Timeval.Date,

                        HwSource = et.SourceHwAddress,
                        IpSource = source,
                        HwDest   = et.DestinationHwAddress,
                        IpDest   = dest,

                        Tcp = p
                    });
                break;
            }

            case IPProtocolType.UDP:
            {
                UdpPacket  p      = (UdpPacket)packet;
                IPEndPoint source = new IPEndPoint(ip.SourceAddress, p.SourcePort);
                IPEndPoint dest   = new IPEndPoint(ip.DestinationAddress, p.DestinationPort);

                if (_HasFilters && !IsAllowedPacket(source, dest, IPProtocolType.UDP))
                {
                    return;
                }
                OnPacket?.Invoke(this, ip.Protocol, et);
                break;
            }

            default:
            {
                IPEndPoint source = new IPEndPoint(ip.SourceAddress, 0);
                IPEndPoint dest   = new IPEndPoint(ip.DestinationAddress, 0);
                if (_HasFilters && !IsAllowedPacket(source, dest, IPProtocolType.UDP))
                {
                    return;
                }
                OnPacket?.Invoke(this, ip.Protocol, et);
                break;
            }
            }
        }
Example #30
0
        /* private static int packetIndex = 0;
         * private void Program_OnPacketArrivalAsync(object sender, CaptureEventArgs e)
         * {
         *   if (e.Packet.LinkLayerType == PacketDotNet.LinkLayers.Ethernet)
         *   {
         *       var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
         *       var ethernetPacket = (PacketDotNet.EthernetPacket)packet;
         *
         *       _dispatcher.BeginInvoke(new ThreadStart(delegate
         *       {
         *
         *           _ShowTextBox += (packetIndex +
         *                         e.Packet.Timeval.Date.ToString() +
         *                         e.Packet.Timeval.Date.Millisecond +
         *                         ethernetPacket.SourceHardwareAddress +
         *                         ethernetPacket.DestinationHardwareAddress + "\n");
         *           packetIndex++;
         *       }));
         *       PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ShowTextBox)));
         *   }
         * }*/
        void Program_OnPacketArrivalAsync(object sender, CaptureEventArgs e)
        {
            Task.Run(() => { captureFileWriter.Write(e.Packet); });
            // парсинг всего пакета
            Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            // получение только TCP пакета из всего фрейма
            TcpPacket tcpPacket = (TcpPacket)packet.Extract <TcpPacket>();
            // получение только IP пакета из всего фрейма
            //IpPacket ipPacket = (IpPacket)packet.Extract(typeof(IpPacket));
            // получение только UDP пакета из всего фрейма
            UdpPacket udpPacket = (UdpPacket)packet.Extract <UdpPacket>();
            ArpPacket arpPacket = (ArpPacket)packet.Extract <ArpPacket>();
            //LinuxSLLPacket sllPacket = (LinuxSLLPacket)packet.Extract(typeof(LinuxSLLPacket));
            IcmpV4Packet icmpPacket = (IcmpV4Packet)packet.Extract <IcmpV4Packet>();
            IgmpV2Packet igmpPacket = (IgmpV2Packet)packet.Extract <IgmpV2Packet>();

            DateTime time    = e.Packet.Timeval.Date.ToLocalTime();
            string   StrTime = time.Hour + ":" + time.Minute + ":" + time.Second + ":" + time.Millisecond;
            int      len     = e.Packet.Data.Length;

            // Stream myStream;

            // using (myStream = File.Open(Path.GetTempPath() + "SnifferLogs.pcapng", FileMode.Append, FileAccess.Write))
            //  {
            //StreamWriter myWriter = new StreamWriter(myStream);
            //myWriter.WriteLine(e.Packet);
            //var thread = new Thread(() =>

            /*          Task.Run(() =>
             *        {
             *            //captureFileWriter = new CaptureFileWriterDevice(Path.GetTempPath() + "SnifferLogs.pcapng");
             *            captureFileWriter.Write(e.Packet);
             *            //Thread.Sleep(50);
             *        });*/
            // }

            // using (myStream = File.Open(Path.GetTempPath() + "SnifferLogs.pcapng", FileMode.OpenOrCreate, FileAccess.Read))
            // {
            // StreamReader myReader = new StreamReader(myStream);
            // Console.Write(myReader.ReadToEnd());
            //captureFileReader = new CaptureFileReaderDevice(Path.GetTempPath() + "SnifferLogs.pcapng");

            //captureFileReader = new CaptureFileReaderDevice(Path.GetTempPath() + "SnifferLogs.pcapng");
            _ShowTextBox += (num +
                             e.Packet.Timeval.Date.ToString() +
                             e.Packet.Timeval.Date.Millisecond + "\n");
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ShowTextBox)));

            //_ShowTextBox += myReader.ReadToEnd();
            // }

            /* using (myStream = File.Open(Path.GetTempPath() + "SnifferLogs.pcapng", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
             * {
             *   StreamWriter myWriter = new StreamWriter(myStream);
             *   StreamReader myReader = new StreamReader(myStream);
             *   //_MainCodeBehind.ShowMessage(e.Packet.ToString());
             *   myWriter.WriteLine(e.Packet.ToString());
             *   _ShowTextBox += myReader.ReadLine();
             *   _MainCodeBehind.ShowMessage(myReader.ReadLine());
             *   //captureFileWriter = new CaptureFileWriterDevice(Path.GetTempPath() + "SnifferLogs.pcapng");
             *   //captureFileWriter.Write(e.Packet);
             * }*/


            /* _dispatcher.BeginInvoke(new ThreadStart(delegate
             * {
             *
             *   captureFileWriter.Write(e.Packet);
             *   File.Copy(Path.GetTempPath() + "SnifferLogs.pcapng", Path.GetTempPath() + "SnifferLogs2.pcapng");
             * }));
             * _dispatcher.BeginInvoke(new ThreadStart(delegate
             * {
             *
             *   _ShowTextBox += (num +
             *                 e.Packet.Timeval.Date.ToString() +
             *                 e.Packet.Timeval.Date.Millisecond + "\n");
             * }));*/

            if (tcpPacket != null)
            {
                IPPacket ipPacket = (IPPacket)tcpPacket.ParentPacket;

                Tcp tpck;
                // порт отправителя
                tpck.srcPort = tcpPacket.SourcePort;
                // порт получателя
                tpck.dstPort   = tcpPacket.DestinationPort;
                tpck.seqNumber = tcpPacket.SequenceNumber;       /*значения в десятеричной форме*/
                tpck.ackNumber = tcpPacket.AcknowledgmentNumber;
                tpck.offset    = tcpPacket.DataOffset;
                tpck.flags     = tcpPacket.Flags;
                tpck.CWR       = tcpPacket.CongestionWindowReduced;
                tpck.ECE       = tcpPacket.ExplicitCongestionNotificationEcho;
                tpck.URG       = tcpPacket.Urgent;
                tpck.ACK       = tcpPacket.Acknowledgment;
                tpck.PSH       = tcpPacket.Push;
                tpck.RST       = tcpPacket.Reset;
                tpck.SYN       = tcpPacket.Synchronize;
                tpck.FIN       = tcpPacket.Finished;
                tpck.winSize   = tcpPacket.WindowSize;
                tpck.chksum    = tcpPacket.Checksum;
                tpck.urgpoint  = tcpPacket.UrgentPointer;
                tpck.tdata     = Hexdata(tcpPacket);

                string data = HexToAscii(tcpPacket);
                _dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Col.Add(new MyTable
                    {
                        Number   = num,
                        Time     = StrTime,
                        Src      = ipPacket.SourceAddress.ToString(),
                        Dst      = ipPacket.DestinationAddress.ToString(),
                        Protocol = "TCP",
                        Length   = len,
                        Info     = Convert.ToString(data)
                    });
                    tpck.pos = num;
                    TcpCol.Add(tpck);
                    num++;
                }));
            }

            if (udpPacket != null)
            {
                IPPacket ipPacket = (IPPacket)udpPacket.ParentPacket;
                Udp      udpk;
                udpk.srcPort = udpPacket.SourcePort;
                udpk.dstPort = udpPacket.DestinationPort;
                udpk.len     = udpPacket.Length;
                udpk.chksum  = udpPacket.Checksum;
                udpk.udata   = Hexdata(udpPacket);

                // данные пакета
                string data = HexToAscii(udpPacket);
                _dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Col.Add(new MyTable
                    {
                        Number   = num,
                        Time     = StrTime,
                        Src      = ipPacket.SourceAddress.ToString(),
                        Dst      = ipPacket.DestinationAddress.ToString(),
                        Protocol = "UDP",
                        Length   = len,
                        Info     = Convert.ToString(data)
                    });
                    udpk.pos = num;
                    UdpCol.Add(udpk);
                    num++;
                }));
            }

            if (arpPacket != null)
            {
                Arp arpk;
                arpk.hwtype     = arpPacket.HardwareAddressType.ToString();
                arpk.prtype     = arpPacket.ProtocolAddressType.ToString();
                arpk.hwsize     = arpPacket.HardwareAddressLength;
                arpk.prtsize    = arpPacket.ProtocolAddressLength;
                arpk.opcode     = Convert.ToInt16(arpPacket.Operation);
                arpk.sender_mac = arpPacket.SenderHardwareAddress;
                arpk.sender_ip  = arpPacket.SenderProtocolAddress;
                arpk.target_mac = arpPacket.TargetHardwareAddress;
                arpk.target_ip  = arpPacket.TargetProtocolAddress;
                arpk.adata      = Hexdata(arpPacket);

                // данные пакета
                string data = HexToAscii(arpPacket);

                _dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Col.Add(new MyTable
                    {
                        Number   = num,
                        Time     = StrTime,
                        Src      = arpk.sender_ip.ToString(),
                        Dst      = arpk.target_ip.ToString(),
                        Protocol = "ARP",
                        Length   = len,
                        Info     = Convert.ToString(data)
                    });
                    arpk.pos = num;
                    ArpCol.Add(arpk);
                    num++;
                }));
            }


            if (icmpPacket != null)
            {
                IPPacket ipPacket = (IPPacket)icmpPacket.ParentPacket;
                Icmp     icmpk;
                icmpk.type   = icmpPacket.TypeCode.ToString();
                icmpk.chksum = icmpPacket.Checksum;
                icmpk.seq    = icmpPacket.Sequence;
                icmpk.icdata = Hexdata(icmpPacket);
                // данные пакета
                string data = "";
                for (int i = 0; i < icmpPacket.Data.Count(); i++)
                {
                    data += icmpPacket.Data[i];
                }

                _dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Col.Add(new MyTable
                    {
                        Number   = num,
                        Time     = StrTime,
                        Src      = ipPacket.SourceAddress.ToString(),
                        Dst      = ipPacket.DestinationAddress.ToString(),
                        Protocol = "ICMPv4",
                        Length   = len,
                        Info     = Convert.ToString(data)
                    });
                    icmpk.pos = num;
                    IcmpCol.Add(icmpk);
                    num++;
                }));
            }

            if (igmpPacket != null)
            {
                IPPacket ipPacket = (IPPacket)igmpPacket.ParentPacket;
                Igmp     igmpk;
                igmpk.type          = igmpPacket.Type.ToString();
                igmpk.max_resp_time = igmpPacket.MaxResponseTime.ToString();
                igmpk.chksum        = igmpPacket.Checksum;
                igmpk.group_addr    = igmpPacket.GroupAddress.ToString();
                igmpk.igdata        = Hexdata(igmpPacket);
                // данные пакета
                string data = HexToAscii(igmpPacket);

                _dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Col.Add(new MyTable
                    {
                        Number   = num,
                        Time     = StrTime,
                        Src      = ipPacket.SourceAddress.ToString(),
                        Dst      = ipPacket.DestinationAddress.ToString(),
                        Protocol = "IGMPv2",
                        Length   = len,
                        Info     = Convert.ToString(data)
                    });
                    igmpk.pos = num;
                    IgmpCol.Add(igmpk);
                    num++;
                }));
            }
        }
Example #31
0
 /// <summary>
 /// 从文件读的数据包到达时发生
 /// </summary>
 private void readPacketArrival(object sender, CaptureEventArgs e)
 {
     packetArrival(sender, e);
 }
Example #32
0
        private void ReceiveCallback(object sender, CaptureEventArgs e)
        {
            //
            // Filter out packets intended for the emulator, forward them on, drop everything else.
            //
            if (e.Packet.LinkLayerType == LinkLayers.Ethernet)
            {
                //
                // We wrap this in a try/catch; on occasion Packet.ParsePacket fails due to a bug
                // in the PacketDotNet library.
                //
                EthernetPacket packet = null;
                try
                {
                    packet = (EthernetPacket)Packet.ParsePacket(LinkLayers.Ethernet, e.Packet.Data);
                }
                catch (Exception ex)
                {
                    // Just eat this, log a message.
                    Log.Write(LogType.Error, LogComponent.HostEthernet, "Failed to parse incoming packet.  Exception {0}", ex.Message);
                    packet = null;
                }

                if (packet != null)
                {
                    if (!packet.SourceHwAddress.Equals(_10mbitSourceAddress) &&             // Don't recieve packets sent by this emulator.
                        (packet.DestinationHwAddress.Equals(_10mbitSourceAddress) ||        // Filter on packets destined for us or broadcast.
                         packet.DestinationHwAddress.Equals(_10mbitBroadcastAddress)))
                    {
                        Log.Write(LogType.Verbose, LogComponent.HostEthernet, "Packet received: dst {0} src {1}",
                                  packet.DestinationHwAddress, packet.SourceHwAddress);

                        _callback(new System.IO.MemoryStream(e.Packet.Data));

                        /*
                         * if (Log.Enabled)
                         * {
                         *  StringBuilder sb = new StringBuilder();
                         *  int byteNum = 0;
                         *  StringBuilder dataLine = new StringBuilder();
                         *  StringBuilder asciiLine = new StringBuilder();
                         *  dataLine.AppendFormat("000: ");
                         *
                         *  for (int i = 0; i < e.Packet.Data.Length; i++)
                         *  {
                         *      dataLine.AppendFormat("{0:x2} ", e.Packet.Data[i]);
                         *      asciiLine.Append(GetPrintableChar(e.Packet.Data[i]));
                         *
                         *      byteNum++;
                         *      if ((byteNum % 16) == 0)
                         *      {
                         *          Log.Write(LogComponent.EthernetPacket, "{0} {1}", dataLine.ToString(), asciiLine.ToString());
                         *          dataLine.Clear();
                         *          asciiLine.Clear();
                         *          dataLine.AppendFormat("{0:x3}: ", i + 1);
                         *          byteNum = 0;
                         *      }
                         *  }
                         *
                         *  if (byteNum > 0)
                         *  {
                         *      Log.Write(LogComponent.EthernetPacket, "{0} {1}", dataLine.ToString(), asciiLine.ToString());
                         *  }
                         *
                         *  Log.Write(LogComponent.EthernetPacket, "");
                         * } */
                    }
                    else
                    {
                        // Not for us, discard the packet.
                    }
                }
            }
        }
Example #33
0
        /// <summary>  
        /// 接收到包的处理函数  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        private void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            ////解析出基本包  
            var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);


            ////协议类别  
            // var dlPacket = PacketDotNet.DataLinkPacket.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);  


            //var ethernetPacket = PacketDotNet.EthernetPacket.GetEncapsulated(packet);  


            //var internetLinkPacket = PacketDotNet.InternetLinkLayerPacket.Parse(packet.BytesHighPerformance.Bytes);  
            //var internetPacket = PacketDotNet.InternetPacket.Parse(packet.BytesHighPerformance.Bytes);  


            //var sessionPacket = PacketDotNet.SessionPacket.Parse(packet.BytesHighPerformance.Bytes);  
            //var appPacket = PacketDotNet.ApplicationPacket.Parse(packet.BytesHighPerformance.Bytes);  
            //var pppoePacket = PacketDotNet.PPPoEPacket.Parse(packet.BytesHighPerformance.Bytes);  


            //var arpPacket = PacketDotNet.ARPPacket.GetEncapsulated(packet);  
            //var ipPacket = PacketDotNet.IpPacket.GetEncapsulated(packet); //ip包  
            var udpPacket = PacketDotNet.UdpPacket.GetEncapsulated(packet);  
            //var tcpPacket = PacketDotNet.TcpPacket.GetEncapsulated(packet);  


            string ret = "";
            if (udpPacket != null)
            {
                //PrintPacket(ref ret, packet);
                ParsePacket(ref ret, udpPacket);
                //sendPackage(packet);

            }
                
            //ParsePacket(ref ret, ethernetPacket);  
            //ParsePacket(ref ret, internetLinkPacket);  
            //ParsePacket(ref ret, internetPacket);  
            //ParsePacket(ref ret, sessionPacket);  
            //ParsePacket(ref ret, appPacket);  
            //ParsePacket(ref ret, pppoePacket);  
            //ParsePacket(ref ret, arpPacket);  
            //ParsePacket(ref ret, ipPacket);  
            //ParsePacket(ref ret, udpPacket);  
            //ParsePacket(ref ret, tcpPacket);  




            if (!string.IsNullOrEmpty(ret))
            {
                string rlt = "\r\n时间 : " +
                    DateTime.Now.ToLongTimeString() +
                    "\r\n数据包: \r\n" + ret;
                //_logAction(rlt);
            }


        }
Example #34
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);
                        }
                    }
                }
            }
        }