Esempio n. 1
1
            public void ReceivePackets()
            {
                // Retrieve the device list from the local machine
                IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

                // Find the NPF device of the TAP interface
                PacketDevice selectedDevice = null;
                for (int i = 0; i != allDevices.Count; ++i)
                {
                    LivePacketDevice device = allDevices[i];
                    if (device.Name.ToUpper().Contains(Guid.ToString().ToUpper()))
                    {
                        selectedDevice = device;
                        break;
                    }
                }

                if (selectedDevice == null)
                {
                    Initialized.Set();
                    Global.ShowTrayTip("Load Balancer", "Interface " + Name + " not captured by WinPcap.", System.Windows.Forms.ToolTipIcon.Warning);
                    Global.WriteLog("Load Balancer: Interface " + Name + " not captured by WinPcap.");
                    return;
                }

                try
                {
                    using (communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.MaximumResponsiveness, 1000))
                    {
                        Global.WriteLog("Load Balancer: Listening on " + Name + "...");
                        communicator.SetFilter("(ether dst " + ownHardwareAddressString + " and ((ip and (tcp or udp or icmp)) or arp)) or (ether dst FF:FF:FF:FF:FF:FF and arp)");
                        Initialized.Set();
                        communicator.ReceivePackets(0, (packet) =>
                        {
                            if (!ThreadActive.IsSet)
                            {
                                communicator.Break();
                                return;
                            }
                            if (packet.Ethernet.EtherType == EthernetType.Arp)
                            {
                                if (packet.Ethernet.Arp.TargetProtocolAddress.SequenceEqual(ownProtocolAddressByte) && packet.Ethernet.Arp.Operation == ArpOperation.Request)
                                {
                                    EthernetLayer ethernetLayer = new EthernetLayer
                                    {
                                        Source = ownHardwareAddress,
                                        Destination = packet.Ethernet.Source,
                                        EtherType = EthernetType.None,
                                    };

                                    ArpLayer arpLayer = new ArpLayer
                                    {
                                        ProtocolType = EthernetType.IpV4,
                                        Operation = ArpOperation.Reply,
                                        SenderHardwareAddress = ownHardwareAddressByte.AsReadOnly(),
                                        SenderProtocolAddress = packet.Ethernet.Arp.TargetProtocolAddress,
                                        TargetHardwareAddress = packet.Ethernet.Arp.SenderHardwareAddress,
                                        TargetProtocolAddress = packet.Ethernet.Arp.SenderProtocolAddress,
                                    };

                                    PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);
                                    SendPacket(builder.Build(DateTime.Now));
                                }
                            }
                            else if (packet.Ethernet.EtherType.ToString() == "IpV4")
                            {

                                if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.DoNotFragment ||
                                    packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset == 0)
                                {
                                    IpV4Handler(packet);
                                }
                                else if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.MoreFragments ||
                                    packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset > 0)
                                {
                                    // TODO: fix warning spam
                                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                                        Global.ShowTrayTip("Load Balancer", "IP fragmentation detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                                    Global.WriteLog("Load Balancer: IP fragmentation detected on " + Name);
                                    //fragments = fragBuffer.Add(packet);
                                    //if (fragments != null)
                                    //    for (int i = 0; i < fragments.Count; i++)
                                    //    {
                                    //        IpV4Handler(fragments[i], fragments);
                                    //    }
                                }
                            }
                        });
                    }
                }
                catch (Exception e)
                {
                    if (ThreadActive.IsSet)
                    {
                        ThreadActive.Reset();
                        Global.WriteLog("Load Balancer: " + Name + " has disconnected");
                        if (Global.Config.Gadget.Debug)
                            Global.WriteLog(e.ToString());
                        Global.ShowTrayTip("Load Balancer", Name + " has disconnected", System.Windows.Forms.ToolTipIcon.Warning);
                    }
                }
            }
Esempio n. 2
0
        public void RandomArpTest()
        {
            Random random = new Random();

            for (int i = 0; i != 1000; ++i)
            {
                MacAddress ethernetSource = random.NextMacAddress();
                EthernetLayer ethernetLayer = new EthernetLayer
                                                  {
                                                      Source = ethernetSource,
                                                  };

                ArpLayer arpLayer = random.NextArpLayer();

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, arpLayer);

                Assert.IsTrue(packet.IsValid, "IsValid");

                // Ethernet
                Assert.AreEqual(packet.Length - EthernetDatagram.HeaderLengthValue, packet.Ethernet.PayloadLength, "PayloadLength");

                Assert.AreEqual(ethernetSource, packet.Ethernet.Source, "Ethernet Source");
                Assert.AreEqual(EthernetDatagram.BroadcastAddress, packet.Ethernet.Destination, "Ethernet Destination");
                Assert.AreEqual(EthernetType.Arp, packet.Ethernet.EtherType, "Ethernet EtherType");

                // Arp
                Assert.AreEqual(ArpDatagram.HeaderBaseLength + 2 * arpLayer.SenderHardwareAddress.Count + 2 * arpLayer.SenderProtocolAddress.Count, packet.Ethernet.Arp.Length, "Arp length");
                Assert.AreEqual(ArpHardwareType.Ethernet, packet.Ethernet.Arp.HardwareType, "Arp hardware type");
                Assert.AreEqual(arpLayer, packet.Ethernet.Arp.ExtractLayer(), "ARP Layer");
                Assert.AreNotEqual(arpLayer, random.NextArpLayer(), "ARP Layer");
                Assert.AreEqual(arpLayer.GetHashCode(), packet.Ethernet.Arp.ExtractLayer().GetHashCode(), "ARP Layer");
                ArpLayer differentArpLayer = random.NextArpLayer();
                Assert.AreNotEqual(arpLayer.GetHashCode(), differentArpLayer.GetHashCode(), "ARP Layer");
            }
        }
Esempio n. 3
0
        //Create a base packet to use as parent for the other classes
        public virtual void GetBase(string MACsrc, string MACdst, string IPsrc, string IPdst,
            string IpId, string TTL)
        {
            // Ethernet Layer
            ethernetLayer = new EthernetLayer
            {
                Source = new MacAddress(MACsrc),
                Destination = new MacAddress(MACdst),
                // Set ethernet type
                EtherType = EthernetType.None
            };

            // IpV4 Layer
            ipV4Layer = new IpV4Layer
            {
                Source = new IpV4Address(IPsrc),
                CurrentDestination = new IpV4Address(IPdst),
                Fragmentation = IpV4Fragmentation.None,
                HeaderChecksum = null, // Will be filled automatically.
                Identification = StringToUShort(IpId),
                Options = IpV4Options.None,
                Protocol = null, // Will be filled automatically.
                Ttl = StringToByte(TTL),
                TypeOfService = 0,
            };
        }
Esempio n. 4
0
        public void RandomUdpTest()
        {
            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 != 1000; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
                ipV4Layer.HeaderChecksum = null;
                IpV6Layer ipV6Layer = random.NextIpV6Layer(IpV4Protocol.Udp, false);

                EthernetType ethernetType = random.NextBool() ? EthernetType.IpV4 : EthernetType.IpV6;
                Layer ipLayer = (ethernetType == EthernetType.IpV4 ? (Layer)ipV4Layer : ipV6Layer);
                UdpLayer udpLayer = random.NextUdpLayer();
                udpLayer.Checksum = null;

                PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(60000));

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, udpLayer, payloadLayer);

                Assert.IsTrue(packet.IsValid, "IsValid");

                // Ethernet
                ethernetLayer.EtherType = ethernetType;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");
                ethernetLayer.EtherType = EthernetType.None;

                // Ip
                if (ipLayer == ipV4Layer)
                {
                    // IpV4.
                    ipV4Layer.Protocol = IpV4Protocol.Udp;
                    ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                    Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IP Layer");
                    ipV4Layer.HeaderChecksum = null;
                }
                else
                {
                    // IpV6.
                    Assert.AreEqual(ipV6Layer, packet.Ethernet.IpV6.ExtractLayer(), "IP Layer");
                }

                // UDP
                udpLayer.Checksum = packet.Ethernet.Ip.Udp.Checksum;
                Assert.AreEqual(udpLayer, packet.Ethernet.Ip.Udp.ExtractLayer(), "UDP Layer");
                Assert.AreEqual(UdpDatagram.HeaderLength + payloadLayer.Length, packet.Ethernet.Ip.Udp.TotalLength, "Total Length");
                Assert.IsTrue(!udpLayer.CalculateChecksum && packet.Ethernet.Ip.Udp.Checksum == 0 ||
                              udpLayer.CalculateChecksum && packet.Ethernet.Ip.IsTransportChecksumCorrect, "IsTransportChecksumCorrect");
                Assert.IsTrue(packet.Ethernet.Ip.Udp.IsChecksumOptional, "IsChecksumOptional");
                Assert.AreEqual(payloadLayer.Data, packet.Ethernet.Ip.Udp.Payload, "Payload");
            }
        }
Esempio n. 5
0
 public bool Equals(EthernetLayer other)
 {
     if (other != null && this.Source == other.Source && this.Destination == other.Destination)
     {
         return(this.EtherType == other.EtherType);
     }
     return(false);
 }
Esempio n. 6
0
        public void RandomDnsTest()
        {
            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 != 1000; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
                ipV4Layer.HeaderChecksum = null;
                Layer ipLayer = random.NextBool() ? (Layer)ipV4Layer : random.NextIpV6Layer(true);

                UdpLayer udpLayer = random.NextUdpLayer();
                udpLayer.Checksum = null;

                DnsLayer dnsLayer;
                do
                {
                    dnsLayer = random.NextDnsLayer();
                } while (dnsLayer.Length > 65000 - ipLayer.Length);

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, udpLayer, dnsLayer);

                Assert.IsTrue(packet.IsValid, "IsValid");

                // DNS
                DnsLayer actualLayer = (DnsLayer)packet.Ethernet.Ip.Udp.Dns.ExtractLayer();
                Assert.AreEqual(dnsLayer, actualLayer, "DNS Layer");
                Assert.IsTrue(packet.Ethernet.Ip.Udp.Dns.IsValid);

                DnsDataResourceRecord opt = packet.Ethernet.Ip.Udp.Dns.Additionals.FirstOrDefault(additional => additional.DnsType == DnsType.Opt);
                Assert.AreEqual(opt, packet.Ethernet.Ip.Udp.Dns.OptionsRecord);

                foreach (var record in packet.Ethernet.Ip.Udp.Dns.ResourceRecords)
                {
                    Assert.IsTrue(record.Equals(record));
                    Assert.IsTrue(record.DomainName.Equals((object)record.DomainName));
                    Assert.IsTrue(record.DomainName.Equals((object)record.DomainName));
                    Assert.AreEqual(record.GetHashCode(), record.GetHashCode());
                }

                foreach (var record in packet.Ethernet.Ip.Udp.Dns.DataResourceRecords)
                {
                    MoreAssert.IsBiggerOrEqual(9, record.ToString().Length);
                    Assert.IsTrue(record.Equals((object)record));
                    Assert.IsInstanceOfType(record.Data, DnsResourceData.GetDnsResourceDataType(record.DnsType) ?? typeof(DnsResourceDataAnything));
                    Assert.IsTrue(record.DomainName.Equals((object)record.DomainName));
                    Assert.IsFalse(record.Data.Equals(null));
                }
            }
        }
Esempio n. 7
0
        public override ILayer ExtractLayer()
        {
            EthernetLayer ethernetLayer = new EthernetLayer();

            ethernetLayer.Source      = this.Source;
            ethernetLayer.Destination = this.Destination;
            ethernetLayer.EtherType   = this.EtherType;
            return((ILayer)ethernetLayer);
        }
Esempio n. 8
0
        public void RandomUdpTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("00:01:02:03:04:05"),
                                                  Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
                                              };

            Random random = new Random();

            IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
            ipV4Layer.HeaderChecksum = null;

            for (int i = 0; i != 1000; ++i)
            {
                UdpLayer udpLayer = random.NextUdpLayer();
                udpLayer.Checksum = null;

                PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(60000));

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, udpLayer, payloadLayer);

                Assert.IsTrue(packet.IsValid, "IsValid");

                // Ethernet
                ethernetLayer.EtherType = EthernetType.IpV4;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");

                // IpV4
                ipV4Layer.Protocol = IpV4Protocol.Udp;
                ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IP Layer");
                ipV4Layer.HeaderChecksum = null;

                // UDP
                udpLayer.Checksum = packet.Ethernet.IpV4.Udp.Checksum;
                Assert.AreEqual(udpLayer, packet.Ethernet.IpV4.Udp.ExtractLayer(), "UDP Layer");
                Assert.AreEqual(UdpDatagram.HeaderLength + payloadLayer.Length, packet.Ethernet.IpV4.Udp.TotalLength, "Total Length");
                Assert.IsTrue(!udpLayer.CalculateChecksum && packet.Ethernet.IpV4.Udp.Checksum == 0 ||
                              udpLayer.CalculateChecksum && packet.Ethernet.IpV4.IsTransportChecksumCorrect, "IsTransportChecksumCorrect");
                Assert.IsTrue(packet.Ethernet.IpV4.Udp.IsChecksumOptional, "IsChecksumOptional");
                Assert.AreEqual(payloadLayer.Data, packet.Ethernet.IpV4.Udp.Payload, "Payload");
            }
        }
Esempio n. 9
0
 public OwnPacketBuilder(PacketType packetType)
 {
     GetLocalInformation.LocalMacAndIPAddress( out _ownIpAddress, out _ownMacAddress );
     ethernetLayer = null;
     ipV4Layer = null;
     tcpLayer = null;
     arpLayer = null;
     switch(packetType)
     {
         case PacketType.ARP :
             BuildingArpPacket();
             break;
         case PacketType.TCP :
             BuildingTcpPacket();
             break;
         case PacketType.Unknown :
             break;
         default :
             break;
     }
 }
Esempio n. 10
0
        /// <summary>
        /// This function build an ICMP over IPv4 over Ethernet packet.
        /// </summary>
        public Packet BuildIcmpPacket( string TargetIpAddress, string RouterMacAddress )
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                {
                    Source = new MacAddress( ToMac( _ownMacAddress.ToString() ) ),
                    Destination = new MacAddress( ToMac( RouterMacAddress.ToString() ) ),
                    EtherType = EthernetType.None, // Will be filled automatically.
                };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                {
                    Source = new IpV4Address( new IPAddress( _ownIpAddress ).ToString() ),
                    CurrentDestination = new IpV4Address( TargetIpAddress ),
                    Fragmentation = IpV4Fragmentation.None,
                    HeaderChecksum = null, // Will be filled automatically.
                    Identification = 123,
                    Options = IpV4Options.None,
                    Protocol = null, // Will be filled automatically.
                    Ttl = 100,
                    TypeOfService = 0,
                };

            IcmpEchoLayer icmpLayer =
                new IcmpEchoLayer
                {
                    Checksum = null, // Will be filled automatically.
                    Identifier = 456,
                    SequenceNumber = 800,
                };

            PacketBuilder builder = new PacketBuilder( ethernetLayer, ipV4Layer, icmpLayer );

            return builder.Build( DateTime.Now );
        }
Esempio n. 11
0
            public void IpV4Handler(Packet packet, IList<Packet> packetList = null)
            {
                if (packet.Ethernet.IpV4.Length > MTU)
                {
                    EthernetLayer ethernetLayer = new EthernetLayer
                    {
                        Source = ownHardwareAddress,
                        Destination = packet.Ethernet.Source,
                        EtherType = EthernetType.None,
                    };
                    IpV4Layer ipV4Layer = new IpV4Layer
                    {
                        Source = packet.Ethernet.IpV4.Destination,
                        CurrentDestination = packet.Ethernet.IpV4.Source,
                        Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = packet.Ethernet.IpV4.Options,
                        Protocol = packet.Ethernet.IpV4.Protocol,
                        Ttl = packet.Ethernet.IpV4.Ttl,
                        TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                    };
                    IcmpDestinationUnreachableLayer icmpLayer = new IcmpDestinationUnreachableLayer
                    {
                        Code = IcmpCodeDestinationUnreachable.FragmentationNeededAndDoNotFragmentSet,
                        NextHopMaximumTransmissionUnit = (ushort)MTU,
                    };

                    PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);
                    SendPacket(builder.Build(DateTime.Now));
                    // TODO: fix warning spam
                    if (Global.Config.LoadBalancer.ShowTrayTipsWarnings)
                        Global.ShowTrayTip("Load Balancer", "IP packet larger than the MTU detected on " + Name + ".\n\nIP fragmentation is not supported.", ToolTipIcon.Warning);
                    Global.WriteLog("Load Balancer: IP packet larger than the MTU detected on " + Name);
                    return;
                }
                if (packet.Ethernet.IpV4.Ttl < 2)
                {
                    EthernetLayer ethernetLayer = new EthernetLayer
                    {
                        Source = ownHardwareAddress,
                        Destination = packet.Ethernet.Source,
                        EtherType = EthernetType.None,
                    };
                    IpV4Layer ipV4Layer = new IpV4Layer
                    {
                        Source = ownProtocolAddress,
                        CurrentDestination = packet.Ethernet.IpV4.Source,
                        Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = packet.Ethernet.IpV4.Options,
                        Protocol = packet.Ethernet.IpV4.Protocol,
                        Ttl = packet.Ethernet.IpV4.Ttl,
                        TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                    };
                    IcmpTimeExceededLayer icmpLayer = new IcmpTimeExceededLayer
                    {
                        Code = 0,
                    };

                    PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer, packet.Ethernet.IpV4.ExtractLayer(), packet.Ethernet.IpV4.Payload.ExtractLayer());
                    SendPacket(builder.Build(DateTime.Now));
                    return;
                }
                if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.InternetControlMessageProtocol)
                {
                    if (packet.Ethernet.IpV4.Destination == ownProtocolAddress)
                    {
                        if ((packet.Ethernet.IpV4.Icmp.MessageType == IcmpMessageType.Echo || packet.Ethernet.IpV4.Fragmentation.Offset > 0))
                        {
                            EthernetLayer ethernetLayer = new EthernetLayer
                            {
                                Source = ownHardwareAddress,
                                Destination = packet.Ethernet.Source,
                                EtherType = EthernetType.None,
                            };
                            IpV4Layer ipV4Layer = new IpV4Layer
                            {
                                Source = packet.Ethernet.IpV4.Destination,
                                CurrentDestination = packet.Ethernet.IpV4.Source,
                                Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                HeaderChecksum = null, // Will be filled automatically.
                                Identification = 123,
                                Options = packet.Ethernet.IpV4.Options,
                                Protocol = packet.Ethernet.IpV4.Protocol,
                                Ttl = packet.Ethernet.IpV4.Ttl,
                                TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                            };
                            if (packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.DoNotFragment ||
                                packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.None && packet.Ethernet.IpV4.Fragmentation.Offset == 0)
                            {
                                byte[] icmpPacket = packet.Ethernet.IpV4.Payload.ToArray();
                                icmpPacket[0] = 0;
                                icmpPacket[2] = 0;
                                icmpPacket[3] = 0;
                                ushort checksum = IpFunctions.ComputeIpChecksum(icmpPacket);
                                icmpPacket[2] = (byte)(checksum >> 8);
                                icmpPacket[3] = (byte)(checksum & 0xff);
                                PayloadLayer payloadLayer = new PayloadLayer
                                {
                                    Data = new Datagram(icmpPacket),
                                };
                                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer);
                                SendPacket(builder.Build(DateTime.Now));
                            }
                            else if (packet.Ethernet.IpV4.Fragmentation.Offset == 0 && packet.Ethernet.IpV4.Fragmentation.Options == IpV4FragmentationOptions.MoreFragments)
                            {
                                byte[] icmpHeader = packet.Ethernet.IpV4.Payload.ToArray();
                                icmpHeader[0] = 0;
                                icmpHeader[2] = 0;
                                icmpHeader[3] = 0;
                                int icmpPacketLength = icmpHeader.Length;
                                for (int i = 1; i < packetList.Count; i++)
                                {
                                    icmpPacketLength += packetList[i].Ethernet.IpV4.Payload.ToArray().Length;
                                }
                                byte[] icmpPacket = new byte[icmpPacketLength];
                                Buffer.BlockCopy(icmpHeader, 0, icmpPacket, 0, icmpHeader.Length);
                                icmpPacketLength = icmpHeader.Length;
                                for (int i = 1; i < packetList.Count; i++)
                                {
                                    Buffer.BlockCopy(packetList[i].Ethernet.IpV4.Payload.ToArray(), 0, icmpPacket, icmpPacketLength, packetList[i].Ethernet.IpV4.Payload.ToArray().Length);
                                    icmpPacketLength += packetList[i].Ethernet.IpV4.Payload.ToArray().Length;
                                }
                                ushort checksum = IpFunctions.ComputeIpChecksum(icmpPacket);
                                icmpHeader[2] = (byte)(checksum >> 8);
                                icmpHeader[3] = (byte)(checksum & 0xff);
                                PayloadLayer payloadLayer = new PayloadLayer
                                {
                                    Data = new Datagram(icmpHeader),
                                };
                                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer);
                                SendPacket(builder.Build(DateTime.Now));
                            }
                            else
                            {
                                PayloadLayer payloadLayer = new PayloadLayer
                                {
                                    Data = new Datagram(packet.Ethernet.IpV4.Payload.ToArray()),
                                };
                                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer);
                                SendPacket(builder.Build(DateTime.Now));
                            }
                        }
                    }
                    else if (packet.Ethernet.IpV4.Source == ifProtocolAddress)
                        if ((packet.Ethernet.IpV4.Icmp.MessageType == IcmpMessageType.Echo || packet.Ethernet.IpV4.Fragmentation.Offset > 0))
                        {
                            {
                                tapRoutingObject = RoutingTable.GetInterface(packet);
                                if (tapRoutingObject.response == -1)
                                    return;
                                EthernetLayer ethernetLayer = new EthernetLayer
                                {
                                    Source = physicalWorkers[tapRoutingObject.ifIndex].ifHardwareAddress,
                                    Destination = physicalWorkers[tapRoutingObject.ifIndex].gatewayHardwareAddress,
                                    EtherType = EthernetType.None,
                                };
                                IpV4Layer ipV4Layer = new IpV4Layer
                                {
                                    Source = physicalWorkers[tapRoutingObject.ifIndex].ifProtocolAddress,
                                    CurrentDestination = packet.Ethernet.IpV4.Destination,
                                    Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                                    HeaderChecksum = null, // Will be filled automatically.
                                    Identification = packet.Ethernet.IpV4.Identification,
                                    Options = packet.Ethernet.IpV4.Options,
                                    Protocol = packet.Ethernet.IpV4.Protocol,
                                    Ttl = (byte)(packet.Ethernet.IpV4.Ttl - 1),
                                    TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                                };
                                PayloadLayer payloadLayer = new PayloadLayer
                                {
                                    Data = new Datagram(packet.Ethernet.IpV4.Payload.ToArray()),
                                };
                                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer);
                                physicalWorkers[tapRoutingObject.ifIndex].SendPacket(builder.Build(DateTime.Now));
                            }
                        }
                }
                else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
                {
                    if (packet.Ethernet.IpV4.Source == ifProtocolAddress)
                    {
                        tapRoutingObject = RoutingTable.GetInterface(packet);
                        if (tapRoutingObject.response == -1)
                            return;
                        if (tapRoutingObject.response == -3)
                        {
                            lock (RoutingTable.connParams[tapRoutingObject.guid])
                                SendAck(tapRoutingObject.guid);
                            return;
                        }
                        lock (RoutingTable.connParams[tapRoutingObject.guid])
                        {
                            RoutingTable.connParams[tapRoutingObject.guid].freeWindow = (int)((packet.Ethernet.IpV4.Tcp.Window << RoutingTable.connParams[tapRoutingObject.guid].windowScale) - (RoutingTable.connParams[tapRoutingObject.guid].seq - packet.Ethernet.IpV4.Tcp.AcknowledgmentNumber));
                            if (RoutingTable.connParams[tapRoutingObject.guid].windowFull)
                            {
                                if (RoutingTable.connParams[tapRoutingObject.guid].freeWindow > RoutingTable.connParams[tapRoutingObject.guid].bytesReceived)
                                {
                                    SendData(tapRoutingObject.guid, RoutingTable.connParams[tapRoutingObject.guid].bytesReceived);
                                    RoutingTable.connParams[tapRoutingObject.guid].freeWindow -= RoutingTable.connParams[tapRoutingObject.guid].bytesReceived;
                                    RoutingTable.connParams[tapRoutingObject.guid].windowFull = false;
                                    RoutingTable.connParams[tapRoutingObject.guid].UpdateSeq(RoutingTable.connParams[tapRoutingObject.guid].bytesReceived);
                                    try
                                    {
                                        RoutingTable.connParams[tapRoutingObject.guid].socket.BeginReceive(RoutingTable.connParams[tapRoutingObject.guid].receivingBuffer, 0, RoutingTable.connParams[tapRoutingObject.guid].receivingBuffer.Count(), 0, new AsyncCallback(physicalWorkers[tapRoutingObject.ifIndex].ReceiveCallback), tapRoutingObject.guid);
                                    }
                                    catch (Exception)
                                    {
                                        RoutingTable.RequestAccess();
                                        if (!RoutingTable.connStatus[tapRoutingObject.guid].remoteEPFin)
                                            tapWorker.SendRst(tapRoutingObject.guid);
                                        RoutingTable.connStatus[tapRoutingObject.guid].remoteEPFin = true;
                                        RoutingTable.connStatus[tapRoutingObject.guid].localEPFin = true;
                                        RoutingTable.ReleaseAccess();
                                    }
                                }
                            }
                        }
                        if (packet.Ethernet.IpV4.Tcp.PayloadLength > 0 || tapRoutingObject.response == -2)
                            physicalWorkers[tapRoutingObject.ifIndex].SendData(packet, tapRoutingObject.guid);
                    }
                }
                else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Udp)
                {
                    if (packet.Ethernet.IpV4.Source == ifProtocolAddress)
                    {
                        tapRoutingObject = RoutingTable.GetInterface(packet);
                        if (tapRoutingObject.response == -1)
                            return;
                        EthernetLayer ethernetLayer = new EthernetLayer
                        {
                            Source = physicalWorkers[tapRoutingObject.ifIndex].ifHardwareAddress,
                            Destination = physicalWorkers[tapRoutingObject.ifIndex].gatewayHardwareAddress,
                            EtherType = packet.Ethernet.EtherType,
                        };

                        IpV4Layer ipV4Layer = new IpV4Layer
                        {
                            Source = physicalWorkers[tapRoutingObject.ifIndex].ifProtocolAddress,
                            CurrentDestination = packet.Ethernet.IpV4.Destination,
                            Fragmentation = packet.Ethernet.IpV4.Fragmentation,
                            HeaderChecksum = null, // Will be filled automatically.
                            Identification = packet.Ethernet.IpV4.Identification,
                            Options = packet.Ethernet.IpV4.Options,
                            Protocol = packet.Ethernet.IpV4.Protocol,
                            Ttl = (byte)(packet.Ethernet.IpV4.Ttl - 1),
                            TypeOfService = packet.Ethernet.IpV4.TypeOfService,
                        };
                        UdpLayer udpLayer = new UdpLayer
                        {
                            SourcePort = packet.Ethernet.IpV4.Udp.SourcePort,
                            DestinationPort = packet.Ethernet.IpV4.Udp.DestinationPort,
                            Checksum = null, // Will be filled automatically.
                            CalculateChecksumValue = packet.Ethernet.IpV4.Udp.IsChecksumOptional,
                        };
                        PayloadLayer payloadLayer = new PayloadLayer
                        {
                            Data = new Datagram(packet.Ethernet.IpV4.Udp.Payload.ToArray()),
                        };
                        PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);
                        physicalWorkers[tapRoutingObject.ifIndex].SendPacket(builder.Build(DateTime.Now));
                    }

                }
            }
Esempio n. 12
0
        static void msearch_response_spoof(LivePacketDevice selectedDevice, string msearch_string, string sourceIP, ushort sourcePort, string destIP, ushort destPort, string destMac)
        {

            byte[] temp = System.Text.Encoding.ASCII.GetBytes(msearch_string);


            EthernetLayer ethernetLayer = new EthernetLayer
            {

                Source = LivePacketDeviceExtensions.GetMacAddress(selectedDevice),
                Destination = new MacAddress(destMac),
                EtherType = EthernetType.None,

            };

            var options = IpV4FragmentationOptions.DoNotFragment;

            IpV4Layer ipV4Layer = new IpV4Layer
            {
                Source = new IpV4Address(sourceIP),
                CurrentDestination = new IpV4Address(destIP),
                Fragmentation = new IpV4Fragmentation(options,0),
                HeaderChecksum = null,
                Identification = 0,
                Options = IpV4Options.None,
                Protocol = null,
                Ttl = 64,
                TypeOfService = 0,
            };

            UdpLayer udpLayer = new UdpLayer
            {
                SourcePort = sourcePort,
                DestinationPort = destPort,
                Checksum = null,
                CalculateChecksumValue = true,
            };

            PayloadLayer payloadLayer = new PayloadLayer
            {
                Data = new Datagram(temp),
            };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);

            using (PacketCommunicator communicator = selectedDevice.Open(69559, PacketDeviceOpenAttributes.Promiscuous, 1000)) // read timeout
            {
                communicator.SendPacket(builder.Build(DateTime.Now));
            }

        }
Esempio n. 13
0
        private static void preparePcap()
        {
            var source = new MacAddress(getClientMAC());
            var dest = new MacAddress(getRouterMAC());

            device = LivePacketDevice.AllLocalMachine[0];
            communicator = device.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000);

            EthernetLayer ethLayer = new EthernetLayer { Source = source, Destination = dest };
            ipLayer = new IpV4Layer { Source = new IpV4Address(LocalIPAddress()), Ttl = 128 };
            icmpLayer = new IcmpEchoLayer();
            icmpBuilder = new PacketBuilder(ethLayer, ipLayer, icmpLayer);

            TCPLayer = new TcpLayer();
            TCPBuilder = new PacketBuilder(ethLayer, ipLayer, TCPLayer);

            if (!TCPMode)
            {
                communicator.SetFilter("icmp[0] = 0");
            }
            else
            {
                //tcp[13] = 18
                communicator.SetFilter("tcp[13] = 18 and port " + TCPPort);
            }
        }
Esempio n. 14
0
        private static void DiscoverNetworkBroadcast(PacketCommunicator communicator, MyDevice device)
        {
            // Supposing to be on ethernet, set mac source
            MacAddress source = new MacAddress(device.MacAddressWithDots());

            // set mac destination to broadcast
            MacAddress destination = new MacAddress("FF:FF:FF:FF:FF:FF");

            // Create the packets layers

            // Ethernet Layer
            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source = source,
                Destination = destination
            };

            // IPv4 Layer
            IpV4Layer ipV4Layer = new IpV4Layer
            {
                Source = new IpV4Address(device.IPAddress),
                Ttl = 128,
                // The rest of the important parameters will be set for each packet
            };

            // ICMP Layer
            IcmpEchoLayer icmpLayer = new IcmpEchoLayer();

            // Create the builder that will build our packets
            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

            string ipBeg = device.IpWithoutEnd();
            //Send 100 Pings to different destination with different parameters
            for (int i = 0; i < 256; i++)
            {
                // Set IPv4 parameters
                ipV4Layer.CurrentDestination = new IpV4Address(ipBeg + i);
                ipV4Layer.Identification = (ushort)i;

                // Set ICMP parameters
                icmpLayer.SequenceNumber = (ushort)i;
                icmpLayer.Identifier = (ushort)i;

                // Build the packet
                Packet packet = builder.Build(DateTime.Now);

                // Send down the packet
                communicator.SendPacket(packet);
                //Console.WriteLine("172.16.1." + i);
            }
        }
Esempio n. 15
0
 void BuildingArpPacket()
 {
     ethernetLayer = new EthernetLayer
         {
             Source = new MacAddress( ToMac( _ownMacAddress.ToString() ) ),
             Destination = new MacAddress( "FF:FF:FF:FF:FF:FF" ),
             EtherType = EthernetType.None, // Will be filled automatically.
         };
     arpLayer = new ArpLayer
         {
             ProtocolType = EthernetType.IpV4,
             Operation = ArpOperation.Request,
             SenderHardwareAddress = Array.AsReadOnly( _ownMacAddress.GetAddressBytes().ToArray() ), // 03:03:03:03:03:03.
             SenderProtocolAddress = Array.AsReadOnly( _ownIpAddress ), // 1.2.3.4.
             TargetHardwareAddress = Array.AsReadOnly( new byte[] { 0, 0, 0, 0, 0, 0 } ), // 00:00:00:00:00:00.
         };
 }
Esempio n. 16
0
 /// <summary>
 /// Two Ethernet layers are equal if they have the same source, destination and ethernet type.
 /// </summary>
 public bool Equals(EthernetLayer other)
 {
     return(other != null &&
            Source == other.Source && Destination == other.Destination && EtherType == other.EtherType);
 }
Esempio n. 17
0
        public void RandomIpV4Test()
        {
            MacAddress ethernetSource = new MacAddress("00:01:02:03:04:05");
            MacAddress ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5");
            const EthernetType EthernetType = EthernetType.IpV4;

            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = ethernetSource,
                                                  Destination = ethernetDestination,
                                                  EtherType = EthernetType
                                              };

            Random random = new Random();

            for (int i = 0; i != 1000; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer();
                ipV4Layer.HeaderChecksum = null;

                PayloadLayer payloadLayer = random.NextPayloadLayer(random.NextInt(0, 50 * 1024));

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, payloadLayer);

                Assert.IsTrue(ipV4Layer.Protocol == IpV4Protocol.Udp ||
                              ipV4Layer.Protocol == IpV4Protocol.Tcp ||
                              ipV4Layer.Protocol == IpV4Protocol.InternetGroupManagementProtocol ||
                              ipV4Layer.Protocol == IpV4Protocol.InternetControlMessageProtocol ||
                              ipV4Layer.Protocol == IpV4Protocol.Gre ||
                              packet.IsValid, "IsValid (" + ipV4Layer.Protocol + ")");

                // Ethernet
                Assert.AreEqual(packet.Length - EthernetDatagram.HeaderLengthValue, packet.Ethernet.PayloadLength, "PayloadLength");
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");

                // IpV4
                ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IP Layer");
                Assert.AreEqual(ipV4Layer.Destination, packet.Ethernet.IpV4.Destination, "Destination");
                Assert.AreNotEqual(ipV4Layer, null);
                Assert.AreNotEqual(ipV4Layer, new PayloadLayer());
                Assert.IsNotNull(ipV4Layer.ToString());
                Assert.AreEqual(IpV4Datagram.HeaderMinimumLength + ipV4Layer.Options.BytesLength, packet.Ethernet.IpV4.HeaderLength, "IP HeaderLength");
                Assert.AreEqual(packet.Length - EthernetDatagram.HeaderLengthValue, packet.Ethernet.IpV4.TotalLength, "IP TotalLength");
                Assert.AreNotEqual(2, packet.Ethernet.IpV4.Fragmentation, "IP Fragmentation");
                Assert.IsTrue(ipV4Layer.Fragmentation == packet.Ethernet.IpV4.Fragmentation, "IP Fragmentation");
                Assert.IsFalse(ipV4Layer.Fragmentation != packet.Ethernet.IpV4.Fragmentation, "IP Fragmentation");
                Assert.IsFalse(ipV4Layer.Fragmentation.Equals(0), "IP Fragmentation");
                if (ipV4Layer.Fragmentation.Offset != 0)
                    Assert.AreNotEqual(ipV4Layer.Fragmentation, IpV4Fragmentation.None, "IP Fragmentation");
                Assert.AreEqual(ipV4Layer.Fragmentation.GetHashCode(), packet.Ethernet.IpV4.Fragmentation.GetHashCode(), "IP Fragmentation");
                Assert.AreEqual(ipV4Layer.Fragmentation.Options, packet.Ethernet.IpV4.Fragmentation.Options, "IP Fragmentation");
                Assert.AreEqual(ipV4Layer.Fragmentation.Offset, packet.Ethernet.IpV4.Fragmentation.Offset, "IP Fragmentation");
                if (ipV4Layer.Fragmentation.Equals(IpV4Fragmentation.None))
                {
                    Assert.AreEqual(IpV4FragmentationOptions.None, packet.Ethernet.IpV4.Fragmentation.Options, "IP Fragmentation");
                    Assert.AreEqual(0, packet.Ethernet.IpV4.Fragmentation.Offset, "IP Fragmentation");
                }
                Assert.AreEqual(true, packet.Ethernet.IpV4.IsHeaderChecksumCorrect, "IP HeaderChecksumCorrect");
                Assert.AreNotEqual(null, packet.Ethernet.IpV4.Options, "IP Options");
                Assert.AreNotEqual(packet.Ethernet.IpV4.Options, null, "IP Options");
                Assert.AreNotEqual(new IpV4Options(new IpV4OptionUnknown(0, new byte[35])), packet.Ethernet.IpV4.Options, "IP Options");
                Assert.AreEqual(ipV4Layer.Options.GetHashCode(), packet.Ethernet.IpV4.Options.GetHashCode(), "IP Options HashCode");
                Assert.IsNotNull(packet.Ethernet.IpV4.Options.ToString());
                for (int optionIndex = 0; optionIndex != ipV4Layer.Options.Count; ++optionIndex)
                {
                    IpV4Option option = ipV4Layer.Options[optionIndex];
                    Assert.AreEqual(option, packet.Ethernet.IpV4.Options[optionIndex]);
                    Assert.IsFalse(option.Equals(null));
                }

                if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
                    Assert.IsInstanceOfType(packet.Ethernet.IpV4.Transport, typeof(TcpDatagram));
                else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Udp)
                    Assert.IsInstanceOfType(packet.Ethernet.IpV4.Transport, typeof(UdpDatagram));
                else
                    Assert.IsNull(packet.Ethernet.IpV4.Transport);

                Assert.AreEqual(payloadLayer.Data, packet.Ethernet.IpV4.Payload, "IP Payload");
            }
        }
Esempio n. 18
0
        public void RandomTcpTest()
        {
            MacAddress ethernetSource = new MacAddress("00:01:02:03:04:05");
            MacAddress ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5");

            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = ethernetSource,
                                                  Destination = ethernetDestination
                                              };

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

            for (int i = 0; i != 1000; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
                ipV4Layer.HeaderChecksum = null;
                IpV6Layer ipV6Layer = random.NextIpV6Layer(IpV4Protocol.Tcp, false);

                EthernetType ethernetType = random.NextBool() ? EthernetType.IpV4 : EthernetType.IpV6;
                Layer ipLayer = (ethernetType == EthernetType.IpV4 ? (Layer)ipV4Layer : ipV6Layer);
                TcpLayer tcpLayer = random.NextTcpLayer();

                PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(60000));

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, tcpLayer, payloadLayer);

                Assert.IsTrue(packet.IsValid);

                // Ethernet
                ethernetLayer.EtherType = ethernetType;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");
                ethernetLayer.EtherType = EthernetType.None;

                // Ip.
                if (ipLayer == ipV4Layer)
                {
                    // IpV4.
                    ipV4Layer.Protocol = IpV4Protocol.Tcp;
                    ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                    Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IPv4 Layer");
                    ipV4Layer.HeaderChecksum = null;
                } 
                else
                {
                    Assert.AreEqual(ipV6Layer, packet.Ethernet.IpV6.ExtractLayer(), "IPv6 Layer");
                }

                // TCP
                tcpLayer.Checksum = packet.Ethernet.Ip.Tcp.Checksum;
                Assert.AreEqual(tcpLayer, packet.Ethernet.Ip.Tcp.ExtractLayer(), "TCP Layer");
                Assert.AreNotEqual(random.NextTcpLayer(), packet.Ethernet.Ip.Tcp.ExtractLayer(), "TCP Layer");
                Assert.AreEqual(tcpLayer.GetHashCode(), packet.Ethernet.Ip.Tcp.ExtractLayer().GetHashCode(), "TCP Layer");
                Assert.AreNotEqual(random.NextTcpLayer().GetHashCode(), packet.Ethernet.Ip.Tcp.ExtractLayer().GetHashCode(), "TCP Layer");
                Assert.AreEqual((uint)(packet.Ethernet.Ip.Tcp.SequenceNumber + packet.Ethernet.Ip.Tcp.PayloadLength), packet.Ethernet.Ip.Tcp.NextSequenceNumber);
                foreach (TcpOption option in packet.Ethernet.Ip.Tcp.Options.OptionsCollection)
                {
                    Assert.AreEqual(option, option);
                    Assert.AreEqual(option.GetHashCode(), option.GetHashCode());
                    Assert.IsFalse(string.IsNullOrEmpty(option.ToString()));
                    Assert.IsFalse(option.Equals(null));
                    Assert.IsFalse(option.Equals(2));
                }
                Assert.AreEqual(tcpLayer.Options, packet.Ethernet.Ip.Tcp.Options, "Options");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Acknowledgment) == TcpControlBits.Acknowledgment, packet.Ethernet.Ip.Tcp.IsAcknowledgment, "IsAcknowledgment");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.CongestionWindowReduced) == TcpControlBits.CongestionWindowReduced, packet.Ethernet.Ip.Tcp.IsCongestionWindowReduced, "IsCongestionWindowReduced");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.ExplicitCongestionNotificationEcho) == TcpControlBits.ExplicitCongestionNotificationEcho, packet.Ethernet.Ip.Tcp.IsExplicitCongestionNotificationEcho, "IsExplicitCongestionNotificationEcho");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Fin) == TcpControlBits.Fin, packet.Ethernet.Ip.Tcp.IsFin, "IsFin");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Push) == TcpControlBits.Push, packet.Ethernet.Ip.Tcp.IsPush, "IsPush");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Reset) == TcpControlBits.Reset, packet.Ethernet.Ip.Tcp.IsReset, "IsReset");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Synchronize) == TcpControlBits.Synchronize, packet.Ethernet.Ip.Tcp.IsSynchronize, "IsSynchronize");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Urgent) == TcpControlBits.Urgent, packet.Ethernet.Ip.Tcp.IsUrgent, "IsUrgent");
                Assert.AreEqual(0, packet.Ethernet.Ip.Tcp.Reserved);
                Assert.IsFalse(packet.Ethernet.Ip.Tcp.IsChecksumOptional, "IsChecksumOptional");
                Assert.AreEqual(TcpDatagram.HeaderMinimumLength + tcpLayer.Options.BytesLength + payloadLayer.Length, packet.Ethernet.Ip.Tcp.Length, "Total Length");
                Assert.IsTrue(packet.Ethernet.Ip.IsTransportChecksumCorrect, "IsTransportChecksumCorrect");

                Assert.AreEqual(payloadLayer.Data, packet.Ethernet.Ip.Tcp.Payload, "Payload");
            }
        }
Esempio n. 19
0
        private static Packet BuildPacket(string httpString)
        {
            MacAddress ethernetSource = new MacAddress("00:01:02:03:04:05");
            MacAddress ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5");

            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source = ethernetSource,
                Destination = ethernetDestination
            };

            Random random = new Random();

            IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
            ipV4Layer.HeaderChecksum = null;
            TcpLayer tcpLayer = random.NextTcpLayer();

            PayloadLayer payloadLayer = new PayloadLayer
            {
                Data = new Datagram(Encoding.ASCII.GetBytes(httpString))
            };

            Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);

            Assert.IsTrue(packet.IsValid);

            // Ethernet
            ethernetLayer.EtherType = EthernetType.IpV4;
            Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");

            // IpV4
            ipV4Layer.Protocol = IpV4Protocol.Tcp;
            ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
            Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IP Layer");
            ipV4Layer.HeaderChecksum = null;

            // TCP
            tcpLayer.Checksum = packet.Ethernet.IpV4.Tcp.Checksum;
            Assert.AreEqual(tcpLayer, packet.Ethernet.IpV4.Tcp.ExtractLayer(), "TCP Layer");

            return packet;
        }
Esempio n. 20
0
        private void buttonSend00_Click(object sender, EventArgs e)
        {
            PacketDevice senderDevice = LivePacketDevice.AllLocalMachine[comboInterface.SelectedIndex];

             using (PacketCommunicator communicator = senderDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
             {
                 for (int j = 0; j < 1; j++)
                 {
                     MacAddress sourceMac = new MacAddress(textSourceMac.Text);
                     MacAddress destinationMac = new MacAddress(textDestinationMac.Text);

                     EthernetLayer ethernetLayer = new EthernetLayer
                     {
                         Source = sourceMac,
                         Destination = destinationMac
                     };

                     IpV4Layer ipv4Layer = new IpV4Layer
                     {
                         Source = new IpV4Address(textSourceIP.Text),
                         CurrentDestination = new IpV4Address(textDestinationIP.Text),
                         HeaderChecksum = null,
                         Identification = 123,
                         Options = IpV4Options.None,
                         Protocol = null,
                         Ttl = 100,
                         TypeOfService = 0,

                     };

                     UdpLayer udpLayer = new UdpLayer
                     {
                         SourcePort = (ushort)Convert.ToUInt16(textSourcePort.Text),
                         DestinationPort = (ushort)Convert.ToUInt16(textDestinationPort.Text),
                         Checksum = null,
                         CalculateChecksumValue = true,
                     };

                     byte[] buff = new byte[128];
                     // goo size
                     //byte[] buff = new byte[192];

                     // monlist
                     buff[0] = 0x17;
                     buff[1] = 0x00;
                     buff[2] = 0x03;

                     // monlist
                     buff[3] = 0x2a;

                     // memstats
                     // buff[3] = 0x07;

                     PayloadLayer payloadLayer = new PayloadLayer
                     {

                         Data = new Datagram(buff),
                         // Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                     };

                     PacketBuilder builder = new PacketBuilder(ethernetLayer, ipv4Layer, udpLayer, payloadLayer);

                     communicator.SendPacket(builder.Build(DateTime.Now));
                 }
             }
        }
Esempio n. 21
0
        public void RandomGreTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("00:01:02:03:04:05"),
                                                  Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
                                              };

            Random random = new Random();

            IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
            ipV4Layer.HeaderChecksum = null;

            for (int i = 0; i != 200; ++i)
            {
                GreLayer greLayer = random.NextGreLayer();
                PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(100));

                PacketBuilder packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, greLayer, payloadLayer);

                Packet packet = packetBuilder.Build(DateTime.Now);
                if (greLayer.Checksum == null &&
                    !new[] { EthernetType.IpV4, EthernetType.Arp, EthernetType.VLanTaggedFrame }.Contains(packet.Ethernet.IpV4.Gre.ProtocolType))
                {
                    Assert.IsTrue(packet.IsValid, "IsValid, ProtocolType=" + packet.Ethernet.IpV4.Gre.ProtocolType);
                }

                // Ethernet
                ethernetLayer.EtherType = EthernetType.IpV4;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");

                // IPv4
                ipV4Layer.Protocol = IpV4Protocol.Gre;
                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 + greLayer.Length + payloadLayer.Length,
                                packet.Ethernet.IpV4.TotalLength);
                Assert.AreEqual(IpV4Datagram.DefaultVersion, packet.Ethernet.IpV4.Version);

                // GRE
                GreDatagram actualGre = packet.Ethernet.IpV4.Gre;
                GreLayer actualGreLayer = (GreLayer)actualGre.ExtractLayer();
                if (greLayer.ChecksumPresent && greLayer.Checksum == null)
                {
                    Assert.IsTrue(actualGre.IsChecksumCorrect);
                    greLayer.Checksum = actualGre.Checksum;
                }
                Assert.AreEqual(greLayer, actualGreLayer, "Layer");
                if (actualGreLayer.Key != null)
                    actualGreLayer.SetKey(actualGreLayer.KeyPayloadLength.Value, actualGreLayer.KeyCallId.Value);
                else
                {
                    Assert.IsNull(actualGreLayer.KeyPayloadLength);
                    Assert.IsNull(actualGreLayer.KeyCallId);
                }
                Assert.AreEqual(greLayer, actualGreLayer, "Layer");
                if (actualGre.KeyPresent)
                {
                    Assert.AreEqual(greLayer.KeyPayloadLength, actualGre.KeyPayloadLength, "KeyPayloadLength");
                    Assert.AreEqual(greLayer.KeyCallId, actualGre.KeyCallId, "KeyCallId");
                }
                Assert.AreNotEqual(random.NextGreLayer(), actualGreLayer, "Not Layer");
                Assert.AreEqual(greLayer.Length, actualGre.HeaderLength);
                Assert.IsTrue(actualGre.KeyPresent ^ (greLayer.Key == null));
                MoreAssert.IsSmaller(8, actualGre.RecursionControl);
                MoreAssert.IsSmaller(32, actualGre.FutureUseBits);
                Assert.IsTrue(actualGre.RoutingPresent ^ (greLayer.Routing == null && greLayer.RoutingOffset == null));
                Assert.IsTrue(actualGre.SequenceNumberPresent ^ (greLayer.SequenceNumber == null));
                Assert.IsTrue(!actualGre.StrictSourceRoute || actualGre.RoutingPresent);
                if (actualGre.RoutingPresent)
                {
                    Assert.IsNotNull(actualGre.ActiveSourceRouteEntryIndex);
                    if (actualGre.ActiveSourceRouteEntryIndex < actualGre.Routing.Count)
                        Assert.IsNotNull(actualGre.ActiveSourceRouteEntry);

                    foreach (GreSourceRouteEntry entry in actualGre.Routing)
                    {
                        Assert.AreNotEqual(entry, 2);
                        Assert.AreEqual(entry.GetHashCode(), entry.GetHashCode());
                        switch (entry.AddressFamily)
                        {
                            case GreSourceRouteEntryAddressFamily.AsSourceRoute:
                                GreSourceRouteEntryAs asEntry = (GreSourceRouteEntryAs)entry;
                                MoreAssert.IsInRange(0, asEntry.AsNumbers.Count, asEntry.NextAsNumberIndex);
                                if (asEntry.NextAsNumberIndex != asEntry.AsNumbers.Count)
                                    Assert.AreEqual(asEntry.AsNumbers[asEntry.NextAsNumberIndex], asEntry.NextAsNumber);
                                break;

                            case GreSourceRouteEntryAddressFamily.IpSourceRoute:
                                GreSourceRouteEntryIp ipEntry = (GreSourceRouteEntryIp)entry;
                                MoreAssert.IsInRange(0, ipEntry.Addresses.Count, ipEntry.NextAddressIndex);
                                if (ipEntry.NextAddressIndex != ipEntry.Addresses.Count)
                                    Assert.AreEqual(ipEntry.Addresses[ipEntry.NextAddressIndex], ipEntry.NextAddress);
                                break;

                            default:
                                GreSourceRouteEntryUnknown unknownEntry = (GreSourceRouteEntryUnknown)entry;
                                MoreAssert.IsInRange(0, unknownEntry.Data.Length, unknownEntry.PayloadOffset);
                                break;

                        }
                    }
                }
                else
                {
                    Assert.IsNull(actualGre.ActiveSourceRouteEntry);
                }

                Assert.IsNotNull(actualGre.Payload);
                switch (actualGre.ProtocolType)
                {
                    case EthernetType.IpV4:
                        Assert.IsNotNull(actualGre.IpV4);
                        break;

                    case EthernetType.Arp:
                        Assert.IsNotNull(actualGre.Arp);
                        break;
                }
            }
        }
Esempio n. 22
0
        public void InvalidGreTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("00:01:02:03:04:05"),
                                                  Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
                                              };

            Random random = new Random();

            for (int i = 0; i != 100; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(IpV4Protocol.Gre);
                ipV4Layer.HeaderChecksum = null;

                GreLayer greLayer = random.NextGreLayer();
                greLayer.Checksum = null;
                greLayer.Routing = new List<GreSourceRouteEntry>
                                   {
                                       new GreSourceRouteEntryAs(new List<ushort> {123}.AsReadOnly(), 0),
                                       new GreSourceRouteEntryIp(new List<IpV4Address> {random.NextIpV4Address()}.AsReadOnly(),
                                                                 0)
                                   }.AsReadOnly();

                PacketBuilder packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, greLayer);
                Packet packet = packetBuilder.Build(DateTime.Now);
                Assert.IsTrue(packet.IsValid ||
                              new[] {EthernetType.IpV4, EthernetType.Arp, EthernetType.VLanTaggedFrame}.Contains(greLayer.ProtocolType),
                              "IsValid. ProtoclType=" + greLayer.ProtocolType);

                GreDatagram gre = packet.Ethernet.IpV4.Gre;

                // Remove a byte from routing
                Datagram newIpPayload = new Datagram(gre.Take(gre.Length - 1).ToArray());
                packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload});
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsNull(packet.Ethernet.IpV4.Gre.Payload);
                Assert.IsFalse(packet.IsValid);

                // SreLength is too big
                byte[] buffer = gre.ToArray();
                buffer[buffer.Length - 1] = 200;
                newIpPayload = new Datagram(buffer);
                packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload});
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsFalse(packet.IsValid);

                // PayloadOffset is too big
                buffer = gre.ToArray();
                buffer[gre.Length - 10] = 100;
                newIpPayload = new Datagram(buffer);
                packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload});
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsFalse(packet.IsValid);

                // PayloadOffset isn't aligned to ip
                buffer = gre.ToArray();
                buffer[gre.Length - 10] = 3;
                newIpPayload = new Datagram(buffer);
                packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload});
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsFalse(packet.IsValid);

                // PayloadOffset isn't aligned to as
                buffer = gre.ToArray();
                buffer[gre.Length - 16] = 1;
                newIpPayload = new Datagram(buffer);
                packetBuilder = new PacketBuilder(ethernetLayer, ipV4Layer, new PayloadLayer {Data = newIpPayload});
                packet = packetBuilder.Build(DateTime.Now);
                Assert.IsFalse(packet.IsValid);
            }
        }
Esempio n. 23
0
        public void RandomIpV6Test()
        {
            MacAddress ethernetSource = new MacAddress("00:01:02:03:04:05");
            MacAddress ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5");
            const EthernetType EthernetType = EthernetType.IpV6;

            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = ethernetSource,
                                                  Destination = ethernetDestination,
                                                  EtherType = EthernetType
                                              };

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

            for (int i = 0; i != 1000; ++i)
            {
                IpV6Layer ipV6Layer = random.NextIpV6Layer(false);

                PayloadLayer payloadLayer = random.NextPayloadLayer(random.NextInt(0, 50 * 1024));

                List<ILayer> layers = new List<ILayer> {ethernetLayer, ipV6Layer};
                if (ipV6Layer.ExtensionHeaders.LastHeader != IpV4Protocol.EncapsulatingSecurityPayload)
                    layers.Add(payloadLayer);
                Packet packet = PacketBuilder.Build(DateTime.Now, layers);

                Assert.IsTrue(ipV6Layer.LastNextHeader == IpV4Protocol.Ip ||
                              ipV6Layer.LastNextHeader == IpV4Protocol.IpV6||
                              ipV6Layer.LastNextHeader == IpV4Protocol.Udp ||
                              ipV6Layer.LastNextHeader == IpV4Protocol.Tcp ||
                              ipV6Layer.LastNextHeader == IpV4Protocol.InternetGroupManagementProtocol ||
                              ipV6Layer.LastNextHeader == IpV4Protocol.InternetControlMessageProtocol ||
                              ipV6Layer.LastNextHeader == IpV4Protocol.Gre ||
                              packet.IsValid, string.Format("IsValid ({0}...{1})", ipV6Layer.NextHeader, ipV6Layer.ExtensionHeaders.NextHeader));

                // Ethernet
                Assert.AreEqual(packet.Length - EthernetDatagram.HeaderLengthValue, packet.Ethernet.PayloadLength, "PayloadLength");
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");

                // IpV6
                Assert.AreEqual(ipV6Layer, packet.Ethernet.IpV6.ExtractLayer(), "IP Layer");
                Assert.AreEqual(ipV6Layer.GetHashCode(), packet.Ethernet.IpV6.ExtractLayer().GetHashCode(), "IP Layer");
                Assert.AreEqual(string.Format("{0} -> {1} ({2})", ipV6Layer.Source, ipV6Layer.CurrentDestination, ipV6Layer.NextHeader), ipV6Layer.ToString());
                IEnumerator extensionHeadersEnumerator = ((IEnumerable)packet.Ethernet.IpV6.ExtensionHeaders).GetEnumerator();
                for (int extensionHeaderIndex = 0; extensionHeaderIndex != packet.Ethernet.IpV6.ExtensionHeaders.Headers.Count; ++extensionHeaderIndex)
                {
                    IpV6ExtensionHeader extensionHeader = packet.Ethernet.IpV6.ExtensionHeaders[extensionHeaderIndex];
                    Assert.IsTrue(extensionHeadersEnumerator.MoveNext());
                    Assert.AreEqual(extensionHeader, extensionHeadersEnumerator.Current);
                    IpV6ExtensionHeader layerExtensionheader = ipV6Layer.ExtensionHeaders[extensionHeaderIndex];
                    Assert.AreEqual(extensionHeader, layerExtensionheader);
                    Assert.AreEqual(extensionHeader.GetHashCode(), layerExtensionheader.GetHashCode());
                    IpV6ExtensionHeaderOptions extensionHeaderOptions = extensionHeader as IpV6ExtensionHeaderOptions;
                    if (extensionHeaderOptions != null)
                    {
                        foreach (IpV6Option option in extensionHeaderOptions.Options)
                        {
                            switch (option.OptionType)
                            {
                                case IpV6OptionType.SimplifiedMulticastForwardingDuplicatePacketDetection:
                                    IpV6OptionSimplifiedMulticastForwardingDuplicatePacketDetection optionSimplifiedMulticastForwardingDuplicatePacketDetection = (IpV6OptionSimplifiedMulticastForwardingDuplicatePacketDetection)option;
                                    Assert.AreEqual(optionSimplifiedMulticastForwardingDuplicatePacketDetection is IpV6OptionSimplifiedMulticastForwardingDuplicatePacketDetectionSequenceHashAssistValue, optionSimplifiedMulticastForwardingDuplicatePacketDetection.HashIndicator);
                                    break;

                                case IpV6OptionType.QuickStart:
                                    IpV6OptionQuickStart optionQuickStart = (IpV6OptionQuickStart)option;
                                    MoreAssert.IsBiggerOrEqual(0, optionQuickStart.RateKbps);
                                    break;
                            }
                        }
                    }
                    IpV6ExtensionHeaderMobility extensionHeaderMobility = extensionHeader as IpV6ExtensionHeaderMobility;
                    if (extensionHeaderMobility != null)
                    {
                        Assert.IsFalse(extensionHeaderMobility.Equals(2));
                        Assert.IsTrue(extensionHeaderMobility.Equals((object)extensionHeader));
                        Assert.AreEqual(extensionHeaderMobility.MobilityOptions, new IpV6MobilityOptions(extensionHeaderMobility.MobilityOptions).AsEnumerable());
                        foreach (IpV6MobilityOption option in extensionHeaderMobility.MobilityOptions)
                        {
                            switch (option.OptionType)
                            {
                                case IpV6MobilityOptionType.BindingIdentifier:
                                    IpV6MobilityOptionBindingIdentifier optionBindingIdentifier = (IpV6MobilityOptionBindingIdentifier)option;
                                    if (optionBindingIdentifier.IpV4CareOfAddress.HasValue)
                                        Assert.AreEqual(optionBindingIdentifier.IpV4CareOfAddress.Value, optionBindingIdentifier.CareOfAddress);
                                    else if (optionBindingIdentifier.IpV6CareOfAddress.HasValue)
                                        Assert.AreEqual(optionBindingIdentifier.IpV6CareOfAddress.Value, optionBindingIdentifier.CareOfAddress);
                                    else
                                        Assert.IsNull(optionBindingIdentifier.CareOfAddress);
                                    break;

                                case IpV6MobilityOptionType.AccessNetworkIdentifier:
                                    IpV6MobilityOptionAccessNetworkIdentifier optionAccessNetworkIdentifier = (IpV6MobilityOptionAccessNetworkIdentifier)option;
                                    foreach (IpV6AccessNetworkIdentifierSubOption subOption in optionAccessNetworkIdentifier.SubOptions)
                                    {
                                        switch (subOption.OptionType)
                                        {
                                            case IpV6AccessNetworkIdentifierSubOptionType.GeoLocation:
                                                IpV6AccessNetworkIdentifierSubOptionGeoLocation subOptionGeoLocation =
                                                    (IpV6AccessNetworkIdentifierSubOptionGeoLocation)subOption;
                                                MoreAssert.IsBiggerOrEqual(-90, subOptionGeoLocation.LatitudeDegreesReal);
                                                MoreAssert.IsSmallerOrEqual(90, subOptionGeoLocation.LatitudeDegreesReal);
                                                MoreAssert.IsBiggerOrEqual(-180, subOptionGeoLocation.LongitudeDegreesReal);
                                                MoreAssert.IsSmallerOrEqual(180, subOptionGeoLocation.LongitudeDegreesReal);
                                                IpV6AccessNetworkIdentifierSubOptionGeoLocation subOptionGetLocationFromReal =
                                                    IpV6AccessNetworkIdentifierSubOptionGeoLocation.CreateFromRealValues(
                                                        subOptionGeoLocation.LatitudeDegreesReal,
                                                        subOptionGeoLocation.LongitudeDegreesReal);
                                                Assert.AreEqual(subOptionGeoLocation, subOptionGetLocationFromReal);
                                                break;
                                        }
                                    }
                                    break;

                                case IpV6MobilityOptionType.Timestamp:
                                    IpV6MobilityOptionTimestamp optionTimestamp = (IpV6MobilityOptionTimestamp)option;
                                    MoreAssert.IsBiggerOrEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), optionTimestamp.TimestampDateTime);
                                    break;

                                case IpV6MobilityOptionType.FlowIdentification:
                                    IpV6MobilityOptionFlowIdentification optionFlowIdentification = (IpV6MobilityOptionFlowIdentification)option;
                                    foreach (IpV6FlowIdentificationSubOption subOption in optionFlowIdentification.SubOptions)
                                    {
                                        switch (subOption.OptionType)
                                        {
                                            case IpV6FlowIdentificationSubOptionType.BindingReference:
                                                IpV6FlowIdentificationSubOptionBindingReference subOptionBindingReference =
                                                    (IpV6FlowIdentificationSubOptionBindingReference)subOption;
                                                Assert.AreEqual(subOptionBindingReference,
                                                                new IpV6FlowIdentificationSubOptionBindingReference(
                                                                    subOptionBindingReference.BindingIds.AsEnumerable()));
                                                break;
                                        }
                                    }
                                    break;

                                case IpV6MobilityOptionType.CryptographicallyGeneratedAddressParameters:
                                    IpV6MobilityOptionCryptographicallyGeneratedAddressParameters optionCryptographicallyGeneratedAddressParameters = (IpV6MobilityOptionCryptographicallyGeneratedAddressParameters)option;
                                    Assert.AreEqual(optionCryptographicallyGeneratedAddressParameters.Length - 2, optionCryptographicallyGeneratedAddressParameters.CryptographicallyGeneratedAddressParameters.Length);
                                    break;

                                case IpV6MobilityOptionType.CareOfTest:
                                    IpV6MobilityOptionCareOfTest optionCareOfTest = (IpV6MobilityOptionCareOfTest)option;
                                    Assert.IsInstanceOfType(optionCareOfTest.CareOfKeygenToken, typeof(ulong));
                                    break;

                                case IpV6MobilityOptionType.IpV4CareOfAddress:
                                    IpV6MobilityOptionIpV4CareOfAddress optionIpV4CareOfAddress = (IpV6MobilityOptionIpV4CareOfAddress)option;
                                    Assert.IsNotNull(optionIpV4CareOfAddress.CareOfAddress);
                                    break;

                                case IpV6MobilityOptionType.ReplayProtection:
                                    IpV6MobilityOptionReplayProtection optionReplayProtection = (IpV6MobilityOptionReplayProtection)option;
                                    Assert.IsNotNull(optionReplayProtection.Timestamp);
                                    break;

                                case IpV6MobilityOptionType.Experimental:
                                    IpV6MobilityOptionExperimental optionExperimental = (IpV6MobilityOptionExperimental)option;
                                    Assert.IsNotNull(optionExperimental.Data);
                                    break;

                                case IpV6MobilityOptionType.PermanentHomeKeygenToken:
                                    IpV6MobilityOptionPermanentHomeKeygenToken optionPermanentHomeKeygenToken =
                                        (IpV6MobilityOptionPermanentHomeKeygenToken)option;
                                    Assert.IsNotNull(optionPermanentHomeKeygenToken.PermanentHomeKeygenToken);
                                    break;

                                case IpV6MobilityOptionType.Signature:
                                    IpV6MobilityOptionSignature optionSignature = (IpV6MobilityOptionSignature)option;
                                    Assert.IsNotNull(optionSignature.Signature);
                                    break;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 24
0
 public void SendData(Guid guid, int payloadLength)
 {
     EthernetLayer ethernetLayer = new EthernetLayer
     {
         Source = ownHardwareAddress,
         Destination = ifHardwareAddress,
         EtherType = EthernetType.None,
     };
     IpV4Layer ipV4Layer = new IpV4Layer
     {
         Source = RoutingTable.connParams[guid].remoteIp,
         CurrentDestination = ifProtocolAddress,
         Fragmentation = IpV4Fragmentation.None,
         HeaderChecksum = null, // Will be filled automatically.
         Identification = ipID,
         Options = IpV4Options.None,
         Protocol = IpV4Protocol.Tcp,
         Ttl = 128,
         TypeOfService = 0,
     };
     TcpLayer tcpLayer = new TcpLayer
     {
         SourcePort = RoutingTable.connParams[guid].remotePort,
         DestinationPort = RoutingTable.connParams[guid].localPort,
         Checksum = null, // Will be filled automatically.
         SequenceNumber = RoutingTable.connParams[guid].seq,
         AcknowledgmentNumber = RoutingTable.connParams[guid].ack,
         ControlBits = TcpControlBits.Acknowledgment,
         Window = RoutingTable.connParams[guid].GetWindow(),
         UrgentPointer = 0,
         Options = TcpOptions.None,
     };
     PayloadLayer payloadLayer = new PayloadLayer
     {
         Data = new Datagram(RoutingTable.connParams[guid].receivingBuffer.Take(payloadLength).ToArray()),
     };
     PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);
     SendPacket(builder.Build(DateTime.Now));
 }
        static void msearch_spoof(PacketDevice selectedDevice, String source_ip, UInt16 port)
        {

            String msearch_string = "M-SEARCH * HTTP/1.1\r\nHOST:239.255.255.250:1900\r\nST: ssdp:all\r\nMAN: \"ssdp:discover\"\r\nMX:2\r\n\r\n";


            byte[] temp = System.Text.Encoding.ASCII.GetBytes(msearch_string);



            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source = new MacAddress(),
                Destination = new MacAddress("01:00:5E:7F:FF:FA"),
                EtherType = EthernetType.None,

            };

            IpV4Layer ipV4Layer = new IpV4Layer
            {
                Source = new IpV4Address(source_ip),
                CurrentDestination = new IpV4Address("239.255.255.250"),
                Fragmentation = IpV4Fragmentation.None,
                HeaderChecksum = null,

                Identification = 1,
                Options = IpV4Options.None,
                Protocol = null,
                Ttl = 64,
                TypeOfService = 0,
            };

            UdpLayer udpLayer = new UdpLayer
            {
                SourcePort = port,
                DestinationPort = 1900,
                Checksum = null,
                CalculateChecksumValue = true,
            };

            PayloadLayer payloadLayer = new PayloadLayer
            {
                Data = new Datagram(temp),
            };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);

            using (PacketCommunicator communicator = selectedDevice.Open(69559, PacketDeviceOpenAttributes.Promiscuous, 1000)) // read timeout
            {
                communicator.SendPacket(builder.Build(DateTime.Now));
            }

        }
Esempio n. 26
0
 public void SendSynAck(Guid guid)
 {
     EthernetLayer ethernetLayer = new EthernetLayer
     {
         Source = ownHardwareAddress,
         Destination = ifHardwareAddress,
         EtherType = EthernetType.None,
     };
     IpV4Layer ipV4Layer = new IpV4Layer
     {
         Source = RoutingTable.connParams[guid].remoteIp,
         CurrentDestination = ifProtocolAddress,
         Fragmentation = IpV4Fragmentation.None,
         HeaderChecksum = null, // Will be filled automatically.
         Identification = ipID,
         Options = IpV4Options.None,
         Protocol = IpV4Protocol.Tcp,
         Ttl = 128,
         TypeOfService = 0,
     };
     TcpLayer tcpLayer = new TcpLayer
     {
         SourcePort = RoutingTable.connParams[guid].remotePort,
         DestinationPort = RoutingTable.connParams[guid].localPort,
         Checksum = null, // Will be filled automatically.
         SequenceNumber = RoutingTable.connParams[guid].seq,
         AcknowledgmentNumber = RoutingTable.connParams[guid].ack,
         ControlBits = TcpControlBits.Synchronize | TcpControlBits.Acknowledgment,
         Window = RoutingTable.connParams[guid].GetWindow(),
         UrgentPointer = 0,
         Options = new TcpOptions(new TcpOptionMaximumSegmentSize((ushort)MSS), new TcpOptionWindowScale(RoutingTable.connParams[guid].windowScale)),
     };
     PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer);
     SendPacket(builder.Build(DateTime.Now));
 }
Esempio n. 27
0
 private static EthernetLayer BuildEthernetLayer(MyDevice newDev, Address addr)
 {
     EthernetLayer ethLayer = null;
     if (addr != null)
     {
         //Console.WriteLine("ADDR: " + addr.Mac.ToString());
         ethLayer = new EthernetLayer { Source = new MacAddress(newDev.MacAddressWithDots()), Destination = new MacAddress(addr.Mac) };
         //Console.WriteLine("%%%%Src: " + newDev.MacAddressWithDots() + " Dst: " + addr.Mac);
     }
     return ethLayer;
 }
Esempio n. 28
0
        /// <summary>
        /// This function build an HTTP over TCP over IPv4 over Ethernet packet.
        /// </summary>
        private static Packet BuildHttpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            TcpLayer tcpLayer =
                new TcpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 80,
                        Checksum = null, // Will be filled automatically.
                        SequenceNumber = 100,
                        AcknowledgmentNumber = 50,
                        ControlBits = TcpControlBits.Acknowledgment,
                        Window = 100,
                        UrgentPointer = 0,
                        Options = TcpOptions.None,
                    };

            HttpRequestLayer httpLayer =
                new HttpRequestLayer
                    {
                        Version = HttpVersion.Version11,
                        Header = new HttpHeader(new HttpContentLengthField(11)),
                        Body = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                        Method = new HttpRequestMethod(HttpRequestKnownMethod.Get),
                        Uri = @"http://pcapdot.net/",
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, httpLayer);

            return builder.Build(DateTime.Now);
        }
Esempio n. 29
0
        private static Packet BuildIcmpPacket(MacAddress SourceMac, MacAddress DestinationMac, IpV4Address SourceIp, IpV4Address CurrentDestination, string packetType)
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                {
                    Source = SourceMac,
                    Destination = DestinationMac,
                    EtherType = EthernetType.None, // Will be filled automatically.
                };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                {
                    //Source = new IpV4Address("1.2.3.4"),
                    //CurrentDestination = new IpV4Address("11.22.33.44"),
                    Source = SourceIp,
                    CurrentDestination = CurrentDestination,
                    Fragmentation = IpV4Fragmentation.None,
                    HeaderChecksum = null, // Will be filled automatically.
                    Identification = 123,
                    Options = IpV4Options.None,
                    Protocol = null, // Will be filled automatically.
                    Ttl = 100,
                    TypeOfService = 0,
                };

            IcmpEchoLayer icmpLayer = null;
            IcmpEchoReplyLayer icmpRLayer = null;

            PacketBuilder builder = null;

            if (packetType.Equals("REQUEST"))
            {
                Console.WriteLine("Request");
                icmpLayer =
                    new IcmpEchoLayer
                    {
                        Checksum = null, // Will be filled automatically.
                        Identifier = 456,
                        SequenceNumber = 800,
                    };
                builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);
            }
            else
            {
                Console.WriteLine("Reply");
                icmpRLayer =
                    new IcmpEchoReplyLayer
                    {
                        Checksum = null, // Will be filled automatically.
                        Identifier = 456,
                        SequenceNumber = 800,
                    };
                builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpRLayer);
            }

            return builder.Build(DateTime.Now);
        }
Esempio n. 30
0
 void BuildingTcpPacket()
 {
     ethernetLayer = new EthernetLayer
     {
         Source = new MacAddress( ToMac( _ownMacAddress.ToString() ) ),
         EtherType = EthernetType.None, // Will be filled automatically.
     };
     ipV4Layer = new IpV4Layer
     {
         Source = new IpV4Address( new IPAddress( _ownIpAddress ).ToString() ),
         Fragmentation = IpV4Fragmentation.None,
         HeaderChecksum = null, // Will be filled automatically.
         Identification = 0,
         Options = IpV4Options.None,
         Protocol = null, // Will be filled automatically.
         Ttl = 100,
         TypeOfService = 0,
     };
     tcpLayer = new TcpLayer
     {
         SourcePort = 62000,
         Checksum = null, // Will be filled automatically.
         SequenceNumber = 100,
         AcknowledgmentNumber = 0,
         ControlBits = TcpControlBits.Synchronize,
         Window = 8192,
         UrgentPointer = 0,
         Options = new TcpOptions( new TcpOptionMaximumSegmentSize( 1460 ), TcpOption.Nop, new TcpOptionWindowScale( 2 ), new TcpOptionSelectiveAcknowledgmentPermitted(), new TcpOptionTimestamp( (uint)DateTime.Now.Ticks, 0 ) ),
     };
 }
Esempio n. 31
0
        /// <summary>
        /// This function build an TCP over IPv4 over Ethernet with payload packet.
        /// </summary>
        private static Packet BuildTcpPacket(MacAddress SourceMac, MacAddress DestinationMac, IpV4Layer ipV4Layer, TcpLayer tcpLayer, PayloadLayer payloadLayer)
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                {
                    Source = SourceMac,
                    Destination = DestinationMac,
                    EtherType = EthernetType.None, // Will be filled automatically.
                };

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

            //TcpLayer tcpLayer =
            //    new TcpLayer
            //    {
            //        SourcePort = 4050,
            //        DestinationPort = 25,
            //        Checksum = null, // Will be filled automatically.
            //        SequenceNumber = 100,
            //        AcknowledgmentNumber = 50,
            //        ControlBits = TcpControlBits.Acknowledgment,
            //        Window = 100,
            //        UrgentPointer = 0,
            //        Options = TcpOptions.None,
            //    };

            //PayloadLayer payloadLayer =
            //    new PayloadLayer
            //    {
            //        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
            //    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }
Esempio n. 32
0
        static void Main(string[] args)
        {
            // Send anonymous statistics about the usage of Pcap.Net
            PcapDotNet.Analysis.PcapDotNetAnalysis.OptIn = true;

            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the list
            for (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Open the output device
            using (PacketCommunicator communicator = selectedDevice.Open(100, // name of the device
                                                                         PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                                                         1000)) // read timeout
            {
                // Supposing to be on ethernet, set mac source to 1:1:1:1:1:1
                MacAddress source = new MacAddress("1:1:1:1:1:1");

                // set mac destination to 2:2:2:2:2:2
                MacAddress destination = new MacAddress("2:2:2:2:2:2");

                // Create the packets layers

                // Ethernet Layer
                EthernetLayer ethernetLayer = new EthernetLayer
                                                  {
                                                      Source = source,
                                                      Destination = destination
                                                  };

                // IPv4 Layer
                IpV4Layer ipV4Layer = new IpV4Layer
                                          {
                                              Source = new IpV4Address("1.2.3.4"),
                                              Ttl = 128,
                                              // The rest of the important parameters will be set for each packet
                                          };

                // ICMP Layer
                IcmpEchoLayer icmpLayer = new IcmpEchoLayer();

                // Create the builder that will build our packets
                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

                // Send 100 Pings to different destination with different parameters
                for (int i = 0; i != 100; ++i)
                {
                    // Set IPv4 parameters
                    ipV4Layer.Destination = new IpV4Address("2.3.4." + i);
                    ipV4Layer.Identification = (ushort)i;

                    // Set ICMP parameters
                    icmpLayer.SequenceNumber = (ushort)i;
                    icmpLayer.Identifier = (ushort)i;

                    // Build the packet
                    Packet packet = builder.Build(DateTime.Now);

                    // Send down the packet
                    communicator.SendPacket(packet);
                }
            }
        }
Esempio n. 33
0
 /// <summary>
 /// Two Ethernet layers are equal if they have the same source, destination and ethernet type.
 /// </summary>
 public bool Equals(EthernetLayer other)
 {
     return other != null &&
            Source == other.Source && Destination == other.Destination && EtherType == other.EtherType;
 }