예제 #1
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();
                    }
                }
            }
        }
예제 #2
0
        public void SendIcmpEchoReply(IpV4Address TargetIP, MacAddress TargetMac, IcmpDatagram icmpRequest)
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
            {
                Source      = _adapter.MAC,
                Destination = TargetMac,
                EtherType   = EthernetType.None,   // Will be filled automatically.
            };

            VLanTaggedFrameLayer vlanLayer =
                new VLanTaggedFrameLayer
            {
                PriorityCodePoint        = ClassOfService.BestEffort,
                CanonicalFormatIndicator = false,
                VLanIdentifier           = _adapter.VLAN,
                EtherType = EthernetType.None,
            };

            IpV4Layer ipV4Layer =
                new IpV4Layer
            {
                Source             = _adapter.IP,
                CurrentDestination = TargetIP,
                Fragmentation      = IpV4Fragmentation.None,
                HeaderChecksum     = null, // Will be filled automatically.
                Identification     = 123,
                Options            = IpV4Options.None,
                Protocol           = null, // Will be filled automatically.
                Ttl           = 100,
                TypeOfService = 0,
            };

            IcmpEchoReplyLayer icmpReplyLayer = new IcmpEchoReplyLayer
            {
                Identifier     = (ushort)((icmpRequest.Variable >> 16) & 0xFFFF),
                SequenceNumber = (ushort)(icmpRequest.Variable & 0xFFFF),
            };

            PayloadLayer payloadLayer = new PayloadLayer()
            {
                Data = icmpRequest.Payload
            };


            if (_adapter.VLAN > 1)
            {
                VirtualNetwork.Instance.SendPacket(PacketBuilder.Build(DateTime.Now, ethernetLayer, vlanLayer, ipV4Layer, icmpReplyLayer, payloadLayer));
            }
            else
            {
                VirtualNetwork.Instance.SendPacket(PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, icmpReplyLayer, payloadLayer));
            }

            VirtualNetwork.Instance.PostTraceMessage("ICMP Reply: " + TargetIP.ToString());
        }
예제 #3
0
        private void GetIpProtocol(Packet packet, PacketInfo info)
        {
            switch (packet.Ethernet.IpV4.Protocol)
            {
            case IpV4Protocol.InternetControlMessageProtocol:
                IcmpDatagram icmp = packet.Ethernet.IpV4.Icmp;
                if (icmp != null)
                {
                    info.Protocol        = "ICMP";
                    info.Info            = "Echo (ping)";
                    info.Layers.ICMPInfo = $"Checksum: {icmp.Checksum}";
                }
                break;

            case IpV4Protocol.Tcp:
                var tcp = packet.Ethernet.IpV4.Tcp;
                info.Protocol = "TCP";
                info.Info     = $"{tcp.SourcePort} → {tcp.DestinationPort} [{GetFlags(tcp)}] " +
                                $"Seq={tcp.SequenceNumber} Win={tcp.Window} Len={tcp.Length}";
                /////////////// HTTP Request//////////////////
                var header = tcp.Http.Header;
                if (header != null)
                {
                    info.Protocol        = "HTTP";
                    info.Layers.HTTPInfo = "Header: " + header;
                }
                /////////////// TCP Layer//////////////////
                info.Layers.TCPInfo = $"Source Port: {tcp.SourcePort}\nDestination Port: {tcp.DestinationPort}" +
                                      $"\nSequence number: {tcp.SequenceNumber}\nNext sequence number: {tcp.NextSequenceNumber}" +
                                      $"\nAcknowledgement number: {tcp.AcknowledgmentNumber}\nHeader Length: {tcp.HeaderLength}" +
                                      $"\nWindow size value: {tcp.Window}\nChecksum: {tcp.Checksum}";
                break;

            case IpV4Protocol.Udp:
                UdpDatagram udp = packet.Ethernet.IpV4.Udp;
                info.Protocol       = "UDP";
                info.Info           = $"{udp.SourcePort} → {udp.DestinationPort} Len={udp.Length}";
                info.Layers.UDPInfo = $"Source Port: {udp.SourcePort}\nDestination Port: {udp.DestinationPort}" +
                                      $"\nLength: {udp.TotalLength}\nChecksum: {udp.Checksum}";
                break;

            case IpV4Protocol.InternetControlMessageProtocolForIpV6:
                info.Protocol = "ICMPv6";
                break;

            default:
                break;
            }
        }
예제 #4
0
        private void PacketHandler2(Packet packet)
        {
            // print timestamp and length of the packet
            richTextBox1.Text += (packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length + Environment.NewLine);

            IpV4Datagram ip   = packet.Ethernet.IpV4;
            IcmpDatagram icmp = ip.Icmp;
            UdpDatagram  udp  = ip.Udp;

            // print ip addresses and udp ports
            richTextBox1.Text += (ip.Source + ":" + packet.Ethernet.IpV6.Source + " -> " + ip.Destination + ":" + packet.Ethernet.IpV6.Source + Environment.NewLine);
            richTextBox1.Text += ("************************************************" + packet.Timestamp.Millisecond.ToString() + Environment.NewLine);
            richTextBox1.Text += ("************************************************" + icmp.MessageType + Environment.NewLine);

            richTextBox1.Text += ("************************************************" + Environment.NewLine);
        }
        protected override bool CompareField(XElement field, Datagram datagram)
        {
            IcmpDatagram icmpDatagram = (IcmpDatagram)datagram;

            switch (field.Name())
            {
            case "icmp.type":
                field.AssertShowDecimal((byte)icmpDatagram.MessageType);
                field.AssertNoFields();
                break;

            case "icmp.code":
                field.AssertShowDecimal(icmpDatagram.Code);
                field.AssertNoFields();
                break;

            case "icmp.checksum_bad":
                field.AssertShowDecimal(!icmpDatagram.IsChecksumCorrect);
                field.AssertNoFields();
                break;

            case "icmp.checksum":
                field.AssertShowDecimal(icmpDatagram.Checksum);
                field.AssertNoFields();
                break;

            case "data":
                var icmpIpV4PayloadDatagram = icmpDatagram as IcmpIpV4PayloadDatagram;
                if (icmpIpV4PayloadDatagram != null)
                {
                    IpV4Datagram ipV4 = icmpIpV4PayloadDatagram.IpV4;
                    switch (ipV4.Protocol)
                    {
                    case IpV4Protocol.Ip:
                        if (ipV4.Payload.Length < IpV4Datagram.HeaderMinimumLength)
                        {
                            field.AssertDataField(ipV4.Payload);
                        }
                        else
                        {
                            field.AssertDataField(ipV4.IpV4.Payload);
                        }
                        break;

                    case IpV4Protocol.Udp:

                        // Uncomment this when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10990 is fixed.
                        //                                field.AssertDataField(casted1.IpV4.Udp.Payload);
                        break;

                    case IpV4Protocol.IpComp:                          // TODO: Support IpComp.
                    case IpV4Protocol.Ax25:                            // TODO: Support Ax25.
                    case IpV4Protocol.FibreChannel:                    // TODO: Support FibreChannel.
                    case IpV4Protocol.MultiprotocolLabelSwitchingInIp: // TODO: Support MPLS.
                    case IpV4Protocol.EtherIp:                         // TODO: Support EtherIP.
                    case IpV4Protocol.LayerTwoTunnelingProtocol:       // TODO: Support LayerTwoTunnelingProtocol.
                    case IpV4Protocol.AuthenticationHeader:            // TODO: Support Authentication Header over IPv4.
                    case IpV4Protocol.UdpLite:                         // TODO: Support UdpLite.
                        break;

                    default:
                        if (icmpIpV4PayloadDatagram is IcmpIpV4HeaderPlus64BitsPayloadDatagram && field.Value().Length > 2 * 8)
                        {
                            Assert.AreEqual(ipV4.Payload.BytesSequenceToHexadecimalString(), field.Value().Substring(0, 2 * 8));
                        }
                        else
                        {
                            field.AssertDataField(ipV4.Payload);
                        }
                        break;
                    }
                }
                else
                {
                    field.AssertDataField(icmpDatagram.Payload);
                }
                break;

            case "":
                switch (icmpDatagram.MessageType)
                {
                case IcmpMessageType.ParameterProblem:
                    if (field.Show() != "Unknown session type")
                    {
                        field.AssertShow("Pointer: " + ((IcmpParameterProblemDatagram)icmpDatagram).Pointer);
                    }
                    break;

                case IcmpMessageType.RouterAdvertisement:
                    IcmpRouterAdvertisementDatagram routerAdvertisementDatagram = (IcmpRouterAdvertisementDatagram)icmpDatagram;
                    string fieldName = field.Show().Split(':')[0];
                    switch (fieldName)
                    {
                    case "Number of addresses":
                        field.AssertShow(fieldName + ": " + routerAdvertisementDatagram.NumberOfAddresses);
                        break;

                    case "Address entry size":
                        field.AssertShow(fieldName + ": " + routerAdvertisementDatagram.AddressEntrySize);
                        break;

                    case "Lifetime":
                        TimeSpan      actualLifetime       = routerAdvertisementDatagram.Lifetime;
                        StringBuilder actualLifetimeString = new StringBuilder(fieldName + ": ");
                        if (actualLifetime.Hours != 0)
                        {
                            actualLifetimeString.Append(actualLifetime.Hours + " hour");
                            if (actualLifetime.Hours != 1)
                            {
                                actualLifetimeString.Append('s');
                            }
                        }
                        if (actualLifetime.Minutes != 0)
                        {
                            if (actualLifetime.Hours != 0)
                            {
                                actualLifetimeString.Append(", ");
                            }
                            actualLifetimeString.Append(actualLifetime.Minutes + " minute");
                            if (actualLifetime.Minutes != 1)
                            {
                                actualLifetimeString.Append('s');
                            }
                        }
                        if (actualLifetime.Seconds != 0)
                        {
                            if (actualLifetime.Hours != 0 || actualLifetime.Minutes != 0)
                            {
                                actualLifetimeString.Append(", ");
                            }
                            actualLifetimeString.Append(actualLifetime.Seconds + " second");
                            if (actualLifetime.Seconds != 1)
                            {
                                actualLifetimeString.Append('s');
                            }
                        }
                        break;

                    case "Router address":
                        field.AssertShow(fieldName + ": " + routerAdvertisementDatagram.Entries[_routerIndex].RouterAddress);
                        break;

                    case "Preference level":
                        field.AssertShow(fieldName + ": " + routerAdvertisementDatagram.Entries[_routerIndex++].RouterAddressPreference);
                        break;

                    default:
                        throw new InvalidOperationException("Invalid icmp " + icmpDatagram.MessageType + " field " + fieldName);
                    }
                    break;
                }
                field.AssertNoFields();
                break;

            case "icmp.ident":
                ushort identifier = ((IcmpIdentifiedDatagram)icmpDatagram).Identifier;
                field.AssertShowDecimal(field.Showname().StartsWith("Identifier (BE): ") ? identifier : identifier.ReverseEndianity());
                field.AssertNoFields();
                break;

            case "icmp.seq":
                field.AssertShowDecimal(((IcmpIdentifiedDatagram)icmpDatagram).SequenceNumber);
                field.AssertNoFields();
                break;

            case "icmp.seq_le":
                byte[] sequenceNumberBuffer = new byte[sizeof(ushort)];
                sequenceNumberBuffer.Write(0, ((IcmpIdentifiedDatagram)icmpDatagram).SequenceNumber, Endianity.Big);
                ushort lowerEndianSequenceNumber = sequenceNumberBuffer.ReadUShort(0, Endianity.Small);
                field.AssertShowDecimal(lowerEndianSequenceNumber);
                field.AssertNoFields();
                break;

            case "icmp.redir_gw":
                field.AssertShow(((IcmpRedirectDatagram)icmpDatagram).GatewayInternetAddress.ToString());
                field.AssertNoFields();
                break;

            case "icmp.mtu":
                field.AssertShowDecimal(((IcmpDestinationUnreachableDatagram)icmpDatagram).NextHopMaximumTransmissionUnit);
                field.AssertNoFields();
                break;

            case "l2tp.l2_spec_def":
                field.AssertShow("");
                field.AssertNoFields();
                break;

            case "icmp.resp_to":
            case "icmp.resptime":
                break;

            case "icmp.length":
                // TODO: Uncomment this case when https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10939 is fixed.
//                    field.AssertShowDecimal(((IcmpParameterProblemDatagram)icmpDatagram).OriginalDatagramLength);
                break;

            default:
                if (!field.Name().StartsWith("lt2p.") &&
                    field.Name() != "pweth" &&
                    !field.Name().StartsWith("pweth."))
                {
                    throw new InvalidOperationException("Invalid icmp field " + field.Name());
                }
                break;
            }

            return(true);
        }
예제 #6
0
        public CustomPacket(Packet packet)
        {
            IpV4Datagram ip   = packet.Ethernet.IpV4;
            UdpDatagram  udp  = ip.Udp;
            TcpDatagram  tcp  = ip.Tcp;
            IcmpDatagram icmp = ip.Icmp;

            DateTime = packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff");

            PacketLength = packet.Length;
            string str = ip.Protocol.ToString();

            switch (str)
            {
            case "Tcp":
                ip_protocol = 1;
                break;

            case "Udp":
                ip_protocol = 2;
                break;

            case "Icmp":
                ip_protocol = 3;
                break;

            case "Igmp":
                ip_protocol = 4;
                break;

            default:
                ip_protocol = 0;
                break;
            }

            Source      = ip.Source.ToString();
            Destination = ip.Destination.ToString();

            ip_length         = ip.Length;
            ip_header_length  = ip.RealHeaderLength;
            ip_total_length   = ip.TotalLength;
            ip_ttl            = ip.Ttl;
            ip_service_type   = ip.TypeOfService;
            ip_header_version = ip.Version;

            udp_check_sum      = udp.Checksum;
            udp_dst_port       = udp.DestinationPort;
            udp_cs_is_optional = udp.IsChecksumOptional;
            udp_is_valid       = udp.IsValid;
            udp_scr_port       = udp.SourcePort;
            udp_total_length   = udp.TotalLength;

            tcp_check_sum      = tcp.Checksum;
            tcp_dst_port       = tcp.DestinationPort;
            tcp_header_length  = tcp.HeaderLength;
            tcp_is_ack         = tcp.IsAcknowledgment;
            tcp_cs_is_optional = tcp.IsChecksumOptional;
            tcp_is_cw_reduced  = tcp.IsCongestionWindowReduced;
            tcp_is_ecne        = tcp.IsExplicitCongestionNotificationEcho;
            tcp_is_nonce_sum   = tcp.IsNonceSum;
            tcp_is_fin         = tcp.IsFin;
            tcp_is_push        = tcp.IsPush;
            tcp_is_reset       = tcp.IsReset;
            tcp_is_syn         = tcp.IsSynchronize;
            tcp_is_urgent      = tcp.IsUrgent;
            tcp_is_valid       = tcp.IsValid;
            tcp_length         = tcp.Length;
            tcp_upointer       = tcp.UrgentPointer;
            tcp_window         = tcp.Window;

            icmp_length    = icmp.Length;
            icmp_is_valid  = icmp.IsValid;
            icmp_check_sum = icmp.IsChecksumCorrect;

            if (tcp.Http != null)
            {
                http_is_request  = tcp.Http.IsRequest;
                http_is_response = tcp.Http.IsResponse;
            }
            else
            {
                http_is_request  = false;
                http_is_response = false;
            }

            Data = CreateData();
        }
예제 #7
0
        protected override bool CompareField(XElement field, Datagram datagram)
        {
            IcmpDatagram icmpDatagram = (IcmpDatagram)datagram;

            switch (field.Name())
            {
            case "icmp.type":
                field.AssertShowDecimal((byte)icmpDatagram.MessageType);
                field.AssertNoFields();
                break;

            case "icmp.code":
                field.AssertShowDecimal(icmpDatagram.Code);
                field.AssertNoFields();
                break;

            case "icmp.checksum_bad":
                field.AssertShowDecimal(!icmpDatagram.IsChecksumCorrect);
                field.AssertNoFields();
                break;

            case "icmp.checksum":
                field.AssertShowHex(icmpDatagram.Checksum);
                field.AssertNoFields();
                break;

            case "data":
                var casted1 = icmpDatagram as IcmpIpV4HeaderPlus64BitsPayloadDatagram;
                if (casted1 != null)
                {
                    if (casted1.IpV4.Protocol != IpV4Protocol.IpComp)     // TODO: Support IpComp.
                    {
                        field.AssertDataField(casted1.IpV4.Payload);
                    }
                }
                else
                {
                    field.AssertDataField(icmpDatagram.Payload);
                }
                break;

            case "":
                switch (icmpDatagram.MessageType)
                {
                case IcmpMessageType.ParameterProblem:
                    if (field.Show() != "Unknown session type")
                    {
                        field.AssertShow("Pointer: " + ((IcmpParameterProblemDatagram)icmpDatagram).Pointer);
                    }
                    break;

                case IcmpMessageType.RouterAdvertisement:
                    IcmpRouterAdvertisementDatagram routerAdvertisementDatagram = (IcmpRouterAdvertisementDatagram)icmpDatagram;
                    string fieldName = field.Show().Split(':')[0];
                    switch (fieldName)
                    {
                    case "Number of addresses":
                        field.AssertShow(fieldName + ": " + routerAdvertisementDatagram.NumberOfAddresses);
                        break;

                    case "Address entry size":
                        field.AssertShow(fieldName + ": " + routerAdvertisementDatagram.AddressEntrySize);
                        break;

                    case "Lifetime":
                        TimeSpan      actualLifetime       = routerAdvertisementDatagram.Lifetime;
                        StringBuilder actualLifetimeString = new StringBuilder(fieldName + ": ");
                        if (actualLifetime.Hours != 0)
                        {
                            actualLifetimeString.Append(actualLifetime.Hours + " hour");
                            if (actualLifetime.Hours != 1)
                            {
                                actualLifetimeString.Append('s');
                            }
                        }
                        if (actualLifetime.Minutes != 0)
                        {
                            if (actualLifetime.Hours != 0)
                            {
                                actualLifetimeString.Append(", ");
                            }
                            actualLifetimeString.Append(actualLifetime.Minutes + " minute");
                            if (actualLifetime.Minutes != 1)
                            {
                                actualLifetimeString.Append('s');
                            }
                        }
                        if (actualLifetime.Seconds != 0)
                        {
                            if (actualLifetime.Hours != 0 || actualLifetime.Minutes != 0)
                            {
                                actualLifetimeString.Append(", ");
                            }
                            actualLifetimeString.Append(actualLifetime.Seconds + " second");
                            if (actualLifetime.Seconds != 1)
                            {
                                actualLifetimeString.Append('s');
                            }
                        }
                        break;

                    case "Router address":
                        field.AssertShow(fieldName + ": " + routerAdvertisementDatagram.Entries[_routerIndex].RouterAddress);
                        break;

                    case "Preference level":
                        field.AssertShow(fieldName + ": " + routerAdvertisementDatagram.Entries[_routerIndex++].RouterAddressPreference);
                        break;

                    default:
                        throw new InvalidOperationException("Invalid icmp " + icmpDatagram.MessageType + " field " + fieldName);
                    }
                    break;
                }
                field.AssertNoFields();
                break;

            case "icmp.ident":
                ushort identifier = ((IcmpIdentifiedDatagram)icmpDatagram).Identifier;
                field.AssertShowDecimal(field.Showname().StartsWith("Identifier (BE): ") ? identifier : identifier.ReverseEndianity());
                field.AssertNoFields();
                break;

            case "icmp.seq":
                field.AssertShowDecimal(((IcmpIdentifiedDatagram)icmpDatagram).SequenceNumber);
                field.AssertNoFields();
                break;

            case "icmp.seq_le":
                byte[] sequenceNumberBuffer = new byte[sizeof(ushort)];
                sequenceNumberBuffer.Write(0, ((IcmpIdentifiedDatagram)icmpDatagram).SequenceNumber, Endianity.Big);
                ushort lowerEndianSequenceNumber = sequenceNumberBuffer.ReadUShort(0, Endianity.Small);
                field.AssertShowDecimal(lowerEndianSequenceNumber);
                field.AssertNoFields();
                break;

            case "icmp.redir_gw":
                field.AssertShow(((IcmpRedirectDatagram)icmpDatagram).GatewayInternetAddress.ToString());
                field.AssertNoFields();
                break;

            case "icmp.mtu":
                field.AssertShowDecimal(((IcmpDestinationUnreachableDatagram)icmpDatagram).NextHopMaximumTransmissionUnit);
                field.AssertNoFields();
                break;

            case "l2tp.l2_spec_def":
                field.AssertShow("");
                field.AssertNoFields();
                break;

            case "icmp.resp_to":
            case "icmp.resptime":
                break;

            default:
                if (!field.Name().StartsWith("lt2p.") &&
                    !field.Name().StartsWith("pweth."))
                {
                    throw new InvalidOperationException("Invalid icmp field " + field.Name());
                }
                break;
            }

            return(true);
        }
예제 #8
0
        public void RandomIcmpTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = new MacAddress("00:01:02:03:04:05"),
                Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
            };

            int seed = new Random().Next();

            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 2000; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
                ipV4Layer.HeaderChecksum = null;
                Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(IpV4Protocol.InternetControlMessageProtocol, false);

                IcmpLayer icmpLayer = random.NextIcmpLayer();
                icmpLayer.Checksum = null;
                if (icmpLayer.MessageType == IcmpMessageType.DestinationUnreachable &&
                    icmpLayer.MessageTypeAndCode != IcmpMessageTypeAndCode.DestinationUnreachableFragmentationNeededAndDoNotFragmentSet)
                {
                    ((IcmpDestinationUnreachableLayer)icmpLayer).NextHopMaximumTransmissionUnit = 0;
                }

                IEnumerable <ILayer> icmpPayloadLayers = random.NextIcmpPayloadLayers(icmpLayer);

                int icmpPayloadLength = icmpPayloadLayers.Select(layer => layer.Length).Sum();

                switch (icmpLayer.MessageType)
                {
                case IcmpMessageType.ParameterProblem:
                    if (icmpPayloadLength % 4 != 0)
                    {
                        icmpPayloadLayers = icmpPayloadLayers.Concat(new[] { new PayloadLayer {
                                                                                 Data = random.NextDatagram(4 - icmpPayloadLength % 4)
                                                                             } });
                    }
                    icmpPayloadLength = icmpPayloadLayers.Select(layer => layer.Length).Sum();
                    IcmpParameterProblemLayer icmpParameterProblemLayer = (IcmpParameterProblemLayer)icmpLayer;
                    icmpParameterProblemLayer.Pointer = (byte)(icmpParameterProblemLayer.Pointer % icmpPayloadLength);
                    icmpParameterProblemLayer.OriginalDatagramLength = icmpPayloadLength - icmpPayloadLayers.First().Length;
                    break;

                case IcmpMessageType.SecurityFailures:
                    ((IcmpSecurityFailuresLayer)icmpLayer).Pointer %= (ushort)icmpPayloadLength;
                    break;
                }

                PacketBuilder packetBuilder = new PacketBuilder(new ILayer[] { ethernetLayer, ipLayer, icmpLayer }.Concat(icmpPayloadLayers));

                Packet packet = packetBuilder.Build(DateTime.Now);
                Assert.IsTrue(packet.IsValid, "IsValid");

                byte[] buffer = (byte[])packet.Buffer.Clone();
                buffer.Write(ethernetLayer.Length + ipLayer.Length, random.NextDatagram(icmpLayer.Length));
                Packet illegalPacket = new Packet(buffer, DateTime.Now, packet.DataLink);
                Assert.IsFalse(illegalPacket.IsValid, "IsInvalid");
                if (illegalPacket.Ethernet.Ip.Icmp is IcmpUnknownDatagram)
                {
                    byte[] icmpBuffer = new byte[illegalPacket.Ethernet.Ip.Icmp.ExtractLayer().Length];
                    ILayer layer      = illegalPacket.Ethernet.Ip.Icmp.ExtractLayer();
                    layer.Write(icmpBuffer, 0, icmpBuffer.Length, null, null);
                    layer.Finalize(icmpBuffer, 0, icmpBuffer.Length, null);
                    MoreAssert.AreSequenceEqual(illegalPacket.Ethernet.Ip.Icmp.ToArray(),
                                                icmpBuffer);

                    Assert.AreEqual(illegalPacket,
                                    PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, illegalPacket.Ethernet.Ip.Icmp.ExtractLayer()));
                }

                // Ethernet
                ethernetLayer.EtherType = ipLayer == ipV4Layer ? EthernetType.IpV4 : EthernetType.IpV6;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");
                ethernetLayer.EtherType = EthernetType.None;

                // IP.
                if (ipLayer == ipV4Layer)
                {
                    // IPv4.
                    ipV4Layer.Protocol       = IpV4Protocol.InternetControlMessageProtocol;
                    ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                    Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer());
                    ipV4Layer.HeaderChecksum = null;
                    Assert.AreEqual(ipV4Layer.Length, packet.Ethernet.IpV4.HeaderLength);
                    Assert.IsTrue(packet.Ethernet.IpV4.IsHeaderChecksumCorrect);
                    Assert.AreEqual(ipV4Layer.Length + icmpLayer.Length + icmpPayloadLength,
                                    packet.Ethernet.IpV4.TotalLength);
                    Assert.AreEqual(IpV4Datagram.DefaultVersion, packet.Ethernet.IpV4.Version);
                }
                else
                {
                    // IPv6.
                    Assert.AreEqual(ipLayer, packet.Ethernet.IpV6.ExtractLayer());
                }

                // ICMP
                IcmpDatagram actualIcmp      = packet.Ethernet.Ip.Icmp;
                IcmpLayer    actualIcmpLayer = (IcmpLayer)actualIcmp.ExtractLayer();
                icmpLayer.Checksum = actualIcmpLayer.Checksum;
                Assert.AreEqual(icmpLayer, actualIcmpLayer);
                Assert.AreEqual(icmpLayer.GetHashCode(), actualIcmpLayer.GetHashCode());
                if (actualIcmpLayer.MessageType != IcmpMessageType.RouterSolicitation)
                {
                    Assert.AreNotEqual(random.NextIcmpLayer(), actualIcmpLayer);
                    IcmpLayer otherIcmpLayer = random.NextIcmpLayer();
                    Assert.AreNotEqual(otherIcmpLayer.GetHashCode(), actualIcmpLayer.GetHashCode());
                }
                Assert.IsTrue(actualIcmp.IsChecksumCorrect);
                Assert.AreEqual(icmpLayer.MessageType, actualIcmp.MessageType);
                Assert.AreEqual(icmpLayer.CodeValue, actualIcmp.Code);
                Assert.AreEqual(icmpLayer.MessageTypeAndCode, actualIcmp.MessageTypeAndCode);
                Assert.AreEqual(packet.Length - ethernetLayer.Length - ipLayer.Length - IcmpDatagram.HeaderLength, actualIcmp.Payload.Length);
                Assert.IsNotNull(icmpLayer.ToString());

                switch (packet.Ethernet.Ip.Icmp.MessageType)
                {
                case IcmpMessageType.RouterSolicitation:
                case IcmpMessageType.SourceQuench:
                case IcmpMessageType.TimeExceeded:
                    Assert.AreEqual <uint>(0, actualIcmp.Variable);
                    break;

                case IcmpMessageType.DestinationUnreachable:
                case IcmpMessageType.ParameterProblem:
                case IcmpMessageType.Redirect:
                case IcmpMessageType.ConversionFailed:
                case IcmpMessageType.Echo:
                case IcmpMessageType.EchoReply:
                case IcmpMessageType.Timestamp:
                case IcmpMessageType.TimestampReply:
                case IcmpMessageType.InformationRequest:
                case IcmpMessageType.InformationReply:
                case IcmpMessageType.RouterAdvertisement:
                case IcmpMessageType.AddressMaskRequest:
                case IcmpMessageType.AddressMaskReply:
                    break;

                case IcmpMessageType.TraceRoute:
                    Assert.AreEqual(((IcmpTraceRouteLayer)icmpLayer).ReturnHopCount == 0xFFFF, ((IcmpTraceRouteDatagram)actualIcmp).IsOutbound);
                    break;

                case IcmpMessageType.DomainNameRequest:
                case IcmpMessageType.SecurityFailures:
                    break;

                case IcmpMessageType.DomainNameReply:
                default:
                    throw new InvalidOperationException("Invalid icmpMessageType " + packet.Ethernet.Ip.Icmp.MessageType);
                }
            }
        }
예제 #9
0
 public void IcmpDatagramCreateDatagramBadOffsetTest()
 {
     Assert.IsInstanceOfType(IcmpDatagram.CreateDatagram(new byte[0], -1, 0), typeof(IcmpUnknownDatagram));
 }
예제 #10
0
 public void IcmpDatagramCreateDatagramNullBufferTest()
 {
     Assert.IsNotNull(IcmpDatagram.CreateDatagram(null, 0, 0));
     Assert.Fail();
 }
예제 #11
0
        //hàm xử lý live
        private void PacketHandler(Packet packet)
        {
            this.count = ""; this.time = ""; this.source = ""; this.destination = ""; this.protocol = ""; this.length = "";

            this.tcpack = ""; this.tcpsec = ""; this.tcpnsec = ""; this.tcpsrc = ""; this.tcpdes = ""; this.udpscr = "";

            this.udpdes = ""; this.httpheader = ""; this.httpver = ""; this.httplen = ""; this.reqres = ""; this.httpbody = "";

            this.infor = "";
            if (no == 0)
            {
                InformationPacket(packet);
            }
            IpV4Datagram ip         = packet.Ethernet.IpV4;
            TcpDatagram  tcp        = ip.Tcp;
            UdpDatagram  udp        = ip.Udp;
            HttpDatagram httpPacket = null;
            IcmpDatagram icmp       = ip.Icmp;

            protocol = ip.Protocol.ToString();
            if (ip.Protocol.ToString().Equals("Tcp"))
            {
                httpPacket = tcp.Http;

                if ((httpPacket.Header != null))
                {
                    protocol         = "Http";
                    httpheader       = httpPacket.Header.ToString();
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    httpver          = httpPacket.Version.ToString();
                    httplen          = httpPacket.Length.ToString();
                    if ((httpPacket.Body != null) /* && (!_tcp.Checked)*/)
                    {
                        httpbody = httpPacket.Body.ToString();
                    }
                    if (httpPacket.IsRequest)
                    {
                        reqres = "Request";
                    }
                    else
                    {
                        reqres = "Response";
                    }
                }

                else
                {
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    protocol         = ip.Protocol.ToString();
                    tcpsrc           = tcp.SourcePort.ToString();
                    tcpdes           = tcp.DestinationPort.ToString();
                    tcpack           = tcp.AcknowledgmentNumber.ToString();
                    tcpsec           = tcp.SequenceNumber.ToString();
                    tcpnsec          = tcp.NextSequenceNumber.ToString();
                    tcpwin           = tcp.Window.ToString();
                    tcplen           = tcp.Length.ToString();
                    tcp.Length.ToString();
                    infor = tcpsrc + "->" + tcpdes + " Seq=" + tcpsec + " win=" + tcpwin + " Ack= " + tcpack + " LEN= " + tcplen;
                }
            }
            else
            {
                if (ip.Protocol.ToString().Equals("Udp"))
                {
                    if (udp.DestinationPort.ToString().Equals(53))
                    {
                        protocol = "dns";
                    }
                    else
                    {
                        count            = packet.Count.ToString();
                        time             = packet.Timestamp.ToString();
                        this.source      = ip.Source.ToString();
                        this.destination = ip.Destination.ToString();
                        length           = ip.Length.ToString();
                        protocol         = ip.Protocol.ToString();
                        udpscr           = udp.SourcePort.ToString();
                        udpdes           = udp.DestinationPort.ToString();
                    }
                }

                else
                {
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.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) //not syn or ack
                {
                    payload = new byte[tcp.PayloadLength];
                    tcp.Payload.ToMemoryStream().Read(payload, 0, tcp.PayloadLength); // read payload from 0 to length
                    if (_destination == 80)                                           // request from server
                    {
                        Packet1 packet1 = new Packet1();
                        if (payload.Count() > 1)
                        {
                            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(@"D:\captured\" + Directory.CreateDirectory(Path.GetFileName(packet1.Name)), FileMode.Create)))
                            //        {
                            //            writer.Write(packet1.Data);

                            //        }

                            //        packets.Remove(_destination);

                            //    }
                        }
                    }
                }
            }
            if (!count.Equals(""))
            {
                no++;
                ListViewItem item = new ListViewItem(no.ToString());
                item.SubItems.Add(time);
                item.SubItems.Add(source);
                item.SubItems.Add(destination);
                item.SubItems.Add(protocol);
                item.SubItems.Add(length);
                item.SubItems.Add(infor);
                item.Tag = packet;
                SetText(item);
            }
        }
예제 #12
0
        //ham xu ly offlive
        private void DispatcherHandler(Packet packet)
        {
            this.count = ""; this.time = ""; this.source = ""; this.destination = ""; this.protocol = ""; this.length = "";

            this.tcpack = ""; this.tcpsec = ""; this.tcpnsec = ""; this.tcpsrc = ""; this.tcpdes = ""; this.udpscr = "";

            this.udpdes = ""; this.httpheader = ""; this.httpver = ""; this.httplen = ""; this.reqres = ""; this.httpbody = "";

            this.infor = "";
            IpV4Datagram ip         = packet.Ethernet.IpV4;
            TcpDatagram  tcp        = ip.Tcp;
            UdpDatagram  udp        = ip.Udp;
            HttpDatagram httpPacket = null;
            IcmpDatagram icmp       = ip.Icmp;

            if (ip.Protocol.ToString().Equals("Tcp"))
            {
                httpPacket = tcp.Http;//Initialize http variable only if the packet was tcp

                if ((httpPacket.Header != null) /* && (!_tcp.Checked)*/)
                {
                    protocol         = "Http";
                    httpheader       = httpPacket.Header.ToString();
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    httpver          = httpPacket.Version.ToString();
                    httplen          = httpPacket.Length.ToString();
                    if ((httpPacket.Body != null) /* && (!_tcp.Checked)*/)
                    {
                        httpbody = httpPacket.Body.ToString();
                    }
                    if (httpPacket.IsRequest)
                    {
                        reqres = "Request";
                    }
                    else
                    {
                        reqres = "Response";
                    }
                }

                else
                {
                    count            = packet.Count.ToString();
                    time             = packet.Timestamp.ToString();
                    this.source      = ip.Source.ToString();
                    this.destination = ip.Destination.ToString();
                    length           = ip.Length.ToString();
                    protocol         = ip.Protocol.ToString();
                    tcpsrc           = tcp.SourcePort.ToString();
                    tcpdes           = tcp.DestinationPort.ToString();
                    tcpack           = tcp.AcknowledgmentNumber.ToString();
                    tcpsec           = tcp.SequenceNumber.ToString();
                    tcpnsec          = tcp.NextSequenceNumber.ToString();
                    tcpwin           = tcp.Window.ToString();
                    tcplen           = tcp.Length.ToString();
                    tcp.Length.ToString();
                    infor = tcpsrc + "->" + tcpdes + " Seq=" + tcpsec + " win=" + tcpwin + " Ack= " + tcpack + " LEN= " + tcplen;
                }
            }
            else
            {
                if (ip.Protocol.ToString().Equals("Udp"))
                {
                    if (udp.DestinationPort.ToString().Equals(53))
                    {
                        protocol = "dns";
                    }
                    else
                    {
                        count            = packet.Count.ToString();
                        time             = packet.Timestamp.ToString();
                        this.source      = ip.Source.ToString();
                        this.destination = ip.Destination.ToString();
                        length           = ip.Length.ToString();
                        protocol         = ip.Protocol.ToString();
                        udpscr           = udp.SourcePort.ToString();
                        udpdes           = udp.DestinationPort.ToString();
                    }
                }

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

            if (!count.Equals(""))
            {
                no++;
                ListViewItem item = new ListViewItem(no.ToString());
                item.SubItems.Add(time);
                item.SubItems.Add(source);
                item.SubItems.Add(destination);
                item.SubItems.Add(protocol);
                item.SubItems.Add(length);
                item.SubItems.Add(infor);
                item.Tag = packet;
                SetText(item);
            }
        }
예제 #13
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))                                  // время чтения
            {
                // Установка фильтра на udp Пакеты
                using (var filter = communicator.CreateFilter("ip and icmp"))
                {
                    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;
                            IcmpDatagram icmp = ip.Icmp;

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

                            // unusual fields

                            StringBuilder properties = new StringBuilder();

                            // Контрольная сумма icmp пакета
                            properties.AppendLine("Checksum : " + icmp.Checksum.ToString());
                            // Формат хранимых данных
                            properties.AppendLine("MessageType : " + icmp.MessageType.ToString());
                            // Сведения о сообщении передаваемом пакетом
                            properties.AppendLine("MessageTypeAndCode : " + icmp.MessageTypeAndCode.ToString());
                            // Специальное значение передаваемое пакетом
                            properties.AppendLine("Variable : " + icmp.Variable.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);
        }
예제 #14
0
 private void MapIcmpData(IcmpDatagram datagram)
 {
     this.Protocol = PacketProtocol.Icmp;
     throw new NotImplementedException("Icmp");
 }