Exemplo n.º 1
0
        public void HandleInform_InformsAreAllowed()
        {
            Random      random        = new Random();
            IPv4Address clientAddress = IPv4Address.FromString("192.168.178.10");

            IPv4HeaderInformation headerInformation =
                new IPv4HeaderInformation(clientAddress, IPv4Address.FromString("192.168.178.1"));

            Byte[] clientMacAdress = random.NextBytes(6);

            DHCPv4Packet requestPacket = new DHCPv4Packet(
                headerInformation, clientMacAdress, (UInt32)random.Next(),
                IPv4Address.Empty, IPv4Address.Empty, clientAddress,
                DHCPv4PacketFlags.Unicast,
                new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Inform)
                );

            Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock =
                new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

            var resolverInformations = new CreateScopeResolverInformation
            {
                Typename = nameof(DHCPv4RelayAgentSubnetResolver),
            };

            Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

            scopeResolverMock.Setup(x => x.InitializeResolver(resolverInformations)).Returns(resolverMock.Object);

            Guid scopeId = random.NextGuid();

            DHCPv4RootScope rootScope = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent(
                    new DHCPv4ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv4ScopeAddressProperties(
                        IPv4Address.FromString("192.168.178.1"),
                        IPv4Address.FromString("192.168.178.255"),
                        new List <IPv4Address> {
                        IPv4Address.FromString("192.168.178.1")
                    },
                        informsAreAllowd: true
                        ),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                })
            });

            DHCPv4Packet result = rootScope.HandleInform(requestPacket);

            CheckAcknowledgePacket(clientAddress, result);

            CheckEventAmount(1, rootScope);
            CheckHandeledEvent(0, InformErros.NoError, requestPacket, result, rootScope);
        }
Exemplo n.º 2
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            IPv4HeaderInformation item = (IPv4HeaderInformation)value;

            serializer.Serialize(writer, new EeasySerialibleVersionOfIPv4HeaderInformationJsonConverter
            {
                Destination = item.Destionation,
                Source      = item.Source,
                Listener    = item.ListenerAddress,
            });;
        }
Exemplo n.º 3
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var info = serializer.Deserialize <EeasySerialibleVersionOfIPv4HeaderInformationJsonConverter>(reader);

            if (info == null)
            {
                return(null);
            }

            IPv4HeaderInformation result = new IPv4HeaderInformation(info.Source, info.Destination, info.Listener);

            return(result);
        }
Exemplo n.º 4
0
        private DHCPv4Packet GetDeclinePacket(Random random, IPv4Address address)
        {
            IPv4HeaderInformation headerInformation =
                new IPv4HeaderInformation(IPv4Address.Empty, IPv4Address.Broadcast);

            Byte[] clientMacAdress = random.NextBytes(6);

            DHCPv4Packet declinePacket = new DHCPv4Packet(
                headerInformation, clientMacAdress, (UInt32)random.Next(),
                IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty,
                DHCPv4PacketFlags.Unicast,
                new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Decline),
                new DHCPv4PacketAddressOption(DHCPv4OptionTypes.RequestedIPAddress, address)
                );

            return(declinePacket);
        }
Exemplo n.º 5
0
        public void HandleRelease_LeaseExists_AddressIsActive()
        {
            Random      random        = new Random();
            IPv4Address leasedAddress = IPv4Address.FromString("192.168.178.10");

            IPv4HeaderInformation headerInformation =
                new IPv4HeaderInformation(leasedAddress, IPv4Address.FromString("192.168.178.1"));

            Byte[] clientMacAdress = random.NextBytes(6);

            DHCPv4Packet requestPacket = new DHCPv4Packet(
                headerInformation, clientMacAdress, (UInt32)random.Next(),
                IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty,
                DHCPv4PacketFlags.Unicast,
                new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Release)
                );

            Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock =
                new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

            var resolverInformations = new CreateScopeResolverInformation
            {
                Typename = nameof(DHCPv4RelayAgentSubnetResolver),
            };

            Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

            scopeResolverMock.Setup(x => x.InitializeResolver(resolverInformations)).Returns(resolverMock.Object);

            Guid scopeId = random.NextGuid();
            Guid leaseId = random.NextGuid();

            DateTime        leaseCreatedAt = DateTime.UtcNow.AddHours(-1);
            DHCPv4RootScope rootScope      = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent(
                    new DHCPv4ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv4ScopeAddressProperties(
                        IPv4Address.FromString("192.168.178.1"),
                        IPv4Address.FromString("192.168.178.255"),
                        new List <IPv4Address> {
                        IPv4Address.FromString("192.168.178.1")
                    },
                        leaseTime: TimeSpan.FromDays(1)
                        ),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
                new DHCPv4LeaseCreatedEvent
                {
                    EntityId         = leaseId,
                    Address          = leasedAddress,
                    ClientIdenfier   = DHCPv4ClientIdentifier.FromHwAddress(clientMacAdress).GetBytes(),
                    ScopeId          = scopeId,
                    UniqueIdentifier = null,
                    StartedAt        = leaseCreatedAt,
                    ValidUntil       = DateTime.UtcNow.AddDays(1),
                },
                new DHCPv4LeaseActivatedEvent
                {
                    EntityId = leaseId,
                    ScopeId  = scopeId,
                },
            });
            DHCPv4Lease lease = rootScope.GetScopeById(scopeId).Leases.GetLeaseById(leaseId);

            DHCPv4Packet result = rootScope.HandleRelease(requestPacket);

            Assert.Equal(DHCPv4Packet.Empty, result);

            CheckIfLeaseIsRelease(lease);

            CheckEventAmount(2, rootScope);
            CheckLeaseReleasedEvent(0, scopeId, rootScope, leaseId);
            CheckHandeledEvent(1, ReleaseError.NoError, requestPacket, rootScope);
        }
Exemplo n.º 6
0
        public void HandleRelease_LeaseExists_AddressIsActive_NotSentDiscover()
        {
            Random      random        = new Random();
            IPv4Address leasedAddress = IPv4Address.FromString("192.168.178.10");

            IPv4HeaderInformation headerInformation =
                new IPv4HeaderInformation(leasedAddress, IPv4Address.FromString("192.168.178.1"));

            Byte[] clientMacAdress = random.NextBytes(6);

            DHCPv4Packet requestPacket = new DHCPv4Packet(
                headerInformation, clientMacAdress, (UInt32)random.Next(),
                IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty,
                DHCPv4PacketFlags.Unicast,
                new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Release)
                );

            DHCPv4Packet discoverPacket = new DHCPv4Packet(
                headerInformation, clientMacAdress, (UInt32)random.Next(),
                IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty,
                DHCPv4PacketFlags.Broadcast,
                new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Discover),
                new DHCPv4PacketClientIdentifierOption(DHCPv4ClientIdentifier.FromIdentifierValue("random test client"))
                );

            Mock <IScopeResolver <DHCPv4Packet, IPv4Address> > resolverMock = new Mock <IScopeResolver <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

            resolverMock.Setup(x => x.PacketMeetsCondition(discoverPacket)).Returns(true);
            resolverMock.SetupGet(x => x.HasUniqueIdentifier).Returns(false);

            Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> > scopeResolverMock =
                new Mock <IScopeResolverManager <DHCPv4Packet, IPv4Address> >(MockBehavior.Strict);

            var resolverInformations = new CreateScopeResolverInformation
            {
                Typename = nameof(DHCPv4RelayAgentSubnetResolver),
            };

            scopeResolverMock.Setup(x => x.InitializeResolver(resolverInformations)).Returns(resolverMock.Object);

            Guid scopeId = random.NextGuid();
            Guid leaseId = random.NextGuid();

            DateTime        leaseCreatedAt = DateTime.UtcNow.AddHours(-1);
            DHCPv4RootScope rootScope      = GetRootScope(scopeResolverMock);

            rootScope.Load(new List <DomainEvent> {
                new DHCPv4ScopeEvents.DHCPv4ScopeAddedEvent(
                    new DHCPv4ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv4ScopeAddressProperties(
                        IPv4Address.FromString("192.168.178.1"),
                        IPv4Address.FromString("192.168.178.255"),
                        new List <IPv4Address> {
                        IPv4Address.FromString("192.168.178.1")
                    },
                        leaseTime: TimeSpan.FromDays(1),
                        renewalTime: TimeSpan.FromHours(12),
                        preferredLifetime: TimeSpan.FromHours(18),
                        reuseAddressIfPossible: true,
                        acceptDecline: true,
                        addressAllocationStrategy: DHCPv4ScopeAddressProperties.AddressAllocationStrategies.Next,
                        supportDirectUnicast: true,
                        maskLength: 24
                        ),
                    ResolverInformation = resolverInformations,
                    Name = "Testscope",
                    Id   = scopeId,
                }),
                new DHCPv4LeaseCreatedEvent
                {
                    EntityId         = leaseId,
                    Address          = leasedAddress,
                    ClientIdenfier   = DHCPv4ClientIdentifier.FromIdentifierValue("random test client").GetBytes(),
                    ScopeId          = scopeId,
                    UniqueIdentifier = null,
                    StartedAt        = leaseCreatedAt,
                    ValidUntil       = DateTime.UtcNow.AddDays(1),
                },
                new DHCPv4LeaseActivatedEvent
                {
                    EntityId = leaseId,
                    ScopeId  = scopeId,
                },
            });

            DHCPv4Lease existingLease = rootScope.GetScopeById(scopeId).Leases.GetLeaseById(leaseId);

            DHCPv4Packet releaseResult = rootScope.HandleRelease(requestPacket);

            Assert.Equal(DHCPv4Packet.Empty, releaseResult);

            CheckIfLeaseIsRelease(existingLease);

            CheckEventAmount(2, rootScope);
            CheckLeaseReleasedEvent(0, scopeId, rootScope, leaseId);
            CheckHandeledEvent(1, ReleaseError.NoError, requestPacket, rootScope);

            DHCPv4Packet discoveryResult    = rootScope.HandleDiscover(discoverPacket);
            IPv4Address  newAssignedAddress = IPv4Address.FromString("192.168.178.2");

            Assert.Equal(newAssignedAddress, discoveryResult.YourIPAdress);
        }
Exemplo n.º 7
0
        public async Task SendAndReceive()
        {
            Random random = new Random();

            String dbName           = $"{random.Next()}";
            String eventStorePrefix = random.GetAlphanumericString();

            var serviceInteractions = GetTestClient(dbName, eventStorePrefix);

            Byte[] opt82Value = random.NextBytes(10);

            try
            {
                //Get and Add Interface
                var interfacesResult = await serviceInteractions.GetAsync("/api/interfaces/dhcpv4/");

                var interfaces = await IsObjectResult <DHCPv4InterfaceOverview>(interfacesResult);

                DHCPv4InterfaceEntry usedInterface = null;
                foreach (var item in interfaces.Entries)
                {
                    try
                    {
                        var createInterfaceResult = await serviceInteractions.PostAsync("/api/interfaces/dhcpv4/", GetContent(new
                        {
                            name = "my test interface",
                            ipv4Address = item.IPv4Address,
                            interfaceId = item.PhysicalInterfaceId
                        }));

                        Guid interfaceDaAPIId = await IsObjectResult <Guid>(createInterfaceResult);

                        Assert.NotEqual(Guid.Empty, interfaceDaAPIId);
                        usedInterface = item;
                        break;
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }

                Assert.NotNull(usedInterface);

                var interfaceAddress = IPv4Address.FromString(usedInterface.IPv4Address);

                //Create scope

                var createScopeResult = await serviceInteractions.PostAsync("/api/scopes/dhcpv4/", GetContent(new
                {
                    name = "Testscope",
                    id = Guid.NewGuid(),
                    addressProperties = new
                    {
                        start = "192.168.10.1",
                        end = "192.168.10.254",
                        excludedAddresses = new[] { "192.168.10.1" },
                        preferredLifetime = TimeSpan.FromDays(0.8),
                        leaseTime = TimeSpan.FromDays(1),
                        renewalTime = TimeSpan.FromDays(0.5),
                        maskLength = 24,
                        supportDirectUnicast = true,
                        acceptDecline = true,
                        informsAreAllowd = true,
                        reuseAddressIfPossible = true,
                        addressAllocationStrategy = Beer.DaAPI.Shared.Requests.DHCPv4ScopeRequests.V1.DHCPv4ScopeAddressPropertyReqest.AddressAllocationStrategies.Next
                    },
                    resolver = new
                    {
                        typename = nameof(DHCPv4Option82Resolver),
                        propertiesAndValues = new Dictionary <String, String>
                        {
                            { nameof(DHCPv4Option82Resolver.Value), System.Text.Json.JsonSerializer.Serialize(opt82Value) },
                        }
                    }
                }));

                Guid scopeId = await IsObjectResult <Guid>(createScopeResult);

                Assert.NotEqual(Guid.Empty, scopeId);

                IPAddress  address        = new IPAddress(interfaceAddress.GetBytes());
                IPEndPoint ownEndPoint    = new IPEndPoint(address, 68);
                IPEndPoint serverEndPoint = new IPEndPoint(address, 67);

                UdpClient client = new UdpClient(ownEndPoint);

                IPv4HeaderInformation headerInformation =
                    new IPv4HeaderInformation(IPv4Address.FromString(address.ToString()), IPv4Address.Broadcast);

                DHCPv4Packet discoverPacket = new DHCPv4Packet(
                    headerInformation, random.NextBytes(6), (UInt32)random.Next(),
                    IPv4Address.Empty, IPv4Address.Empty, IPv4Address.Empty, DHCPv4PacketFlags.Broadcast,
                    new DHCPv4PacketMessageTypeOption(DHCPv4MessagesTypes.Discover),
                    new DHCPv4PacketRawByteOption(82, opt82Value),
                    new DHCPv4PacketClientIdentifierOption(DHCPv4ClientIdentifier.FromIdentifierValue("my custom client")));

                byte[] discoverPacketStream = discoverPacket.GetAsStream();
                await client.SendAsync(discoverPacketStream, discoverPacketStream.Length, serverEndPoint);

                await Task.Delay(2000);

                var content = await client.ReceiveAsync();

                Byte[]       receivedBytes = content.Buffer;
                DHCPv4Packet response      = DHCPv4Packet.FromByteArray(receivedBytes, new IPv4HeaderInformation(interfaceAddress, interfaceAddress));

                Assert.NotNull(response);
                Assert.True(response.IsValid);

                var serverIdentifierOption = response.GetOptionByIdentifier(DHCPv4OptionTypes.ServerIdentifier) as DHCPv4PacketAddressOption;
                Assert.NotNull(serverIdentifierOption);
                Assert.Equal(interfaceAddress, serverIdentifierOption.Address);

                var subnetOption = response.GetOptionByIdentifier(DHCPv4OptionTypes.SubnetMask) as DHCPv4PacketAddressOption;
                Assert.NotNull(subnetOption);
                Assert.Equal(IPv4Address.FromString("255.255.255.0"), subnetOption.Address);

                var clientIdentifierOption = response.GetOptionByIdentifier(DHCPv4OptionTypes.ClientIdentifier) as DHCPv4PacketClientIdentifierOption;
                Assert.NotNull(clientIdentifierOption);
                Assert.Equal("my custom client", clientIdentifierOption.Identifier.IdentifierValue);
                Assert.Equal(DUID.Empty, clientIdentifierOption.Identifier.DUID);
                Assert.Equal((UInt32)0, clientIdentifierOption.Identifier.IaId);
                Assert.Empty(clientIdentifierOption.Identifier.HwAddress);

                var incoming82Option = response.GetOptionByIdentifier(DHCPv4OptionTypes.Option82) as DHCPv4PacketRawByteOption;
                Assert.NotNull(incoming82Option);
                Assert.Equal(opt82Value, incoming82Option.OptionData);
            }
            finally
            {
                await EventStoreClientDisposer.CleanUp(eventStorePrefix, null);

                await DatabaseTestingUtility.DeleteDatabase(dbName);
            }
        }