예제 #1
0
파일: PPacket.cs 프로젝트: 24/source_04
        public PPacket(Packet packet, long packetNumber, TimeSpan relativeTime)
        {
            _packet       = packet;
            _packetNumber = packetNumber;
            _relativeTime = relativeTime;
            EthernetDatagram ethernet = packet.Ethernet;

            if (ethernet != null)
            {
                _ethernetType     = ethernet.EtherType;
                _ethernetTypeCode = GetEthernetTypeCode(ethernet.EtherType);
                //_ipv4 = packet.Ethernet.IpV4;
                //if (_ipv4 != null)
                if (ethernet.EtherType == PcapDotNet.Packets.Ethernet.EthernetType.IpV4)
                {
                    _ipv4           = packet.Ethernet.IpV4;
                    _source         = _ipv4.Source;
                    _destination    = _ipv4.Destination;
                    _ipProtocol     = _ipv4.Protocol;
                    _ipProtocolCode = GetIPProtocolCode(_ipv4.Protocol);
                    //_tcp = _ipv4.Tcp;
                    //if (_tcp != null)
                    if (_ipv4.Protocol == IpV4Protocol.Tcp)
                    {
                        _tcp             = _ipv4.Tcp;
                        _sourcePort      = _tcp.SourcePort;
                        _destinationPort = _tcp.DestinationPort;
                    }
                }
            }
        }
예제 #2
0
        public TcpConnection(Packet packet)
        {
            if (packet.Ethernet == null)
            {
                throw new Exception("error creating TcpStreamAddress packet is not ethernet");
            }
            EthernetDatagram ethernet = packet.Ethernet;

            //if (ip == null)
            if (ethernet.EtherType != PcapDotNet.Packets.Ethernet.EthernetType.IpV4)
            {
                throw new Exception("error creating TcpStreamAddress packet is not ipv4");
            }
            IpV4Datagram ip = ethernet.IpV4;

            //if (tcp == null)
            if (ip.Protocol != IpV4Protocol.Tcp)
            {
                throw new Exception("error creating TcpStreamAddress packet is not tcp");
            }
            TcpDatagram tcp = ip.Tcp;

            //_source = new TcpAddress(ip.Source, tcp.SourcePort);
            _source = new TcpAddress(ethernet.Source, ip.Source, tcp.SourcePort);
            //_destination = new TcpAddress(ip.Destination, tcp.DestinationPort);
            _destination = new TcpAddress(ethernet.Destination, ip.Destination, tcp.DestinationPort);
            SetOrder();
        }
예제 #3
0
        /// <summary>
        /// Update ctrl with packet information
        /// Increment frame_id by one
        /// </summary>
        /// <param name="packet">The packet to handle</param>
        /// <param name="frame_id">The frame id, for UI display</param>
        /// <param name="ctrl">The control to display information</param>
        public static void HandlePacket(Packet packet, ref UInt64 frame_id, object[] ctrl)
        {
            EthernetDatagram ethernet = packet.Ethernet;

            if (ethernet == null)
            {
                return;
            }

            switch (ethernet.EtherType)
            {
            case EthernetType.IpV4: {
                IpV4Datagram ip = ethernet.IpV4;
                IPParser.HandleIPV4(packet, ip, ref frame_id, ctrl);
                break;
            }

            case EthernetType.Arp: {
                ArpDatagram arp = ethernet.Arp;
                ArpParser.HandleARP(packet, arp, ref frame_id, ctrl);
                break;
            }

            default:
                break;
            }
        }
예제 #4
0
        /// <summary>
        /// Handle ARP packets
        /// </summary>
        /// <param name="packet">The EthernetDatagram</param>
        /// <param name="arp">The ArpDatagram to parse</param>
        public static void HandleARP(Packet packet, ArpDatagram arp,
                                     ref UInt64 frame_id, object[] ctrl)
        {
            ListViewItem item = new ListViewItem(frame_id.ToString());

            frame_id++;
            List <string>    packet_info = new List <string>();
            ListView         frames      = (ListView)ctrl[0];
            EthernetDatagram ethernet    = packet.Ethernet;

            packet_info.Add(packet.Timestamp.ToString("hh:mm:ss.fff tt"));
            packet_info.Add(arp.SenderProtocolIpV4Address.ToString());
            packet_info.Add(arp.TargetProtocolIpV4Address.ToString());
            packet_info.Add(ethernet.Source.ToString());
            packet_info.Add(ethernet.Destination.ToString());
            packet_info.Add("ARP");
            packet_info.Add(arp.Length.ToString());

            // update UI
            if (item != null)
            {
                item.SubItems.AddRange(packet_info.ToArray());
                object[] param = new object[2];
                param[0] = frames;
                object[] o = new object[3];
                o[0]     = item;
                o[1]     = ctrl[1];
                o[2]     = packet;
                param[1] = o;
                frames.BeginInvoke(new ParserHelper.UIHandlerEx(ParserHelper.UpdateFrameUI), param);
            }
        }
예제 #5
0
        public void ProcessICMP(EthernetDatagram packet)
        {
            IpV4Datagram ip = null;

            if (packet.EtherType == EthernetType.VLanTaggedFrame)
            {
                ip = packet.VLanTaggedFrame.IpV4;
            }
            else
            {
                ip = packet.IpV4;
            }

            IcmpDatagram icmp = ip.Icmp;

            if (icmp.MessageType == IcmpMessageType.Echo && ip.Destination.Equals(_adapter.IP))
            {
                SendIcmpEchoReply(ip.Source, packet.Source, icmp);
            }
            else if (icmp.MessageType == IcmpMessageType.EchoReply)
            {
                if (_current_state == ICMP_STATE.WAIT_ECHO && ip.Source.Equals(_target_ip) && ip.Destination.Equals(_adapter.IP))
                {
                    ushort SequenceNumber = (ushort)(icmp.Variable & 0xFFFF);
                    if (SequenceNumber == _current_icmp_sequence_num)
                    {
                        _ping_echo_wait_handle.Set();
                    }
                }
            }
        }
예제 #6
0
        //public static void Test_DumpPacketsToFile_03(string dumpFile, string deviceName = null, bool detail = false)
        //{
        //    // from project SavingPacketsToADumpFile
        //    _tr.WriteLine("Test_DumpPacketsToFile_03");

        //    string filter = "";
        //    //string filter = "not tcp portrange 52000-53000 and not net 0.0.0.0 mask 255.0.0.0";

        //    //string dumpFile = @"dump\dump.pcap";
        //    dumpFile = GetPath(dumpFile);
        //    _tr.WriteLine("dump to file \"{0}\"", dumpFile);

        //    PacketDevice device = SelectDevice(deviceName);
        //    if (device == null)
        //        return;
        //    __communicator = null;
        //    //_rs.OnAbortExecution += new OnAbortEvent(OnAbortExecution);
        //    _rs.OnAbortExecution = OnAbortExecution;
        //    try
        //    {
        //        using (__communicator = device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
        //        {
        //            using (PacketDumpFile dump = __communicator.OpenDump(dumpFile))
        //            {
        //                _tr.WriteLine("Listening on " + device.Description + "...");
        //                __communicator.SetFilter(filter);

        //                //PPacketManager ppacketManager = new PPacketManager();
        //                __communicator.ReceivePackets(0, packet =>
        //                    {
        //                        dump.Dump(packet);
        //                        //PrintPacketHandler2(ppacketManager.CreatePPacket(packet), detail);
        //                        PrintIpAdressList(packet);
        //                    });
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        _tr.WriteLine(ex.Message);
        //    }
        //    finally
        //    {
        //        //_rs.OnAbortExecution -= new OnAbortEvent(OnAbortExecution);
        //    }
        //}

        private static void PrintPacketHandler1(Packet packet)
        {
            _tr.Write("{0:yyyy-MM-dd HH:mm:ss.fff}", packet.Timestamp);

            EthernetDatagram ethernet = packet.Ethernet;

            if (ethernet != null)
            {
                _tr.WriteLine(" eth : src {0} dst {1} type {2,-10} pl {3,5}", ethernet.Source, ethernet.Destination, ethernet.EtherType, ethernet.PayloadLength);
                IpV4Datagram ipv4 = ethernet.IpV4;
                if (ipv4 != null)
                {
                    _tr.WriteLine(" ipv4 : src {0} dst {1} type {2,-10} pl {3,5}", ipv4.Source, ethernet.Destination, ethernet.EtherType, ethernet.PayloadLength);
                }
                //IpV4Datagram ip = packet.Ethernet.IpV4;
                //UdpDatagram udp = ip.Udp;

                // print ip addresses and udp ports
                //_tr.Write(ip.Source + ":" + udp.SourcePort + " -> " + ip.Destination + ":" + udp.DestinationPort);
            }
            else
            {
                _tr.WriteLine(" not ethernet");
            }
        }
예제 #7
0
        async void ReceiveResposnes()
        {
            await Task.Run(() =>
            {
                Packet pck;

                do
                {
                    if (!receiveTask)
                    {
                        return;
                    }


                    PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out pck);



                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                        {
                            if (pck.DataLink.Kind != DataLinkKind.Ethernet)
                            {
                                continue;
                            }
                            EthernetDatagram ed = pck.Ethernet;

                            if (ed.EtherType != EthernetType.Arp)
                            {
                                continue;
                            }
                            ArpDatagram arppck = ed.Arp;

                            if (arppck.Operation != ArpOperation.Reply)
                            {
                                continue;
                            }


                            NetworkHost host = new NetworkHost {
                                IP = arppck.SenderProtocolIpV4Address.ToString(), MAC = ed.Source.ToString()
                            };
                            OnCaptureHost?.Invoke(host);



                            continue;
                        }

                    default:
                        throw new InvalidOperationException("The result " + result + " shoudl never be reached here");
                    }
                } while (true);
            });
        }
예제 #8
0
        /// <summary>
        /// Handle IPV4 packets, including TCP and UDP packets
        /// </summary>
        /// <param name="packet">The IpV4Datagram to parse</param>
        public static void HandleIPV4(Packet packet, IpV4Datagram ip,
                                      ref UInt64 frame_id, object[] ctrl)
        {
            ListViewItem item = new ListViewItem(frame_id.ToString());

            frame_id++;
            List <string>    packet_info = new List <string>();
            ListView         frames      = (ListView)ctrl[0];
            EthernetDatagram ethernet    = packet.Ethernet;

            switch (ip.Protocol)
            {
            case IpV4Protocol.Udp: {
                UdpDatagram udp = ip.Udp;
                packet_info.Add(packet.Timestamp.ToString("hh:mm:ss.fff tt"));
                packet_info.Add(ip.Source + ":" + udp.SourcePort);
                packet_info.Add(ip.Destination + ":" + udp.DestinationPort);
                packet_info.Add(ethernet.Source.ToString());
                packet_info.Add(ethernet.Destination.ToString());
                packet_info.Add("UDP");
                packet_info.Add(udp.Length.ToString());

                break;
            }

            case IpV4Protocol.Tcp: {
                TcpDatagram tcp = ip.Tcp;
                packet_info.Add(packet.Timestamp.ToString("hh:mm:ss.fff tt"));
                packet_info.Add(ip.Source + ":" + tcp.SourcePort);
                packet_info.Add(ip.Destination + ":" + tcp.DestinationPort);
                packet_info.Add(ethernet.Source.ToString());
                packet_info.Add(ethernet.Destination.ToString());
                packet_info.Add("TCP");
                packet_info.Add(tcp.Length.ToString());

                break;
            }

            default: {
                item = null;
                break;
            }
            }

            // update UI
            if (item != null)
            {
                item.SubItems.AddRange(packet_info.ToArray());
                object[] param = new object[2];
                param[0] = frames;
                object[] o = new object[3];
                o[0]     = item;
                o[1]     = ctrl[1];
                o[2]     = packet;
                param[1] = o;
                frames.BeginInvoke(new ParserHelper.UIHandlerEx(ParserHelper.UpdateFrameUI), param);
            }
        }
예제 #9
0
        // Callback function invoked by Pcap.Net for every incoming packet
        private static void PacketHandler(Packet packet)
        {
            string packSource = packet.Ethernet.Source.ToString();

            if (myDevices[0].IPAddress != packet.IpV4.Source.ToString() && myDevices[0].MacAddress != packSource && myDevices[1].MacAddress != packSource)
            {
                //Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length + "IP:" + packet.IpV4);

                int              threadID = System.Threading.Thread.CurrentThread.ManagedThreadId; //fetch current thread ID
                MyDevice         devObj   = GetDevice(threadID, "mine");
                EthernetDatagram ed       = packet.Ethernet;

                if (ed.EtherType == EthernetType.Arp)//Checking if the packet type is arp
                {
                    Console.WriteLine("ARP packet MAC src=" + packet.Ethernet.Source.ToString());

                    //Console.WriteLine("ARP Packet");
                    //Console.WriteLine("TARGET ADDRESS: " + packet.Ethernet.Arp.TargetProtocolIpV4Address);
                    //Console.WriteLine("DEST: " + packet.IpV4.Destination);
                    //IPAddress ipSrc = IPAddress.Parse(packet.Ethernet.Arp.TargetProtocolIpV4Address);
                    //Console.WriteLine("ipSrc: " + packet.Ethernet.Arp.TargetProtocolIpV4Address.ToString());

                    ////if (CheckAddress(packet, "Arp"))
                    ////{
                    //    ArpPoison(packet, devObj);
                    ////}

                    Console.WriteLine("A=" + RemoveDots(packet.Ethernet.Source.ToString()));
                    Console.WriteLine("B=" + devObj.MacAddress);
                    Console.WriteLine("C=" + GetDevice(threadID, "other").MacAddress);

                    if (!(RemoveDots(packet.Ethernet.Source.ToString()).Equals(devObj.MacAddress) || RemoveDots(packet.Ethernet.Source.ToString()).Equals(GetDevice(threadID, "other").MacAddress)))
                    {
                        ArpPoison(packet, devObj);
                    }
                }
                else//packet type is icmp
                {
                    if (ed.IpV4.Protocol == IpV4Protocol.InternetControlMessageProtocol)
                    {
                        Console.WriteLine("ICMP packet IP DEST=" + packet.Ethernet.IpV4.Destination.ToString());
                        HandleIcmp(packet, threadID);
                    }
                    else
                    {
                        if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
                        {
                            Console.WriteLine("TCP packet");
                            HandleTcp(packet, threadID);
                        }
                        //else
                        //{
                        //    Console.WriteLine("Packet not recognized");
                        //}
                    }
                }
            }
        }
        protected override bool CompareField(XElement field, Datagram datagram)
        {
            EthernetDatagram ethernetDatagram = (EthernetDatagram)datagram;

            switch (field.Name())
            {
            case "eth.dst":
                CompareEthernetAddress(field, ethernetDatagram.Destination);
                break;

            case "eth.src":
                CompareEthernetAddress(field, ethernetDatagram.Source);
                break;

            case "eth.type":
                field.AssertNoFields();
                field.AssertShowDecimal((ushort)ethernetDatagram.EtherType);
                break;

            case "eth.trailer":
                // TODO: Support RARP.
                if (ethernetDatagram.EtherType != EthernetType.ReverseArp)
                {
                    field.AssertValue(ethernetDatagram.Trailer);
                }
                break;

            case "eth.fcs":
                // TODO: Support RARP.
                if (ethernetDatagram.EtherType != EthernetType.ReverseArp)
                {
                    field.AssertValue(ethernetDatagram.FrameCheckSequence);
                }
                break;

            case "eth.padding":
                field.AssertNoFields();
                // TODO: Support RARP.
                if (ethernetDatagram.EtherType != EthernetType.ReverseArp)
                {
                    field.AssertValue(ethernetDatagram.Padding);
                }
                break;

            default:
                throw new InvalidOperationException("Invalid etherent field " + field.Name());
            }

            return(true);
        }
예제 #11
0
        /// <summary>
        /// Packet parser dispatcher
        /// </summary>
        /// <param name="packet">The packet to be parsed</param>
        /// <param name="ctrl">Contorls to update details with</param>
        public static void ParsePacket(Packet packet, object[] ctrl)
        {
            if (packet == null || ctrl == null ||
                ctrl[0] == null || ctrl[1] == null)
            {
                return;
            }

            EthernetDatagram ethernet = packet.Ethernet;

            List <ListViewItem> items = new List <ListViewItem>();
            ListViewItem        item  = new ListViewItem("Ethernet");
            string estr = "Etype = " + ethernet.EtherType;

            estr += ", DestinationAddress = " + ethernet.Destination;
            estr += ", SourceAddress = " + ethernet.Source;
            item.SubItems.Add(estr);
            items.Add(item);

            ListView f_details = (ListView)ctrl[0];

            f_details.Items.Clear();

            object[] param = new object[2];
            param[0] = f_details;
            param[1] = items;
            f_details.BeginInvoke(new ParserHelper.UIHandler(ParserHelper.UpdateDetailsUI), param);

            switch (ethernet.EtherType)
            {
            case EthernetType.IpV4: {
                IpV4Datagram ip = ethernet.IpV4;
                IPParser.ParseIPPacket(ip, ctrl);
                break;
            }

            case EthernetType.Arp: {
                ArpDatagram arp = ethernet.Arp;
                ArpParser.ParseARPPacket(arp, ctrl);
                break;
            }

            default:
                break;
            }


            // Save packet for layed analyze
            SnifferMain.packet = packet;
        }
예제 #12
0
 private void PrintEthernet(PPacket ppacket)
 {
     EthernetDatagram ethernet = ppacket.Packet.Ethernet;
     if (ethernet == null)
         return;
     _dataLength -= 14;
     WriteTitle("[ethernet frame]");
     WriteValues(6, "destination MAC address", ethernet.Destination, "header length", 14);
     //WriteValues(6, "source MAC address", ethernet.Source, "data length", _dataLength);
     WriteValues(6, "source MAC address", ethernet.Source);
     WriteValues(2, "ether type", "0x" + ((ushort)ethernet.EtherType).zToHex() + "  " + ppacket.EthernetTypeCode);
     WriteTitle("[ethernet data]");
     WritePayloadData(48, ethernet.Payload.zAsEnumerableWithCounter(_dataEnum.Index));
 }
예제 #13
0
        public Packet CreateDnsReply(EthernetDatagram etherpacket, IpV4Address newAddress)
        {
            var ipPacket  = etherpacket.IpV4;
            var udpPacket = ipPacket.Udp;
            var dnsPacket = udpPacket.Dns;

            if (!dnsPacket.IsQuery)
            {
                throw new Exception("Packet should be a dns query!");
            }

            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = etherpacket.Destination,
                Destination = etherpacket.Source,
            };

            IpV4Layer ipLayer = new IpV4Layer
            {
                Source             = ipPacket.Destination,
                CurrentDestination = ipPacket.Source,
            };

            UdpLayer udpLayer = new UdpLayer
            {
                SourcePort      = udpPacket.DestinationPort,
                DestinationPort = udpPacket.SourcePort
            };


            DnsResourceData       resourceData   = new DnsResourceDataIpV4(newAddress);
            DnsDataResourceRecord resourceRecord = new DnsDataResourceRecord(dnsPacket.Queries[0].DomainName,
                                                                             dnsPacket.Queries[0].DnsType,
                                                                             dnsPacket.Queries[0].DnsClass,
                                                                             60,
                                                                             resourceData);

            DnsLayer dnsLayer = new DnsLayer
            {
                Queries    = dnsPacket.Queries,
                IsQuery    = false,
                IsResponse = true,
                Id         = dnsPacket.Id,
                Answers    = new[] { resourceRecord }
            };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipLayer, udpLayer, dnsLayer);

            return(builder.Build(DateTime.Now));
        }
예제 #14
0
        private void MapEthernetData(EthernetDatagram datagram)
        {
            this.SourceIp      = datagram.Source.ToString();
            this.DestinationIp = datagram.Destination.ToString();

            switch (datagram.EtherType)
            {
            case EthernetType.IpV4:
                this.MapIpV4Data(datagram.IpV4);
                break;

            default:
                throw new Exception($"Unsupported EtherType. ({datagram.EtherType})");
            }
        }
예제 #15
0
        protected virtual void NetifLevel2LayerIPv4(EthernetDatagram datagram, IpV4Datagram ip)
        {
            byte[] packet_data   = g_getIPv4DatagramBuffer(ip);
            int    packet_offset = g_getIPv4DatagramOffset(ip);
            int    packet_size   = ip.Length;

            if (packet_size > 0)
            {
                IPFrame frame = IPv4Layer.ParseFrame(new BufferSegment(packet_data, packet_offset, packet_size), true);
                if (frame != null)
                {
                    frame.SourceMacAddress      = datagram.Source;
                    frame.DestinationMacAddress = datagram.Destination;
                    this.OnSniffer(frame);
                }
            }
        }
예제 #16
0
        private void f_details_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (e.IsSelected)
            {
                ListViewItem item = e.Item;

                EthernetDatagram ethernet = packet.Ethernet;
                switch (item.Text)
                {
                case "Ethernet":
                {
                    // Update Ethernet details
                    if (ethernet != null)
                    {
                        PacketParser.DumpPacket(ethernet, h_details);
                    }
                    break;
                }

                case "IPV4":
                {
                    // Update IPV4 details
                    if (ethernet != null)
                    {
                        IpV4Datagram ip = packet.Ethernet.IpV4;
                        PacketParser.DumpPacket(ip, h_details);
                    }
                    break;
                }

                case "Payload Length":
                {
                    PacketParser.DumpPacket(payload, h_details);
                    break;
                }

                default:
                {
                    // Otherwise, use the last datagram
                    PacketParser.DumpPacket(datagram, h_details);
                    break;
                }
                }
            }
        }
예제 #17
0
        private static string GetConnString(PcapDotNet.Packets.Packet packet)
        {
            String           srcIp = "";
            String           dstIp = "";
            TcpDatagram      tcp   = null;
            EthernetDatagram eth   = packet.Ethernet;

            switch (eth.EtherType)
            {
            case EthernetType.IpV4:
                IpV4Datagram ip = eth.IpV4;
                tcp   = ip.Tcp;
                srcIp = ip.Source.ToString();
                dstIp = ip.Destination.ToString();
                break;

            case EthernetType.IpV6:
                IpV6Datagram ip6 = eth.IpV6;
                tcp   = ip6.Tcp;
                srcIp = ip6.Source.ToString();
                dstIp = ip6.CurrentDestination.ToString();
                break;

            default:
                Console.WriteLine("We should never see anything not ipv4 or ipv6 since we filtered by tcp");
                return("");
            }

            StringBuilder sb = new StringBuilder();

            sb.Append(srcIp);
            sb.Append(":");
            sb.Append(tcp.SourcePort);
            sb.Append(" to ");
            sb.Append(dstIp);
            sb.Append(":");
            sb.Append(tcp.DestinationPort);
            return(sb.ToString());
        }
        protected override bool CompareField(XElement field, Datagram datagram)
        {
            EthernetDatagram ethernetDatagram = (EthernetDatagram)datagram;

            switch (field.Name())
            {
            case "eth.dst":
                CompareEthernetAddress(field, ethernetDatagram.Destination);
                break;

            case "eth.src":
                CompareEthernetAddress(field, ethernetDatagram.Source);
                break;

            case "eth.type":
                field.AssertShowHex((ushort)ethernetDatagram.EtherType);
                break;

            case "eth.trailer":
                if (ethernetDatagram.Trailer != null)
                {
                    field.AssertValue(ethernetDatagram.Trailer);
                }
                break;

            case "":
                if (ethernetDatagram.Trailer != null)
                {
                    field.AssertValue(ethernetDatagram.FrameCheckSequence);
                }
                break;

            default:
                throw new InvalidOperationException("Invalid etherent field " + field.Name());
            }

            return(true);
        }
예제 #19
0
 protected virtual void NetifLevel2LayerArp(EthernetDatagram datagram, ArpDatagram arp)
 {
 }
예제 #20
0
        private void HandlePacket(PcapDotNet.Packets.Packet packet)
        {
            //give up if 10 errors are seen to prevent unexpected crashes
            if (numErrors > 10)
            {
                return;
            }
            String           srcIp = "";
            TcpDatagram      tcp   = null;
            EthernetDatagram eth   = packet.Ethernet;
            int dataStart          = eth.HeaderLength;

            switch (eth.EtherType)
            {
            case EthernetType.IpV4:
                IpV4Datagram ip = eth.IpV4;
                tcp        = ip.Tcp;
                srcIp      = ip.Source.ToString();
                dataStart += ip.HeaderLength + tcp.RealHeaderLength;
                break;

            case EthernetType.IpV6:
                IpV6Datagram ip6 = eth.IpV6;
                tcp        = ip6.Tcp;
                srcIp      = ip6.Source.ToString();
                dataStart += 40 + tcp.RealHeaderLength;
                Console.WriteLine("IPv6?");
                break;

            default:
                Console.WriteLine("We should never see anything not ipv4 or ipv6 since we filtered by tcp");
                return;
            }

            ushort srcPort   = tcp.SourcePort;
            int    dataBytes = tcp.PayloadLength;
            bool   syn       = tcp.IsSynchronize;

            //Console.WriteLine("dataStart={0} dataByes={1} srcPort={2} syn={3} srcIp={4}",dataStart,dataBytes,srcPort,syn,srcIp);

            if (syn && dataBytes == 0)
            {
                ct = new ServiceCore.CryptoTransformHeroes();
                ClearBuffer();
                if (myIp == srcIp)
                {
                    int dstPort = tcp.DestinationPort;
                    encryptDict.TryGetValue(dstPort, out encrypt);
                    serviceDict.TryGetValue(dstPort, out serviceType);
                }
                else
                {
                    encryptDict.TryGetValue(srcPort, out encrypt);
                    serviceDict.TryGetValue(srcPort, out serviceType);
                }
                Console.WriteLine("TCP connection starting with type {0} to {1}", encrypt, serviceType);
                SawSyn = true;
                return;
            }
            else if (!SawSyn)
            {
                Console.WriteLine("Haven't seen SYN yet from {0}", srcPort);
                return;
            }
            if (encrypt == EncryptionType.Relay || encrypt == EncryptionType.Pipe)
            {
                Console.WriteLine("Cannot handle type {0} from {1}", encrypt, serviceType);
                return;
            }
            if (dataBytes == 6 || dataBytes == 0)
            {
                //Console.WriteLine("Ping from port {0}", srcPort);
                ClearBuffer();
                return;
            }

            //String timestamp = packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff");
            //Console.WriteLine("{0}: {1} bytes={2}", timestamp, connString, dataBytes);

            recvSize.AddLast(dataBytes);
            Buffer.BlockCopy(packet.Buffer, dataStart, buffer, bufLen, dataBytes);

            ArraySegment <byte> dataSeg = new ArraySegment <byte>(buffer, bufLen, dataBytes);

            Devcat.Core.Net.Message.Packet p = new Devcat.Core.Net.Message.Packet(dataSeg);
            if (encrypt == EncryptionType.Normal)
            {
                long salt = p.InstanceId;
                ct.Decrypt(dataSeg, salt);
            }

            bufLen += dataBytes;

            while (bufLen != 0)
            {
                dataSeg = new ArraySegment <byte>(buffer, 0, bufLen);
                p       = new Devcat.Core.Net.Message.Packet(dataSeg);
                int pLen = 0;
                try
                {
                    pLen = p.Length + p.BodyOffset;
                    if (pLen == 0)
                    {
                        ClearBuffer();
                        //Console.WriteLine("Received ping");
                        return;
                    }
                    else
                    {
                        //Console.WriteLine("bufLen={0} pLen={1} recvSize={2}", bufLen, pLen, recvSizeToString());
                    }
                }
                catch (System.Runtime.Serialization.SerializationException)
                {
                    //Console.WriteLine("{0}: Bad length {1}", connString, e.Message);
                    RemovePacket();
                    numErrors++;
                    continue;
                }

                if (pLen > bufLen)
                {
                    return;
                }
                if (pLen <= 3 || pLen == 6)
                {
                    //ClearBuffer();
                    ShortenBuffer(pLen);
                    numErrors++;
                    Console.WriteLine("{0}: Invalid data packet with Length={1}", connString, pLen);
                    continue;
                }
                //Console.WriteLine("Read {0} bytes but need {1} bytes, creating object", bufLen, pLen);
                dataSeg = new ArraySegment <byte>(buffer, 0, pLen);
                p       = new Devcat.Core.Net.Message.Packet(dataSeg);
                try
                {
                    Console.WriteLine(p);
                    if (srcIp == myIp)
                    {
                        Console.WriteLine("Client->{0}:", serviceType);
                    }
                    else
                    {
                        Console.WriteLine("Server {0}:", serviceType);
                    }
                    if (classNames.Count == 0)
                    {
                        ProcessTypeConverter(p);
                        Console.WriteLine("Received TypeConverter");
                        //String reverse = reverseConnString(connString);
                        //Console.WriteLine("Sending TypeConverter to Client {0}",reverse);
                        //portHandler[reverse].processTypeConverter(p);
                    }
                    else
                    {
                        mf.Handle(p, null);
                    }
                    ShortenBuffer(pLen);
                }
                catch (InvalidOperationException e)
                {
                    Console.WriteLine(e);
                    String errMsg     = e.Message;
                    String className  = "";
                    int    categoryId = p.CategoryId;
                    ShortenBuffer(pLen);
                    MatchCollection mc;
                    if (classNames.TryGetValue(categoryId, out className))
                    {
                        LogUnhandledClass(className);
                        return;
                    }
                    mc = Regex.Matches(errMsg, @"\.([^,\.]{2,})(,|$)");
                    if (mc.Count != 0)
                    {
                        className = mc[0].Groups[1].ToString();
                        LogUnhandledClass(className);
                        return;
                    }
                    Console.WriteLine("{0}: Unknown class error {1}", connString, errMsg);
                }
                catch (System.Runtime.Serialization.SerializationException e)
                {
                    Console.WriteLine("{0}: The packet wasn't ready {1}", connString, e.Message);
                    RemovePacket();
                    numErrors++;
                }
                catch (System.ArgumentOutOfRangeException e)
                {
                    Console.WriteLine("{0}: The packet was too short: {1}", connString, e.Message);
                    ShortenBuffer(pLen);
                    numErrors++;
                }
                catch (System.ArgumentException e)
                {
                    Console.WriteLine("{0}: Serializing failed bacause a dict was made with 2 identical keys: {1}", connString, e.StackTrace);
                    ClearBuffer();
                    numErrors++;
                }
            }
        }
예제 #21
0
        private static void PrintPacketDetailHandlerOld(PPacket ppacket)
        {
            EthernetDatagram ethernet = ppacket.Packet.Ethernet;

            if (ethernet == null)
            {
                _tr.WriteLine("---------------------------------------------[not ethernet packet]---------------------------------------------");
                _tr.WriteLine("---------------------------------------------------------------------------------------------------------------");
                _tr.WriteLine();
                return;
            }
            _tr.WriteLine("----------------------------------[ethernet type II frame (64 to 1518 bytes)]----------------------------------");
            _tr.WriteLine("| dest MAC address   src MAC address    ether type  data (46-1500 bytes)   length  CRC checksum  total length |");
            _tr.WriteLine("| XX:XX:XX:XX:XX:XX  XX:XX:XX:XX:XX:XX  XX XX       XX XX XX XX XX XX ...          XX XX XX XX                |");
            _tr.WriteLine("---------------------------------------------------------------------------------------------------------------");
            StringBuilder sb = new StringBuilder();

            sb.Append("|");
            byte[] buffer = ppacket.Packet.Buffer;
            int    i      = 0;

            foreach (byte b in buffer)
            {
                if (i == 6 || i == 12)
                {
                    sb.Append(" ");
                }
                else if (i == 14)
                {
                    sb.Append("      ");
                }
                else if (i == 20)
                {
                    sb.Append(" ... ");
                    sb.AppendFormat(" {0,6} ", ethernet.PayloadLength);
                    break;
                }
                sb.Append(" ");
                sb.Append(b.zToHex());
                i++;
            }
            //for (i = buffer.Length - 4; i < buffer.Length; i++)
            //{
            //    byte b = buffer[i];
            //    sb.Append(" ");
            //    sb.Append(b.zToHex());
            //}
            sb.Append("            ");
            //  total length
            sb.AppendFormat("         {0,6} |", ppacket.Packet.Count);
            _tr.WriteLine(sb.ToString());
            _tr.WriteLine("---------------------------------------------------------------------------------------------------------------");
            sb.Clear();
            sb.AppendFormat("| {0}  {1}  {2}       ", ethernet.Destination, ethernet.Source, ((ushort)ethernet.EtherType).zToHex());
            i = 0;
            foreach (byte b in ethernet.Payload)
            {
                if (i++ == 6)
                {
                    break;
                }
                sb.Append(" ");
                sb.Append(b.zToHex());
            }
            sb.Append(" ... ");
            sb.AppendFormat(" {0,6} ", ethernet.PayloadLength);
            if (ethernet.FrameCheckSequence != null)
            {
                foreach (byte b in ethernet.FrameCheckSequence)
                {
                    sb.Append(" ");
                    sb.Append(b.zToHex());
                }
            }
            else
            {
                sb.Append("            ");
            }
            sb.AppendFormat("         {0,6} |", ppacket.Packet.Count);
            _tr.WriteLine(sb.ToString());
            _tr.WriteLine("|                                       {0,-25}                                             |", ppacket.EthernetTypeCode);
            _tr.WriteLine("---------------------------------------------------------------------------------------------------------------");
            IpV4Datagram ip = ethernet.IpV4;

            if (ip == null)
            {
                _tr.WriteLine("-----------------------------------------------[not ipv4 packet]-----------------------------------------------");
                _tr.WriteLine("---------------------------------------------------------------------------------------------------------------");
                _tr.WriteLine();
                return;
            }
            buffer = ip.ToArray();
            _tr.WriteLine("------------------------------------------[ipv4 header]-------------------------------------------");
            _tr.WriteLine("| 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |");
            _tr.WriteLine("|  version  |    ihl    |      dscp       | ecn |                  total length                  |");
            _tr.WriteLine("|                identification                 | flags  |            fragment offset            |");
            _tr.WriteLine("|     time to live      |       protocol        |                header checksum                 |");
            _tr.WriteLine("|                                       source ip address                                        |");
            _tr.WriteLine("|                                     destination ip address                                     |");
            _tr.WriteLine("|                                      options (if ihl > 5)                                      |");
            _tr.WriteLine("--------------------------------------------------------------------------------------------------");
            sb.Clear();
            for (i = 0; i < 4; i++)
            {
                sb.AppendFormat("|          {0}           ", buffer[i].zToHex());
            }
            sb.Append(" |");
            _tr.WriteLine(sb.ToString());
            sb.Clear();
            for (i = 4; i < 8; i++)
            {
                sb.AppendFormat("|          {0}           ", buffer[i].zToHex());
            }
            sb.Append(" |");
            _tr.WriteLine(sb.ToString());
            sb.Clear();
            for (i = 8; i < 12; i++)
            {
                sb.AppendFormat("|          {0}           ", buffer[i].zToHex());
            }
            sb.Append(" |");
            _tr.WriteLine(sb.ToString());
            sb.Clear();
            for (i = 12; i < 16; i++)
            {
                sb.AppendFormat("|          {0}           ", buffer[i].zToHex());
            }
            sb.Append(" |");
            _tr.WriteLine(sb.ToString());
            sb.Clear();
            for (i = 16; i < 20; i++)
            {
                sb.AppendFormat("|          {0}           ", buffer[i].zToHex());
            }
            sb.Append(" |");
            _tr.WriteLine(sb.ToString());
            _tr.WriteLine("--------------------------------------------------------------------------------------------------");
            //_tr.WriteLine("|  version  |    ihl    |      dscp       | ecn |                  total length                  |");
            //_tr.WriteLine("|     4     |    15     |      dscp       | ecn |                     12345                      |");
            _tr.WriteLine("|     {0}     |    {1,2}     |      0x{2}       |     |                     {3,5}                      |",
                          ip.Version, ip.HeaderLength / 4, ip.TypeOfService.zToHex(), ip.TotalLength);
            //_tr.WriteLine("|                identification                 | flags  |            fragment offset            |");
            //_tr.WriteLine("|                    0x0000                     | flags  |                0x0000                 |");
            _tr.WriteLine("|                    0x{0}                     |        |                0x{1}                 |", ip.Identification.zToHex(), ip.Fragmentation.Offset.zToHex());
            //_tr.WriteLine("|     time to live      |       protocol        |                header checksum                 |");
            //_tr.WriteLine("|         0x00          |         0x00          |                    0x0000                      |");
            _tr.WriteLine("|         0x{0}          |         0x{1}          |                    0x{2}                      |",
                          ip.Ttl.zToHex(), ((byte)ip.Protocol).zToHex(), ip.HeaderChecksum.zToHex());
            //_tr.WriteLine("|                                       source ip address                                        |");
            //_tr.WriteLine("|                                        123.123.123.123                                         |");
            _tr.WriteLine("|                                        {0,-15}                                         |", ip.Source);
            _tr.WriteLine("|                                        {0,-15}                                         |", ip.Destination);
            _tr.WriteLine("-------------------------------------------[ipv4 data]--------------------------------------------");
            //             | 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ...  |
            sb.Clear();
            sb.Append("|");
            i = 0;
            foreach (byte b in ip.Payload)
            {
                if (++i == 31)
                {
                    break;
                }
                sb.Append(" ");
                sb.Append(b.zToHex());
            }
            if (i != 31)
            {
                for (; i < 30; i++)
                {
                    sb.Append("   ");
                }
                sb.Append("      |");
            }
            else
            {
                sb.Append(" ...  |");
            }
            _tr.WriteLine(sb.ToString());
            _tr.WriteLine("--------------------------------------------------------------------------------------------------");
            _tr.WriteLine();



            ////*************    0      3    0.465083 192.168.0.1     52581 173.194.66.94     443 TCP         ACK                  0x0001 0x4B2091F9 0x4B2091FA 0x4695DD86 0x401A       .
            ////_tr.WriteLine("group     no    time     source           port destination      port protocal    flags                length sequence   next seq   ack number window urgent");
            //StringBuilder sb = new StringBuilder();
            ////_tr.Write("{0,5}  {1,5}  {2,10:0.000000}", ppacket.GroupNumber, ppacket.PacketNumber, ppacket.RelativeTime.TotalSeconds);
            //sb.AppendFormat("{0,5}  {1,5}  {2,10:0.000000}", ppacket.GroupNumber, ppacket.PacketNumber, ppacket.RelativeTime.TotalSeconds);
            //sb.AppendFormat(" {0,-15} {1,5} {2,-15} {3,5} {4,-10}", ppacket.Source, ppacket.SourcePort, ppacket.Destination, ppacket.DestinationPort, ppacket.ProtocolCode);
            //if (detail)
            //{
            //    TcpDatagram tcp = ppacket.Tcp;
            //    if (tcp != null && ppacket.Ipv4.Protocol == IpV4Protocol.Tcp)
            //    {
            //        sb.AppendFormat("  {0,-20}", ppacket.GetTcpFlagsString());
            //        sb.AppendFormat(" {0,6}", tcp.PayloadLength > 0 ? "0x" + ((short)tcp.PayloadLength).zToHex() : null);

            //        sb.AppendFormat(" 0x{0} {1,10} {2,10} {3,6} {4,6}", ppacket.Tcp.SequenceNumber.zToHex(), tcp.NextSequenceNumber != tcp.SequenceNumber ? "0x" + tcp.NextSequenceNumber.zToHex() : null,
            //            tcp.AcknowledgmentNumber != 0 ? "0x" + tcp.AcknowledgmentNumber.zToHex() : null, "0x" + tcp.Window.zToHex(),
            //            tcp.UrgentPointer != 0 ? "0x" + tcp.UrgentPointer.zToHex() : null);

            //        int i = 0;
            //        int maxDataChar = 50;
            //        foreach (byte b in tcp.Payload)
            //        {
            //            if (++i > maxDataChar)
            //                break;
            //            if (b >= 32 && b <= 126)
            //                sb.Append(((char)b).ToString());
            //            else
            //                sb.Append(".");
            //        }


            //    }
            //    else if (ppacket.Packet.Ethernet == null)
            //        sb.Append(" not ethernet");
            //}
            //_tr.WriteLine(sb.ToString());
        }
예제 #22
0
        public static CategorizeInfo SortPacket(PcapDotNet.Packets.Packet raw)
        {
            // Get a packet from raw data.
            // Be a little lazy and assume that only Ethernet DLL protcol is used.
            EthernetDatagram packet = raw.Ethernet;

            CategorizeInfo info = new CategorizeInfo
            {
                NetworkLayer     = new Dictionary <string, long>(),
                TransportLayer   = new Dictionary <string, long>(),
                ApplicationLayer = new Dictionary <string, long>()
            };

            #region Network Layer
            switch (packet.EtherType)
            {
            case EthernetType.Arp:
                info.NetworkLayer.Increment("ARP");
                break;

            case EthernetType.IpV4:
                info.NetworkLayer.Increment("IPv4");
                break;

            case EthernetType.IpV6:
                info.NetworkLayer.Increment("IPv6");
                break;

            default:
                info.NetworkLayer.Increment("Others");
                break;
            }
            #endregion

            #region Transport Layer
            IpV4Datagram ipv4pk = null;
            if (packet.EtherType == EthernetType.IpV4)
            {
                ipv4pk = packet.IpV4;
                switch (ipv4pk.Protocol)
                {
                case IpV4Protocol.Tcp:
                    info.TransportLayer.Increment("TCP");
                    break;

                case IpV4Protocol.Udp:
                    info.TransportLayer.Increment("UDP");
                    break;

                default:
                    info.TransportLayer.Increment("Others");
                    break;
                }
            }
            #endregion

            #region Application Layer
            if (ipv4pk != null)
            {
                if (ipv4pk.Protocol == IpV4Protocol.Tcp)
                {
                    TcpDatagram tcpPk = ipv4pk.Tcp;
                    string      s     = new ASCIIEncoding().GetString(tcpPk.Payload.ToArray());
                    if (s.IndexOf("HTTP") > 0)
                    {  // Found HTTP head
                        info.ApplicationLayer.Increment("HTTP Header");
                    }
                    else
                    {
                        info.ApplicationLayer.Increment("Others");
                    }
                }
            }
            #endregion

            return(info);
        }
예제 #23
0
        public List <Packet> ParsePcapFile(string path)
        {
            List <Packet> list = new List <Packet>();

            OfflinePacketDevice selectedDevice = new OfflinePacketDevice(path);

            // открытие файла для парсинга
            using (PacketCommunicator communicator =
                       selectedDevice.Open(65536,                                  // считает полностью весь пакет 65536 max size of packet
                                           PacketDeviceOpenAttributes.Promiscuous, // какие - то непонятные флаги)
                                           1000))                                  // время чтения
            {
                using (var filter = communicator.CreateFilter("ether broadcast"))
                {
                    communicator.SetFilter(filter);

                    bool endOfFile = false;

                    // разираем полученные пакеты по одному
                    do
                    {
                        PcapDotNet.Packets.Packet packet;
                        var myPacket = new Packet();


                        PacketCommunicatorReceiveResult result = communicator.ReceivePacket(out packet);
                        switch (result)
                        {
                        case PacketCommunicatorReceiveResult.Eof:
                        {
                            endOfFile = true;
                            break;
                        }

                        case PacketCommunicatorReceiveResult.Timeout:
                            break;     // Timeout

                        case PacketCommunicatorReceiveResult.Ok:
                        {
                            IpV4Datagram     ip       = packet.Ethernet.IpV4;
                            TcpDatagram      tcp      = ip.Tcp;
                            EthernetDatagram ethernet = packet.Ethernet;

                            // common fields
                            myPacket.Protocol           = "Ethernet";
                            myPacket.SourceAddress      = ip.Source.ToString();
                            myPacket.SourcePort         = tcp.SourcePort.ToString();
                            myPacket.DestinationAddress = ip.Destination.ToString();
                            myPacket.DestinationPort    = tcp.DestinationPort.ToString();
                            myPacket.TimeStamp          = packet.Timestamp;
                            myPacket.Length             = packet.Length;
                            myPacket.Data = packet.Buffer;

                            // unusual fields

                            StringBuilder properties = new StringBuilder();

                            // MAC адресс получателя
                            properties.AppendLine("MAC address of destination : " + ethernet.Destination.ToString());
                            //
                            properties.AppendLine("EtherType : " + ethernet.EtherType.ToString());
                            // Длинна заголовков
                            properties.AppendLine("HeaderLength : " + ethernet.HeaderLength.ToString());
                            // Длинна полезной загрузки
                            properties.AppendLine("PayloadLength : " + ethernet.PayloadLength.ToString());
                            // MAC адресс отправителя
                            properties.AppendLine("Source Mac address : " + ethernet.Source.ToString());

                            myPacket.Header = properties.ToString();

                            list.Add(myPacket);

                            continue;
                        }

                        default:
                            throw new InvalidOperationException("The result " + result +
                                                                " shoudl never be reached here");
                        }
                    } while (!endOfFile);
                }
            }

            return(list);
        }
예제 #24
0
        public virtual void Listen()
        {
            while (true)
            {
                lock (this.m_syncobj)
                {
                    if (this.m_disposed)
                    {
                        break;
                    }
                }
                if (this.SupportTwoLayerLinks)
                {
#if !NO_USAGE_PCAP_NET
                    // Retrieve the packets
                    PacketCommunicatorReceiveResult result = this.m_packetCommunicator.ReceivePacket(out Packet packet);
                    switch (result)
                    {
                    case PacketCommunicatorReceiveResult.Timeout:
                        // Timeout elapsed
                        continue;

                    case PacketCommunicatorReceiveResult.Ok:
                    {
                        EthernetDatagram datagram = packet.Ethernet;         // 以太网数据报
                        switch (datagram.EtherType)
                        {
                        case EthernetType.IpV4:
                            NetifLevel2LayerIPv4(datagram, datagram.IpV4);
                            break;

                        case EthernetType.IpV6:
                            break;

                        case EthernetType.Arp:
                            NetifLevel2LayerArp(datagram, datagram.Arp);
                            break;

                        default:
                            break;
                        }
                    }
                    break;

                    default:
                        break;
                    }
#endif
                }
                else
                {
                    int packet_size = 0;
                    try
                    {
                        EndPoint localEP = this.m_socket.LocalEndPoint;
                        packet_size = this.m_socket.ReceiveFrom(this.m_buffer, 0, this.m_buffer.Length, SocketFlags.None, ref localEP);
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                    if (packet_size <= 0)
                    {
                        continue;
                    }

                    IPFrame frame = IPv4Layer.ParseFrame(new BufferSegment(this.m_buffer, 0, packet_size), true);
                    if (frame != null)
                    {
                        this.OnSniffer(frame);
                    }
                }
            }
        }
예제 #25
0
        private void PacketHandler(Packet packet)
        {
            this.count = ""; this.time = ""; this.source = ""; this.destination = ""; this.protocol = ""; this.length = "";


            paqueter = packet;

            EthernetDatagram eth = packet.Ethernet;
            IpV4Datagram     ip  = packet.Ethernet.IpV4;
            TcpDatagram      tcp = ip.Tcp;
            UdpDatagram      udp = ip.Udp;


            HttpDatagram httpPacket = null;



            if (ip.Protocol.ToString().Equals("Tcp"))
            {
                count            = packet.Count.ToString();
                time             = packet.Timestamp.ToString();
                this.source      = ip.Source.ToString();
                this.destination = ip.Destination.ToString();
                length           = eth.Length.ToString();
                protocol         = ip.Protocol.ToString();
            }
            else
            {
                if ((ip.Protocol.ToString().Equals("Udp")))
                {
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = eth.Length.ToString();
                    protocol         = ip.Protocol.ToString();
                }
            }

            if (ip.Protocol.ToString().Equals("Tcp") && (save.Checked))
            {
                int _source      = tcp.SourcePort;
                int _destination = tcp.DestinationPort;

                if (tcp.PayloadLength != 0)
                {
                    payload = new byte[tcp.PayloadLength];
                    tcp.Payload.ToMemoryStream().Read(payload, 0, tcp.PayloadLength);
                    if (_destination == 80)
                    {
                        Packet1 packet1 = new Packet1();
                        int     i       = Array.IndexOf(payload, (byte)32, 6);
                        byte[]  t       = new byte[i - 5];
                        Array.Copy(payload, 5, t, 0, i - 5);
                        packet1.Name = System.Text.ASCIIEncoding.ASCII.GetString(t);

                        if (!packets.ContainsKey(_source))
                        {
                            packets.Add(_source, packet1);
                        }
                    }
                    else
                    if (_source == 80)
                    {
                        if (packets.ContainsKey(_destination))
                        {
                            Packet1 packet1 = packets[_destination];
                            if (packet1.Data == null)
                            {
                                if ((httpPacket.Header != null) && (httpPacket.Header.ContentLength != null))
                                {
                                    packet1.Data = new byte[(uint)httpPacket.Header.ContentLength.ContentLength];
                                    Array.Copy(httpPacket.Body.ToMemoryStream().ToArray(), packet1.Data, httpPacket.Body.Length);
                                    packet1.Order       = (uint)(tcp.SequenceNumber + payload.Length - httpPacket.Body.Length);
                                    packet1.Data_Length = httpPacket.Body.Length;
                                    for (int i = 0; i < packet1.TempPackets.Count; i++)
                                    {
                                        Temp tempPacket = packet1.TempPackets[i];
                                        Array.Copy(tempPacket.data, 0, packet1.Data, tempPacket.tempSeqNo - packet1.Order, tempPacket.data.Length);
                                        packet1.Data_Length += tempPacket.data.Length;
                                    }
                                }
                                else
                                {
                                    Temp tempPacket = new Temp();
                                    tempPacket.tempSeqNo = (uint)tcp.SequenceNumber;
                                    tempPacket.data      = new byte[payload.Length];
                                    Array.Copy(payload, tempPacket.data, payload.Length);
                                    packet1.TempPackets.Add(tempPacket);
                                }
                            }
                            else if (packet1.Data_Length != packet1.Data.Length)
                            {
                                Array.Copy(payload, 0, packet1.Data, tcp.SequenceNumber - packet1.Order, payload.Length);

                                packet1.Data_Length += payload.Length;
                            }

                            if (packet1.Data != null)
                            {
                                if (packet1.Data_Length == packet1.Data.Length)
                                {
                                    using (BinaryWriter writer = new BinaryWriter(File.Open(fullpath + Directory.CreateDirectory(Path.GetFileName(packet1.Name)), FileMode.Create)))
                                    {
                                        writer.Write(packet1.Data);
                                    }

                                    packets.Remove(_destination);
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #26
0
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                int    indice  = listView1.Items.IndexOf(listView1.SelectedItems[0]);
                Packet paquete = paquetes[indice];

                EthernetDatagram eth = paquete.Ethernet;
                IpV4Datagram     ip  = paquete.Ethernet.IpV4;
                TcpDatagram      tcp = ip.Tcp;
                UdpDatagram      udp = ip.Udp;

                long checksum = Convert.ToInt64(ip.HeaderChecksum);

                string            df = "", mf = "";
                IpV4Fragmentation flags = ip.Fragmentation;
                if (flags.Options.ToString().Equals("MoreFragments"))
                {
                    df = "True";
                    mf = "True";
                }
                if (flags.Options.ToString().Equals("None"))
                {
                    df = "True";
                    mf = "False";
                }
                if (flags.Options.ToString().Equals("DoNotFragment"))
                {
                    df = "False";
                    mf = "False";
                }

                treeView1.Nodes.Clear();

                TreeNode node1 = new TreeNode("ETHERNET");
                node1.ForeColor = Color.Blue;
                node1.Nodes.Add("MAC de Origen: " + eth.Source.ToString().ToUpper());
                node1.Nodes.Add("MAC de Destino: " + eth.Destination.ToString().ToUpper());
                node1.Nodes.Add("Tipo de servicio: " + eth.EtherType.ToString().ToUpper());

                TreeNode node2 = new TreeNode("IP");
                node2.ForeColor = Color.Green;
                node2.Nodes.Add("Version: " + ip.Version.ToString());
                node2.Nodes.Add("Longitud de la cabecera: " + ip.HeaderLength.ToString() + " Bytes");
                node2.Nodes.Add("Tipo de servicio: " + ip.TypeOfService.ToString());
                node2.Nodes.Add("Longitud del paquete: " + ip.Length.ToString() + " Bytes");
                node2.Nodes.Add("Identificacion: " + Convert.ToString(Convert.ToInt64(ip.Identification), 16));
                node2.Nodes.Add("Fragmentado: " + df);
                node2.Nodes.Add("Mas fragmentos: " + mf);
                node2.Nodes.Add("Desplazamiento del fragmento: " + flags.Offset.ToString());
                node2.Nodes.Add("Tiempo de vida: " + ip.Ttl.ToString() + " Segundos");
                node2.Nodes.Add("Protocolo: " + ip.Protocol.ToString());
                node2.Nodes.Add("Checksum 0x" + Convert.ToString(Convert.ToInt64(checksum), 16) + "  [ " + ip.IsHeaderChecksumCorrect.ToString() + " ] ");
                node2.Nodes.Add("Ip origen: " + ip.Source.ToString());
                node2.Nodes.Add("Ip destino: " + ip.Destination.ToString());

                node1.Nodes.Add(node2);

                if (ip.Protocol.ToString().Equals("Tcp"))
                {
                    long checksumtcp = Convert.ToInt64(tcp.Checksum);
                    int  flag;

                    TreeNode node3 = new TreeNode("TCP");
                    node3.ForeColor = Color.Red;
                    node3.Nodes.Add("Puerto de Origen: " + tcp.SourcePort.ToString());
                    node3.Nodes.Add("Puerto de Destino: " + tcp.DestinationPort.ToString());
                    node3.Nodes.Add("Numero de secuencia: " + tcp.SequenceNumber.ToString());
                    node3.Nodes.Add("Siguiente numero de secuencia: " + tcp.NextSequenceNumber.ToString());
                    node3.Nodes.Add("Numero de confirmacion: " + tcp.AcknowledgmentNumber.ToString());
                    node3.Nodes.Add("Longitud de la cabecera: " + tcp.HeaderLength.ToString() + " Bytes");
                    node3.Nodes.Add("0000 00.. ....  : Reservado");
                    flag = tcp.IsUrgent ? 1 : 0;
                    node3.Nodes.Add(".... .." + flag.ToString() + ". ....  : URG =" + tcp.IsUrgent.ToString());
                    flag = tcp.IsAcknowledgment ? 1 : 0;
                    node3.Nodes.Add(".... ..." + flag.ToString() + " ....  : ACK =" + tcp.IsAcknowledgment.ToString());
                    flag = tcp.IsPush ? 1 : 0;
                    node3.Nodes.Add(".... .... " + flag.ToString() + "...  : PSH =" + tcp.IsPush.ToString());
                    flag = tcp.IsReset ? 1 : 0;
                    node3.Nodes.Add(".... .... ." + flag.ToString() + "..  : RST =" + tcp.IsReset.ToString());
                    flag = tcp.IsSynchronize ? 1 : 0;
                    node3.Nodes.Add(".... .... .." + flag.ToString() + ".  : SYN =" + tcp.IsSynchronize.ToString());
                    flag = tcp.IsFin ? 1 : 0;
                    node3.Nodes.Add(".... .... ..." + flag.ToString() + "  : FIN =" + tcp.IsFin.ToString());
                    node3.Nodes.Add("Tamaño de ventana: " + tcp.Window.ToString() + " Bytes");
                    node3.Nodes.Add("Checksum 0x" + Convert.ToString(Convert.ToInt64(checksumtcp), 16));
                    node3.Nodes.Add("Puntero urgente: " + tcp.UrgentPointer.ToString());

                    node2.Nodes.Add(node3);
                }

                if ((ip.Protocol.ToString().Equals("Udp")))
                {
                    long checksumudp = Convert.ToInt64(udp.Checksum);

                    TreeNode node3 = new TreeNode("UDP");
                    node3.ForeColor = Color.Red;
                    node3.Nodes.Add("Puerto de Origen: " + udp.SourcePort.ToString());
                    node3.Nodes.Add("Puerto de Destino: " + udp.DestinationPort.ToString());
                    node3.Nodes.Add("Longitud de la cabecera: " + udp.TotalLength.ToString() + " Bytes");
                    node3.Nodes.Add("Checksum 0x" + Convert.ToString(Convert.ToInt64(checksumudp), 16));

                    node2.Nodes.Add(node3);
                }

                treeView1.Nodes.Add(node1);
                treeView1.ExpandAll();
            }
        }
예제 #27
0
        public void _PrintPacketDetailHandler(PPacket ppacket)
        {
            //try
            //{
                //------------------------------------------------------------------------------------------------------------------------------
                //| packet no 5                      | relative time 0.745022                                            | packet length 55    |
                //-------------------------------------------------------[ethernet frame]-------------------------------------------------------
                //| 0x0000 | 00 07 CB C1 35 5D       | destination MAC address         00:07:CB:C1:35:5D                 | header length 14    |
                //| 0x0006 | 48 5B 39 C0 45 48       | source MAC address              48:5B:39:C0:45:48                 | data length   41    |
                //| 0x000C | 08 00                   | ether type                      0x0800  IPv4                      |                     |
                //---------------------------------------------------------[ipv4 frame]---------------------------------------------------------
                //| 0x000E | 45                      | version                         4                                 | header length 20    |
                //|        |                         | internet header length (ihl)    5                                 | data length   21    |
                //| 0x000F | 00                      | dscp                            0x00                              |                     |
                //|        |                         | ecn                                                               |                     |
                //| 0x0010 | 00 29                   | total length                    41                                |                     |
                //| 0x0012 | 4F F9                   | identification                  0x4FF9                            |                     |
                //| 0x0014 | 40 00                   | flags                                                             |                     |
                //|        |                         | fragment offset                 0x0000                            |                     |
                //| 0x0016 | 80                      | time to live                    0x80                              |                     |
                //| 0x0017 | 06                      | protocol                        0x06 TCP                          |                     |
                //| 0x0018 | 1A 47                   | header checksum                 0x1A47                            |                     |
                //| 0x001A | C0 A8 00 01             | source ip address               192.168.0.1                       |                     |
                //| 0x001E | AD C2 22 23             | destination ip address          173.194.34.35                     |                     |
                //|        |                         | options (if ihl > 5)                                              |                     |
                //| 0x0022 | CD 67 01 BB E9 DF 53 5D | data                                                              |                     |
                //| 0x002A | 91 1F 42 06 50 10 40 3D |                                                                   |                     |
                //| 0x0032 | FF 81 00 00 00          |                                                                   |                     |
                //------------------------------------------------------------------------------------------------------------------------------

                //if (ip.Tcp != null && ip.Tcp.Http.Version == null)
                //    return;

                PrintPacketInfos(ppacket);
                _dataLength = (ushort)ppacket.Packet.Count;
                _dataEnum = ppacket.Packet.zAsEnumerableWithCounter();
                PrintEthernet(ppacket);

                EthernetDatagram ethernet = ppacket.Packet.Ethernet;
                if (ethernet.EtherType == EthernetType.IpV4)
                {
                    PrintIpV4(ppacket);
                    IpV4Datagram ip = ethernet.IpV4;
                    if (ip.Protocol == IpV4Protocol.Tcp)
                    {
                        PrintTcp(ppacket);
                        if (ip.Tcp.Http.Version != null)
                            PrintHttp(ppacket);
                    }
                }
                WriteSeparation();
                Trace.WriteLine();


            //}
            //finally
            //{
            //    WriteSeparation();
            //    Trace.WriteLine();
            //}
        }