Esempio n. 1
0
        public async Task <Guid?> Handle(CreateDHCPv6InterfaceListenerCommand request, CancellationToken cancellationToken)
        {
            _logger.LogDebug("Handle started");

            DHCPv6Listener listener = DHCPv6Listener.Create(
                request.NicId,
                DHCPListenerName.FromString(request.Name),
                IPv6Address.FromString(request.IPv6Addres));

            var possibleListeners = _interfaceEngine.GetPossibleListeners();

            if (possibleListeners.Count(x => x.Address == listener.Address && x.PhysicalInterfaceId == listener.PhysicalInterfaceId) == 0)
            {
                return(null);
            }

            var activeListeners = await _interfaceEngine.GetActiveListeners();

            if (activeListeners.Count(x => x.Address == listener.Address && x.PhysicalInterfaceId == listener.PhysicalInterfaceId) > 0)
            {
                return(null);
            }

            if (await _storageEngine.Save(listener) == false)
            {
                return(null);
            }

            _interfaceEngine.OpenListener(listener);

            return(listener.Id);
        }
Esempio n. 2
0
        public async Task <IActionResult> GetAllInterface()
        {
            var possibleInterfaces = _interfaceEngine.GetPossibleListeners();
            var activeInterfaces   = await _interfaceEngine.GetActiveListeners();

            List <ActiveDHCPv6InterfaceEntry> activeEntries  = new List <ActiveDHCPv6InterfaceEntry>();
            List <DHCPv6InterfaceEntry>       unboundEntries = new List <DHCPv6InterfaceEntry>();

            foreach (var item in possibleInterfaces)
            {
                var activeInterface = activeInterfaces.FirstOrDefault(x => x.PhysicalInterfaceId == item.PhysicalInterfaceId && x.Address == item.Address);
                if (activeInterface != null)
                {
                    activeEntries.Add(new ActiveDHCPv6InterfaceEntry
                    {
                        SystemId              = activeInterface.Id,
                        IPv6Address           = activeInterface.Address.ToString(),
                        MACAddress            = item.PhysicalAddress,
                        Name                  = activeInterface.Name,
                        PhysicalInterfaceName = item.Interfacename,
                        PhysicalInterfaceId   = activeInterface.PhysicalInterfaceId
                    });
                }
                else
                {
                    unboundEntries.Add(new DHCPv6InterfaceEntry
                    {
                        IPv6Address         = item.Address.ToString(),
                        MACAddress          = item.PhysicalAddress,
                        InterfaceName       = item.Interfacename,
                        PhysicalInterfaceId = item.PhysicalInterfaceId,
                    });
                }
            }

            var detachedInterfaces = activeInterfaces
                                     .Where(x => possibleInterfaces.Count(y => y.PhysicalInterfaceId == x.PhysicalInterfaceId) == 0)
                                     .Select(x => new DetachedDHCPv6InterfaceEntry
            {
                SystemId    = x.Id,
                IPv6Address = x.Address.ToString(),
                Name        = x.Name
            }).ToList();


            var result = new DHCPv6InterfaceOverview
            {
                ActiveEntries   = activeEntries,
                Entries         = unboundEntries,
                DetachedEntries = detachedInterfaces
            };

            return(base.Ok(result));
        }
Esempio n. 3
0
        //[Fact]
        public async Task SendAndReceive()
        {
            Random random = new Random();

            String dbName = $"mydb-{random.Next()}";
            String prefix = random.GetAlphanumericString();

            try
            {
                UInt32 enterpriseNumber = (UInt32)random.Next();

                StorageContext initicalContext = DatabaseTestingUtility.GetTestDatabaseContext(dbName);

                await initicalContext.Database.MigrateAsync();

                await initicalContext.SaveInitialServerConfiguration(new DHCPv6ServerProperties { ServerDuid = new UUIDDUID(new Guid()) });

                initicalContext.Dispose();

                IPv6Address expectedAdress = IPv6Address.FromString("fe80::0");

                var services = new ServiceCollection();
                services.AddScoped <ServiceFactory>(p => p.GetService);

                services.AddSingleton <DHCPv6RootScope>(sp =>
                {
                    var storageEngine = sp.GetRequiredService <IDHCPv6StorageEngine>();
                    var scope         = storageEngine.GetRootScope().GetAwaiter().GetResult();
                    return(scope);
                });

                services.AddTransient <IDHCPv6ServerPropertiesResolver, DatabaseDHCPv6ServerPropertiesResolver>();
                services.AddSingleton <ISerializer, JSONBasedSerializer>();
                services.AddSingleton <IScopeResolverManager <DHCPv6Packet, IPv6Address>, DHCPv6ScopeResolverManager>();
                services.AddSingleton <IServiceBus, MediaRBasedServiceBus>();
                services.AddSingleton <IDHCPv6PacketFilterEngine, SimpleDHCPv6PacketFilterEngine>();
                services.AddSingleton <IDHCPv6InterfaceEngine, DHCPv6InterfaceEngine>();
                services.AddSingleton <IDHCPv6LeaseEngine, DHCPv6LeaseEngine>();
                services.AddSingleton <IDHCPv6StorageEngine, DHCPv6StorageEngine>();
                services.AddSingleton <IDHCPv6ReadStore, StorageContext>();
                services.AddSingleton(new EventStoreBasedStoreConnenctionOptions(new EventStoreClient(EventStoreClientSettings.Create("esdb://127.0.0.1:2113?tls=false")), prefix));
                services.AddSingleton <IDHCPv6EventStore, EventStoreBasedStore>();
                services.AddSingleton(DatabaseTestingUtility.GetTestDbContextOptions(dbName));

                services.AddTransient <INotificationHandler <DHCPv6PacketArrivedMessage> >(sp => new DHCPv6PacketArrivedMessageHandler(
                                                                                               sp.GetRequiredService <IServiceBus>(), sp.GetRequiredService <IDHCPv6PacketFilterEngine>(), sp.GetService <ILogger <DHCPv6PacketArrivedMessageHandler> >()));

                services.AddTransient <INotificationHandler <ValidDHCPv6PacketArrivedMessage> >(sp => new ValidDHCPv6PacketArrivedMessageHandler(
                                                                                                    sp.GetRequiredService <IServiceBus>(), sp.GetRequiredService <IDHCPv6LeaseEngine>(), sp.GetService <ILogger <ValidDHCPv6PacketArrivedMessageHandler> >()));

                services.AddTransient <INotificationHandler <DHCPv6PacketReadyToSendMessage> >(sp => new DHCPv6PacketReadyToSendMessageHandler(
                                                                                                   sp.GetRequiredService <IDHCPv6InterfaceEngine>(), sp.GetService <ILogger <DHCPv6PacketReadyToSendMessageHandler> >()));

                services.AddTransient <DHCPv6RateLimitBasedFilter>();
                services.AddTransient <DHCPv6PacketConsistencyFilter>();
                services.AddTransient <DHCPv6PacketServerIdentifierFilter>((sp) => new DHCPv6PacketServerIdentifierFilter(
                                                                               new UUIDDUID(new Guid()), sp.GetService <ILogger <DHCPv6PacketServerIdentifierFilter> >()));

                services.AddLogging();

                var provider = services.BuildServiceProvider();

                DHCPv6RootScope initialRootScope = provider.GetService <DHCPv6RootScope>();

                initialRootScope.AddScope(new DHCPv6ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv6ScopeAddressProperties(
                        IPv6Address.FromString("fe80::0"),
                        IPv6Address.FromString("fe80::ff"),
                        new List <IPv6Address> {
                        IPv6Address.FromString("fe80::1")
                    },
                        preferredLifeTime: TimeSpan.FromDays(0.5),
                        validLifeTime: TimeSpan.FromDays(1),
                        rapitCommitEnabled: true,
                        informsAreAllowd: true,
                        supportDirectUnicast: true,
                        reuseAddressIfPossible: false,
                        acceptDecline: true,
                        t1: DHCPv6TimeScale.FromDouble(0.6),
                        t2: DHCPv6TimeScale.FromDouble(0.8),
                        addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next),
                    ScopeProperties     = DHCPv6ScopeProperties.Empty,
                    ResolverInformation = new CreateScopeResolverInformation
                    {
                        Typename            = nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver),
                        PropertiesAndValues = new Dictionary <String, String>
                        {
                            { nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver.EnterpriseNumber), enterpriseNumber.ToString() },
                            { nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver.RelayAgentIndex), 0.ToString() },
                        }
                    },
                    Name = "Testscope",
                    Id   = Guid.NewGuid(),
                });

                IDHCPv6PacketFilterEngine packetFilterEngine = provider.GetService <IDHCPv6PacketFilterEngine>();
                packetFilterEngine.AddFilter(provider.GetService <DHCPv6RateLimitBasedFilter>());
                packetFilterEngine.AddFilter(provider.GetService <DHCPv6PacketConsistencyFilter>());
                packetFilterEngine.AddFilter(provider.GetService <DHCPv6PacketServerIdentifierFilter>());


                IDHCPv6InterfaceEngine interfaceEngine = provider.GetService <IDHCPv6InterfaceEngine>();
                var possibleListener = interfaceEngine.GetPossibleListeners();

                var listener = possibleListener.First();

                interfaceEngine.OpenListener(listener);

                IPAddress  address        = new IPAddress(listener.Address.GetBytes());
                IPEndPoint ownEndPoint    = new IPEndPoint(address, 546);
                IPEndPoint serverEndPoint = new IPEndPoint(address, 547);

                UdpClient client = new UdpClient(ownEndPoint);

                DHCPv6Packet packet = DHCPv6Packet.AsInner(14, DHCPv6PacketTypes.Solicit, new List <DHCPv6PacketOption>
                {
                    new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit),
                    new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, new UUIDDUID(Guid.NewGuid())),
                    new DHCPv6PacketIdentityAssociationNonTemporaryAddressesOption(15, TimeSpan.Zero, TimeSpan.Zero, new List <DHCPv6PacketSuboption>()),
                });

                DHCPv6RelayPacket outerPacket = DHCPv6RelayPacket.AsOuterRelay(new IPv6HeaderInformation(listener.Address, listener.Address),
                                                                               true, 0, IPv6Address.FromString("fe80::2"), IPv6Address.FromString("fe80::2"), new DHCPv6PacketOption[]
                {
                    new DHCPv6PacketRemoteIdentifierOption(enterpriseNumber, new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }),
                }, packet);

                byte[] packetStream = outerPacket.GetAsStream();
                await client.SendAsync(packetStream, packetStream.Length, serverEndPoint);

                await Task.Delay(2000);

                var content = await client.ReceiveAsync();

                Byte[]       receivedBytes = content.Buffer;
                DHCPv6Packet response      = DHCPv6Packet.FromByteArray(receivedBytes, new IPv6HeaderInformation(listener.Address, listener.Address));

                var iaOption = response.GetInnerPacket().GetNonTemporaryIdentiyAssocation(15);
                Assert.NotNull(iaOption);
                Assert.Single(iaOption.Suboptions);
                Assert.IsAssignableFrom <DHCPv6PacketIdentityAssociationAddressSuboption>(iaOption.Suboptions.First());
                Assert.Equal(expectedAdress, ((DHCPv6PacketIdentityAssociationAddressSuboption)iaOption.Suboptions.First()).Address);
            }
            finally
            {
                await DatabaseTestingUtility.DeleteDatabase(dbName);

                await EventStoreClientDisposer.CleanUp(prefix, null);
            }
        }