コード例 #1
0
        private DHCPv6Packet GetReleasePacket(
            Random random, out IPv6Address usedAddress, out DUID clientDuid, out UInt32 iaId, Boolean withIdentity, params DHCPv6PacketOption[] options)
        {
            IPv6HeaderInformation headerInformation =
                new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2"));

            clientDuid = new UUIDDUID(random.NextGuid());
            iaId       = random.NextBoolean() == false?random.NextUInt32() : 0;

            usedAddress = random.GetIPv6Address();

            var packetOptions = new List <DHCPv6PacketOption>(options)
            {
                new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, clientDuid),
            };

            if (withIdentity == true)
            {
                packetOptions.Add(new DHCPv6PacketIdentityAssociationNonTemporaryAddressesOption(iaId, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), new DHCPv6PacketSuboption[]
                {
                    new DHCPv6PacketIdentityAssociationAddressSuboption(usedAddress, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), Array.Empty <DHCPv6PacketSuboption>())
                }));
            }

            DHCPv6Packet packet = DHCPv6Packet.AsOuter(headerInformation, random.NextUInt16(),
                                                       DHCPv6PacketTypes.RELEASE, packetOptions);

            return(packet);
        }
コード例 #2
0
        public async Task Handle_ResponseAvaiable()
        {
            IPv6HeaderInformation headerInformation = new IPv6HeaderInformation(
                IPv6Address.FromString("fe80::2"), IPv6Address.FromString("fe80::1"));

            DHCPv6Packet packet          = DHCPv6Packet.AsOuter(headerInformation, 1, DHCPv6PacketTypes.Solicit, new List <DHCPv6PacketOption>());
            DHCPv6Packet reseponsePacket = DHCPv6Packet.AsOuter(IPv6HeaderInformation.AsResponse(headerInformation), 1, DHCPv6PacketTypes.ADVERTISE, new List <DHCPv6PacketOption>());

            Mock <IDHCPv6LeaseEngine> leaseEngineMock = new Mock <IDHCPv6LeaseEngine>(MockBehavior.Strict);

            leaseEngineMock.Setup(x => x.HandlePacket(packet)).ReturnsAsync(reseponsePacket).Verifiable();

            Mock <IServiceBus> serviceBusMock = new Mock <IServiceBus>(MockBehavior.Strict);

            serviceBusMock.Setup(x => x.Publish(It.Is <DHCPv6PacketReadyToSendMessage>(y => y.Packet == reseponsePacket))).Returns(Task.CompletedTask).Verifiable();

            ValidDHCPv6PacketArrivedMessageHandler handler = new ValidDHCPv6PacketArrivedMessageHandler(
                serviceBusMock.Object, leaseEngineMock.Object,
                Mock.Of <ILogger <ValidDHCPv6PacketArrivedMessageHandler> >());

            await handler.Handle(new ValidDHCPv6PacketArrivedMessage(packet), CancellationToken.None);

            leaseEngineMock.Verify();
            serviceBusMock.Verify();
        }
コード例 #3
0
        public async Task SendPacket()
        {
            Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict);

            factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv6Server> >());

            DHCPv6InterfaceEngine engine = new DHCPv6InterfaceEngine(
                Mock.Of <IServiceBus>(MockBehavior.Strict),
                Mock.Of <IDHCPv6StorageEngine>(MockBehavior.Strict),
                factoryMock.Object
                );

            var possibleListener = engine.GetPossibleListeners();
            var listener         = possibleListener.First();

            engine.OpenListener(listener);

            DHCPv6Packet responsePacket = DHCPv6Packet.AsOuter(
                new IPv6HeaderInformation(listener.Address, listener.Address), 4, DHCPv6PacketTypes.Solicit, new List <DHCPv6PacketOption>
            {
                new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit),
                new DHCPv6PacketByteOption(DHCPv6PacketOptionTypes.Preference, 14),
            });

            IPAddress  address       = new IPAddress(listener.Address.GetBytes());
            IPEndPoint localEndPoint = new IPEndPoint(address, 546);
            UdpClient  client        = new UdpClient(localEndPoint);

            client.Connect(new IPEndPoint(address, 547));
            try
            {
                Boolean sended = engine.SendPacket(responsePacket);
                Assert.True(sended);
                var result = await client.ReceiveAsync();

                Assert.True(result.Buffer.Length > 0);

                DHCPv6Packet receivedPacket = DHCPv6Packet.FromByteArray(result.Buffer,
                                                                         new IPv6HeaderInformation(listener.Address, listener.Address));

                Assert.Equal(responsePacket, receivedPacket);
            }
            finally
            {
                client.Dispose();
                engine.CloseListener(listener);

                await Task.Delay(1000);
            }
        }
コード例 #4
0
        public async Task Handle()
        {
            IPv6HeaderInformation headerInformation = new IPv6HeaderInformation(
                IPv6Address.FromString("fe80::2"), IPv6Address.FromString("fe80::1"));

            DHCPv6Packet response = DHCPv6Packet.AsOuter(headerInformation, 1, DHCPv6PacketTypes.ADVERTISE, new List <DHCPv6PacketOption>());

            Mock <IDHCPv6InterfaceEngine> interfaceEngine = new Mock <IDHCPv6InterfaceEngine>(MockBehavior.Strict);

            interfaceEngine.Setup(x => x.SendPacket(response)).Returns(true).Verifiable();

            DHCPv6PacketReadyToSendMessageHandler handler = new DHCPv6PacketReadyToSendMessageHandler(
                interfaceEngine.Object,
                Mock.Of <ILogger <DHCPv6PacketReadyToSendMessageHandler> >());

            await handler.Handle(new DHCPv6PacketReadyToSendMessage(response), CancellationToken.None);

            interfaceEngine.Verify();
        }
コード例 #5
0
        private DHCPv6Packet GetSolicitPacket(
            Random random, out DUID clientDuid, out UInt32 iaId, params DHCPv6PacketOption[] options)
        {
            IPv6HeaderInformation headerInformation =
                new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::1"));

            clientDuid = new UUIDDUID(random.NextGuid());
            iaId       = random.NextUInt32();

            var packetOptions = new List <DHCPv6PacketOption>(options)
            {
                new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, clientDuid),
                new DHCPv6PacketIdentityAssociationNonTemporaryAddressesOption(iaId, TimeSpan.Zero, TimeSpan.Zero, Array.Empty <DHCPv6PacketSuboption>()),
                new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit),
            };

            DHCPv6Packet packet = DHCPv6Packet.AsOuter(headerInformation, random.NextUInt16(),
                                                       DHCPv6PacketTypes.Solicit, packetOptions);

            return(packet);
        }
コード例 #6
0
        public void PacketMeetsCondition_False_NotRelay()
        {
            Random random = new Random();
            String value  = random.GetAlphanumericString();

            IPv6HeaderInformation headerInformation =
                new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2"));

            var packetOptions = new List <DHCPv6PacketOption>
            {
                new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit),
            };

            DHCPv6Packet packet = DHCPv6Packet.AsOuter(headerInformation, random.NextUInt16(),
                                                       DHCPv6PacketTypes.Solicit, packetOptions);

            Mock <ISerializer> serializerMock = new Mock <ISerializer>(MockBehavior.Strict);

            serializerMock.Setup(x => x.Deserialze <String>(value)).Returns(value).Verifiable();
            serializerMock.Setup(x => x.Deserialze <UInt16>("0")).Returns(0).Verifiable();
            serializerMock.Setup(x => x.Deserialze <Boolean>("true")).Returns(true).Verifiable();

            var resolver = new DHCPv6MilegateResolver();

            resolver.ApplyValues(new Dictionary <String, String> {
                { "Value", value },
                { "Index", "0" },
                { "IsCaseSenstiveMatch", "true" },
            }, serializerMock.Object);

            Boolean result = resolver.PacketMeetsCondition(packet);

            Assert.False(result);

            serializerMock.Verify();
        }
コード例 #7
0
        public void PacketMeetsCondition_False_NotRelay()
        {
            Random random = new Random();

            Mock <ISerializer>           serializerMock = new Mock <ISerializer>(MockBehavior.Strict);
            DHCPv6SimpleZyxelIESResolver resolver       = new DHCPv6SimpleZyxelIESResolver();

            IPv6HeaderInformation headerInformation =
                new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2"));

            var packetOptions = new List <DHCPv6PacketOption>
            {
                new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit),
            };

            DHCPv6Packet packet = DHCPv6Packet.AsOuter(headerInformation, random.NextUInt16(),
                                                       DHCPv6PacketTypes.Solicit, packetOptions);

            Boolean result = resolver.PacketMeetsCondition(packet);

            Assert.False(result);

            serializerMock.Verify();
        }
コード例 #8
0
        public async Task SeedDatabase(Boolean reset, StorageContext storageContext)
        {
            if (reset == true)
            {
                {
                    var packets = await storageContext.DHCPv6PacketEntries.AsQueryable().ToListAsync();

                    var entries = await storageContext.DHCPv6LeaseEntries.AsQueryable().ToListAsync();

                    storageContext.RemoveRange(packets);
                    storageContext.RemoveRange(entries);
                }

                {
                    var packets = await storageContext.DHCPv4PacketEntries.AsQueryable().ToListAsync();

                    var entries = await storageContext.DHCPv4LeaseEntries.AsQueryable().ToListAsync();

                    storageContext.RemoveRange(packets);
                    storageContext.RemoveRange(entries);
                }

                await storageContext.SaveChangesAsync();
            }

            if (storageContext.DHCPv6PacketEntries.Count() == 0)
            {
                DateTime start = DateTime.UtcNow.AddDays(-20);
                DateTime end   = DateTime.UtcNow.AddDays(20);

                Int32 diff = (Int32)(end - start).TotalMinutes;

                Random random = new Random();

                List <DHCPv6PacketHandledEntryDataModel> dhcpv6PacketEntries = new List <DHCPv6PacketHandledEntryDataModel>();
                var requestPacketTypes = new[] { DHCPv6PacketTypes.Solicit, DHCPv6PacketTypes.CONFIRM, DHCPv6PacketTypes.DECLINE, DHCPv6PacketTypes.REBIND, DHCPv6PacketTypes.RELEASE, DHCPv6PacketTypes.RENEW, DHCPv6PacketTypes.REQUEST };
                for (int i = 0; i < 30_000; i++)
                {
                    var request =

                        DHCPv6RelayPacket.AsOuterRelay(new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")), true, 2, IPv6Address.FromString("faf::2"), IPv6Address.FromString("fefc::23"),
                                                       new DHCPv6PacketOption[] {
                        new DHCPv6PacketRemoteIdentifierOption((UInt32)random.Next(), GetRandomBytes(random)),
                        new DHCPv6PacketByteArrayOption(DHCPv6PacketOptionTypes.InterfaceId, GetRandomBytes(random)),
                    },
                                                       DHCPv6RelayPacket.AsInnerRelay(true, 1, IPv6Address.FromString("fe70::2"), IPv6Address.FromString("fecc::23"),
                                                                                      new DHCPv6PacketOption[] {
                        new DHCPv6PacketByteArrayOption(DHCPv6PacketOptionTypes.InterfaceId, GetRandomBytes(random)),
                    },
                                                                                      DHCPv6Packet.AsInner(
                                                                                          (UInt16)random.Next(0, UInt16.MaxValue),
                                                                                          random.NextDouble() > 0.3 ? DHCPv6PacketTypes.Solicit : DHCPv6PacketTypes.RELEASE,
                                                                                          new DHCPv6PacketOption[]
                    {
                        new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ServerIdentifer, new UUIDDUID(Guid.NewGuid())),
                        new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, new UUIDDUID(Guid.NewGuid())),
                        new DHCPv6PacketIdentityAssociationNonTemporaryAddressesOption((UInt32)random.Next()),
                    })));

                    var entry = new DHCPv6PacketHandledEntryDataModel
                    {
                        Id                 = Guid.NewGuid(),
                        Timestamp          = start.AddMinutes(random.Next(0, diff)),
                        ScopeId            = Guid.NewGuid(),
                        RequestType        = requestPacketTypes[random.Next(0, requestPacketTypes.Length)],
                        RequestSize        = request.GetSize(),
                        RequestStream      = request.GetAsStream(),
                        RequestDestination = request.Header.Destionation.ToString(),
                        RequestSource      = request.Header.Source.ToString(),
                    };

                    if (random.NextDouble() > 0.8)
                    {
                        entry.FilteredBy = "something";
                    }
                    else
                    {
                        if (random.NextDouble() > 0.8)
                        {
                            entry.InvalidRequest = true;
                        }
                        else
                        {
                            if (random.NextDouble() > 0.5)
                            {
                                entry.HandledSuccessfully = true;
                                entry.ErrorCode           = 0;

                                var response = DHCPv6Packet.AsOuter(
                                    new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")),
                                    (UInt16)random.Next(0, UInt16.MaxValue),
                                    random.NextDouble() > 0.3 ? DHCPv6PacketTypes.REPLY : DHCPv6PacketTypes.ADVERTISE,
                                    new DHCPv6PacketOption[]
                                {
                                    new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ServerIdentifer, new UUIDDUID(Guid.NewGuid())),
                                    new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, new UUIDDUID(Guid.NewGuid())),
                                    DHCPv6PacketIdentityAssociationNonTemporaryAddressesOption.AsSuccess(
                                        (UInt16)random.Next(0, UInt16.MaxValue), TimeSpan.FromMinutes(random.Next(30, 100)), TimeSpan.FromMinutes(random.Next(30, 100)), IPv6Address.FromString("fe80::100"),
                                        TimeSpan.FromMinutes(random.Next(30, 100)), TimeSpan.FromMinutes(random.Next(30, 100))),
                                    DHCPv6PacketIdentityAssociationPrefixDelegationOption.AsSuccess((UInt32)random.Next(), TimeSpan.FromMinutes(random.Next(30, 100)), TimeSpan.FromMinutes(random.Next(30, 100)),
                                                                                                    (Byte)random.Next(30, 68), IPv6Address.FromString("fc:12::0"), TimeSpan.FromMinutes(random.Next(30, 100)), TimeSpan.FromMinutes(random.Next(30, 100))),
                                    new DHCPv6PacketBooleanOption(DHCPv6PacketOptionTypes.Auth, random.NextDouble() > 0.5),
                                    new DHCPv6PacketByteOption(DHCPv6PacketOptionTypes.Preference, (Byte)random.Next(0, 256)),
                                    new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit),
                                    new DHCPv6PacketIPAddressOption(DHCPv6PacketOptionTypes.ServerUnicast, IPv6Address.FromString("fd::1")),
                                    new DHCPv6PacketIPAddressListOption(48, new [] { IPv6Address.FromString("2001::1"), IPv6Address.FromString("2001::1") }),
                                });

                                entry.ResponseDestination = response.Header.Destionation.ToString();
                                entry.ResponseSource      = response.Header.Source.ToString();
                                entry.ResponseStream      = response.GetAsStream();
                                entry.ResponseSize        = response.GetSize();
                                entry.ResponseType        = random.NextDouble() > 0.3 ? DHCPv6PacketTypes.REPLY : DHCPv6PacketTypes.ADVERTISE;
                            }
                            else
                            {
                                entry.HandledSuccessfully = false;
                                entry.ErrorCode           = random.Next(0, 5);
                            }
                        }
                    }

                    entry.SetTimestampDates();

                    dhcpv6PacketEntries.Add(entry);
                }

                List <DHCPv4PacketHandledEntryDataModel> dhcpv4PacketEntries = new();
                var requestDHCPv4PacketTypes = new[] { DHCPv4MessagesTypes.Discover, DHCPv4MessagesTypes.Decline, DHCPv4MessagesTypes.Inform, DHCPv4MessagesTypes.Release, DHCPv4MessagesTypes.Request };
                for (int i = 0; i < 30_000; i++)
                {
                    var hwAddress = new Byte[6];
                    random.NextBytes(hwAddress);

                    var option82Value = new Byte[30];
                    random.NextBytes(option82Value);

                    var request =
                        new DHCPv4Packet(new IPv4HeaderInformation(IPv4Address.FromString("192.168.0.1"), IPv4Address.FromString("10.10.10.10")),
                                         hwAddress, (UInt32)random.Next(), IPv4Address.FromString("0.0.0.0"), IPv4Address.FromString("192.168.0.5"), IPv4Address.FromString("0.0.0.0"),
                                         DHCPv4PacketFlags.Unicast,
                                         new DHCPv4PacketParameterRequestListOption(new DHCPv4OptionTypes[] { DHCPv4OptionTypes.NetworkTimeProtocolServers, DHCPv4OptionTypes.DNSServers, DHCPv4OptionTypes.Router, DHCPv4OptionTypes.DomainName }),
                                         new DHCPv4PacketRawByteOption((Byte)DHCPv4OptionTypes.Option82, option82Value)
                                         );


                    var entry = new DHCPv4PacketHandledEntryDataModel
                    {
                        Id                 = Guid.NewGuid(),
                        Timestamp          = start.AddMinutes(random.Next(0, diff)),
                        ScopeId            = Guid.NewGuid(),
                        RequestType        = requestDHCPv4PacketTypes[random.Next(0, requestDHCPv4PacketTypes.Length)],
                        RequestSize        = request.GetSize(),
                        RequestStream      = request.GetAsStream(),
                        RequestDestination = request.Header.Destionation.ToString(),
                        RequestSource      = request.Header.Source.ToString(),
                    };

                    if (random.NextDouble() > 0.8)
                    {
                        entry.FilteredBy = "something";
                    }
                    else
                    {
                        if (random.NextDouble() > 0.8)
                        {
                            entry.InvalidRequest = true;
                        }
                        else
                        {
                            if (random.NextDouble() > 0.5)
                            {
                                entry.HandledSuccessfully = true;
                                entry.ErrorCode           = 0;

                                var response = new DHCPv4Packet(new IPv4HeaderInformation(IPv4Address.FromString("10.10.10.10"), IPv4Address.FromString("192.168.0.1")),
                                                                hwAddress, (UInt32)random.Next(), IPv4Address.FromString("0.0.0.0"), IPv4Address.FromString("192.168.0.5"), IPv4Address.FromString("192.168.0.15"),
                                                                DHCPv4PacketFlags.Unicast,
                                                                new DHCPv4PacketAddressListOption(DHCPv4OptionTypes.DNSServers, new[] { IPv4Address.FromString("1.1.1.1"), IPv4Address.FromString("8.8.8.8") }),
                                                                new DHCPv4PacketAddressOption(DHCPv4OptionTypes.Router, IPv4Address.FromString("192.168.0.253"))
                                                                );

                                entry.ResponseDestination = response.Header.Destionation.ToString();
                                entry.ResponseSource      = response.Header.Source.ToString();
                                entry.ResponseStream      = response.GetAsStream();
                                entry.ResponseSize        = response.GetSize();
                                entry.ResponseType        = random.NextDouble() > 0.3 ? DHCPv4MessagesTypes.Offer : DHCPv4MessagesTypes.Acknowledge;
                            }
                            else
                            {
                                entry.HandledSuccessfully = false;
                                entry.ErrorCode           = random.Next(0, 5);
                            }
                        }
                    }

                    entry.SetTimestampDates();
                    dhcpv4PacketEntries.Add(entry);
                }

                List <DHCPv6LeaseEntryDataModel> dhcpv6LeaseEntries = new List <DHCPv6LeaseEntryDataModel>();
                for (int i = 0; i < 30_000; i++)
                {
                    Byte[] addressBytes = new byte[16];
                    Byte[] prefixBytes  = new byte[16];
                    random.NextBytes(addressBytes);
                    random.NextBytes(prefixBytes);

                    DHCPv6LeaseEntryDataModel entryDataModel = new DHCPv6LeaseEntryDataModel
                    {
                        Id        = Guid.NewGuid(),
                        Timestamp = start.AddMinutes(random.Next(0, diff)),
                        LeaseId   = Guid.NewGuid(),
                        Address   = IPv6Address.FromByteArray(addressBytes).ToString(),
                        EndReason = StatisticsControllerResponses.V1.ReasonToEndLease.Nothing,
                        ScopeId   = Guid.NewGuid(),
                        Start     = start.AddMinutes(random.Next(0, diff - 50)),
                    };

                    Int32 leaseDiff = (Int32)(end.AddDays(4) - entryDataModel.Start).TotalMinutes;
                    entryDataModel.End = entryDataModel.Start.AddMinutes(random.Next(10, leaseDiff));

                    TimeSpan lifetime      = entryDataModel.End - entryDataModel.Start;
                    TimeSpan renewalTime   = lifetime / 2;
                    TimeSpan rebindingTime = lifetime * (2.0 / 3.0);

                    entryDataModel.EndOfRenewalTime       = entryDataModel.Start + renewalTime;
                    entryDataModel.EndOfPreferredLifetime = entryDataModel.Start + rebindingTime;

                    if (random.NextDouble() > 0.5)
                    {
                        entryDataModel.Prefix       = IPv6Address.FromByteArray(prefixBytes).ToString();
                        entryDataModel.PrefixLength = (Byte)random.Next(48, 76);
                    }

                    dhcpv6LeaseEntries.Add(entryDataModel);
                }

                List <DHCPv4LeaseEntryDataModel> dhcpv4LeaseEntries = new();
                for (int i = 0; i < 30_000; i++)
                {
                    Byte[] addressBytes = new byte[4];
                    random.NextBytes(addressBytes);

                    DHCPv4LeaseEntryDataModel entryDataModel = new DHCPv4LeaseEntryDataModel
                    {
                        Id        = Guid.NewGuid(),
                        Timestamp = start.AddMinutes(random.Next(0, diff)),
                        LeaseId   = Guid.NewGuid(),
                        Address   = IPv4Address.FromByteArray(addressBytes).ToString(),
                        EndReason = StatisticsControllerResponses.V1.ReasonToEndLease.Nothing,
                        ScopeId   = Guid.NewGuid(),
                        Start     = start.AddMinutes(random.Next(0, diff - 50)),
                    };

                    Int32 leaseDiff = (Int32)(end.AddDays(4) - entryDataModel.Start).TotalMinutes;
                    entryDataModel.End = entryDataModel.Start.AddMinutes(random.Next(10, leaseDiff));

                    TimeSpan lifetime      = entryDataModel.End - entryDataModel.Start;
                    TimeSpan renewalTime   = lifetime / 2;
                    TimeSpan rebindingTime = lifetime * (2.0 / 3.0);

                    entryDataModel.EndOfRenewalTime       = entryDataModel.Start + renewalTime;
                    entryDataModel.EndOfPreferredLifetime = entryDataModel.Start + rebindingTime;

                    dhcpv4LeaseEntries.Add(entryDataModel);
                }

                storageContext.AddRange(dhcpv6PacketEntries);
                storageContext.AddRange(dhcpv6LeaseEntries);

                storageContext.AddRange(dhcpv4PacketEntries);
                storageContext.AddRange(dhcpv4LeaseEntries);

                storageContext.SaveChanges();
            }
        }