예제 #1
0
        public void TestInform_RootScopeAcceptInforms()
        {
            Random random = new Random();

            IPv4Address start         = random.GetIPv4Address();
            IPv4Address end           = random.GetIPv4AddressGreaterThan(start);
            IPv4Address sourceAddress = random.GetIPv4AddressBetween(start, end);

            DHCPv4Packet input = GetInformPacket(random, sourceAddress);

            DHCPv4RootScope rootScope = GetRootScope();

            Guid scopeId = Guid.NewGuid();

            rootScope.Load(new List <DomainEvent> {
                new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    AddressProperties = new DHCPv4ScopeAddressProperties(start, end, new List <IPv4Address>(), informsAreAllowd: true),
                    Id = scopeId,
                })
            });

            DHCPv4Packet result = rootScope.HandleInform(input);

            DHCPv4InformHandledEvent domainEvent = TestResult <DHCPv4InformHandledEvent>(
                input, result, false, true, scopeId, rootScope);

            Assert.Equal(InformErros.NoError, domainEvent.Error);
        }
예제 #2
0
 public DHCPv4RequestHandledEvent(Guid scopeId, DHCPv4Packet request, RequestErros error) : this(scopeId, request, DHCPv4Packet.Empty, error)
 {
     if (error == RequestErros.NoError)
     {
         throw new ArgumentException("if a request has no error, a response packet is needed");
     }
 }
예제 #3
0
    private void receiveCallback(Packet packet)
    {
        try
        {
            IpV4Datagram ipPacket    = packet.Ethernet.IpV4;
            UdpDatagram  udpDatagram = ipPacket.Udp;
            Datagram     datagram    = udpDatagram.Payload;

            if (udpDatagram.SourcePort.Equals(68) & udpDatagram.DestinationPort.Equals(67))
            {
                DHCPv4Packet dhcpv4Packet = new DHCPv4Packet();
                if (dhcpv4Packet.parsePacket(datagram.ToArray()))
                {
                    List <DHCPv4Option> list = new DHCPv4Option().parseDhcpOptions(dhcpv4Packet.dhcpOptions);
                    foreach (DHCPv4Option dhcpMessageTypeOption in list)
                    {
                        if (dhcpMessageTypeOption.optionIdBytes.Equals(0x35))
                        {
                            switch (dhcpMessageTypeOption.optionValue[0])
                            {
                            //--Packet is a Discover
                            case 0x01:
                                Console.WriteLine("Service received:\t" + packet.Ethernet.Destination + "\tDISCOVER\txid: " + BitConverter.ToString(dhcpv4Packet.xid));
                                sendDhcpOffer(new MacAddress(inter.getMacAddress()), packet.Ethernet.Source, dhcpv4Packet.xid, dhcpv4Packet.secs);

                                break;

                            //--Packet is an Request
                            case 0x03:
                                foreach (DHCPv4Option dhcpServerIdentifierOption in list)
                                {
                                    //--DHCP contains Server-Identifier-Option.
                                    if (dhcpServerIdentifierOption.optionIdBytes.Equals(0x36))
                                    {
                                        //--DHCP-Server-Identifier equals IP-Address of DHCP-Server.
                                        if (BitConverter.ToInt32(dhcpServerIdentifierOption.optionValue, 0).Equals(BitConverter.ToInt32(inter.getIPAddress().GetAddressBytes(), 0)))
                                        {
                                            Console.WriteLine("Service received:\t" + packet.Ethernet.Destination + "\tREQUEST\t\txid: " + BitConverter.ToString(dhcpv4Packet.xid) + "\tSID: " + BitConverter.ToString(dhcpServerIdentifierOption.optionValue, 0));
                                            sendDhcpAck(new MacAddress(inter.getMacAddress()), packet.Ethernet.Source, dhcpv4Packet.xid, dhcpv4Packet.secs);
                                        }
                                        else
                                        {
                                            Console.WriteLine("Client preferes other DHCP-Server!");
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("The DHCP-Message could not be parsed...");
                }
            }
        }
        catch (Exception) { }
    }
예제 #4
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);
        }
예제 #5
0
            public DHCPv4RequestHandledEvent(DHCPv4Packet request, DHCPv4Packet response, RequestErros error) : base(request, response, error == RequestErros.NoError)
            {
                if (error != RequestErros.ScopeNotFound)
                {
                    throw new ArgumentException("a scope id has to be specified if an error different from 'ScopeNotFound' is used");
                }

                Error = error;
            }
예제 #6
0
            public DHCPv4DeclineHandledEvent(DHCPv4Packet request, DeclineErros error) : base(request, DHCPv4Packet.Empty, false)
            {
                if (error != DeclineErros.ScopeNotFound)
                {
                    throw new ArgumentException("a scope id has to be specified if an error different from 'ScopeNotFound' is used");
                }

                Error = error;
            }
예제 #7
0
        public void DHCPv4RelayAgentSubnetResolver_PacketMeetsConditions()
        {
            Random random = new Random();

            Int32 maskIdentifier = random.Next(20, 24);

            IPv4SubnetMask mask      = new IPv4SubnetMask(new IPv4SubnetMaskIdentifier(maskIdentifier));
            IPv4Address    addresses = random.GetIPv4NetworkAddress(mask);

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

            serializer.Setup(x => x.Deserialze <String>(mask.GetSlashNotation().ToString())).Returns(mask.GetSlashNotation().ToString());
            serializer.Setup(x => x.Deserialze <String>(addresses.ToString())).Returns(addresses.ToString());

            DHCPv4RelayAgentSubnetResolver resolver = new DHCPv4RelayAgentSubnetResolver();
            Dictionary <String, String>    values   = new Dictionary <String, String>()
            {
                { nameof(DHCPv4RelayAgentSubnetResolver.NetworkAddress), addresses.ToString() },
                { nameof(DHCPv4RelayAgentSubnetResolver.Mask), mask.GetSlashNotation().ToString() },
            };

            resolver.ApplyValues(values, serializer.Object);

            Int32 trys = random.Next(20, 30);

            for (int i = 0; i < trys; i++)
            {
                Boolean     shouldPass = false;
                IPv4Address gwAddress  = IPv4Address.Empty;

                if (random.NextDouble() > 0.5)
                {
                    gwAddress  = random.GetIPv4AddressWithinSubnet(mask, addresses);
                    shouldPass = true;
                }
                else
                {
                    if (random.NextDouble() > 0.5)
                    {
                        gwAddress = random.GetIPv4AddressOutWithSubnet(mask, addresses);
                    }
                }

                DHCPv4Packet packet = new DHCPv4Packet(
                    new IPv4HeaderInformation(random.GetIPv4Address(), random.GetIPv4Address()),
                    random.NextBytes(6),
                    (UInt32)random.Next(),
                    IPv4Address.Empty,
                    gwAddress,
                    IPv4Address.Empty
                    );

                Boolean actual = resolver.PacketMeetsCondition(packet);
                Assert.Equal(shouldPass, actual);
            }
        }
예제 #8
0
                public DHCPv4Packet GetPacket()
                {
                    if (_packet == null)
                    {
                        _packet = DHCPv4Packet.FromByteArray(Content,
                                                             new IPv4HeaderInformation(IPv4Address.FromString(Header.Source), IPv4Address.FromString(Header.Destination)));
                    }

                    return(_packet);
                }
예제 #9
0
        public void Blub()
        {
            String input = "0101060115430d42062c0000000000000000000000000000c2229c0202a0574ff12f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000638253633501013d070102a0574ff12f390205003204c23763440c13524f555445524c414e434f4d313739335641573c0e4c414e434f4d20313739335641573707017903060f2bd4520d0103312f320206082697683201ff0000000000000000";

            Byte[] content = StringToByteArray(input);

            DHCPv4Packet packet = DHCPv4Packet.FromByteArray(content, new IPv4HeaderInformation(IPv4Address.FromString("192.168.10.0"), IPv4Address.FromString("192.168.10.10")));

            Assert.True(packet.IsValid);
        }
예제 #10
0
        public void TestInform_RandomScopeAcceptInforms()
        {
            Random random = new Random();

            IPv4Address start         = random.GetIPv4Address();
            IPv4Address end           = random.GetIPv4AddressGreaterThan(start);
            IPv4Address sourceAddress = random.GetIPv4AddressBetween(start, end);

            List <Tuple <IPv4Address, IPv4Address> > existingRanges = new List <Tuple <IPv4Address, IPv4Address> >
            {
                new Tuple <IPv4Address, IPv4Address>(start, end),
            };

            DHCPv4Packet input = GetInformPacket(random, sourceAddress);

            Int32 rootScopeAmount     = random.Next(3, 10);
            List <DomainEvent> events = new List <DomainEvent>();

            for (int i = 0; i < rootScopeAmount; i++)
            {
                Guid rootScopeId = Guid.NewGuid();
                Tuple <IPv4Address, IPv4Address> addressRange = random.GenerateUniqueAddressRange(existingRanges);

                events.Add(new DHCPv4ScopeAddedEvent(new DHCPv4ScopeCreateInstruction
                {
                    Id = rootScopeId,
                    AddressProperties = new DHCPv4ScopeAddressProperties
                                            (addressRange.Item1, addressRange.Item2, Array.Empty <IPv4Address>(), informsAreAllowd: true)
                }));

                GenerateScopeTree(
                    random.NextDouble(), random,
                    rootScopeId, existingRanges, events);
            }

            Int32 randomScopeIndex = random.Next(0, events.Count);
            DHCPv4ScopeAddedEvent corelatedScopeEvent = (DHCPv4ScopeAddedEvent)events[randomScopeIndex];

            corelatedScopeEvent.Instructions.AddressProperties = new DHCPv4ScopeAddressProperties
                                                                     (start, end, Array.Empty <IPv4Address>(), informsAreAllowd: true);

            Guid scopeId = corelatedScopeEvent.Instructions.Id;

            DHCPv4RootScope rootScope = GetRootScope();

            rootScope.Load(events);

            DHCPv4Packet result = rootScope.HandleInform(input);

            DHCPv4InformHandledEvent domainEvent = TestResult <DHCPv4InformHandledEvent>(
                input, result, false, true, scopeId, rootScope);

            Assert.Equal(InformErros.NoError, domainEvent.Error);
        }
예제 #11
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            DHCPv4Packet packet = (DHCPv4Packet)value;

            Byte[] bytes = packet.GetAsStream();

            serializer.Serialize(writer, new DHCPv4PacketSerializerInfo
            {
                Header = (IPv4HeaderInformation)packet.Header,
                Stream = bytes,
            });
        }
예제 #12
0
        public static bool IsOptionPresentend(DHCPv4Packet result, Byte optionType)
        {
            foreach (var item in result.Options)
            {
                if (item.OptionType == optionType)
                {
                    return true;
                }
            }

            return false;
        }
예제 #13
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var info = serializer.Deserialize <DHCPv4PacketSerializerInfo>(reader);

            if (info == null)
            {
                return(DHCPv4Packet.Empty);
            }

            DHCPv4Packet packet = DHCPv4Packet.FromByteArray(info.Stream, info.Header);

            return(packet);
        }
예제 #14
0
        public override Boolean PacketMeetsCondition(DHCPv4Packet packet)
        {
            foreach (var resolver in InnerResolvers)
            {
                Boolean resolverResult = resolver.PacketMeetsCondition(packet);
                if (resolverResult == false)
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #15
0
        private static void CheckAcknowledgePacket(IPv4Address clientAddress, DHCPv4Packet result)
        {
            Assert.NotNull(result);
            Assert.NotEqual(DHCPv4Packet.Empty, result);
            Assert.True(result.IsValid);

            Assert.Equal(IPv4Address.Empty, result.YourIPAdress);

            Assert.Equal(clientAddress, result.Header.Destionation);
            Assert.Equal(clientAddress, result.ClientIPAdress);

            Assert.Equal(DHCPv4MessagesTypes.Acknowledge, result.MessageType);
        }
예제 #16
0
        public void DHCPv4RelayAgentResolver_PacketMeetsConditions()
        {
            Random             random    = new Random();
            List <IPv4Address> addresses = random.GetIPv4Addresses();

            String serializedValues = System.Text.Json.JsonSerializer.Serialize(addresses.Select(x => x.ToString()));

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

            serializer.Setup(x => x.Deserialze <IEnumerable <String> >(serializedValues)).Returns(addresses.Select(x => x.ToString()));

            DHCPv4RelayAgentResolver    resolver = new DHCPv4RelayAgentResolver();
            Dictionary <String, String> values   = new Dictionary <String, String>()
            {
                { nameof(DHCPv4RelayAgentResolver.AgentAddresses), serializedValues }
            };

            resolver.ApplyValues(values, serializer.Object);

            foreach (IPv4Address item in addresses)
            {
                Boolean shouldPass = false;

                IPv4Address gwAddress = IPv4Address.Empty;
                if (random.NextDouble() > 0.5)
                {
                    gwAddress  = item;
                    shouldPass = true;
                }
                else
                {
                    if (random.NextDouble() > 0.5)
                    {
                        gwAddress = random.GetIPv4Address();
                    }
                }

                DHCPv4Packet packet = new DHCPv4Packet(
                    new IPv4HeaderInformation(random.GetIPv4Address(), random.GetIPv4Address()),
                    random.NextBytes(6),
                    (UInt32)random.Next(),
                    IPv4Address.Empty,
                    gwAddress,
                    IPv4Address.Empty
                    );

                Boolean actual = resolver.PacketMeetsCondition(packet);
                Assert.Equal(shouldPass, actual);
            }
        }
예제 #17
0
        public static bool HasOptionThisIPv4Adress(DHCPv4Packet result, DHCPv4OptionTypes optionType, IPv4Address address)
        {
            foreach (var item in result.Options)
            {
                if (item.OptionType == (Byte)optionType)
                {
                    Assert.IsAssignableFrom<DHCPv4PacketAddressOption>(item);

                    DHCPv4PacketAddressOption castedItem = (DHCPv4PacketAddressOption)item;
                    return castedItem.Address == address;
                }
            }

            return false;
        }
예제 #18
0
        public void TestInform_ScopeNotFound()
        {
            Random random = new Random();

            IPv4Address  sourceAddress = random.GetIPv4Address();
            DHCPv4Packet input         = GetInformPacket(random, sourceAddress);

            DHCPv4RootScope rootScope = GetRootScope();
            DHCPv4Packet    result    = rootScope.HandleInform(input);

            DHCPv4InformHandledEvent domainEvent = TestResult <DHCPv4InformHandledEvent>(
                input, result, true, false, new Guid?(), rootScope);

            Assert.Equal(InformErros.ScopeNotFound, domainEvent.Error);
        }
예제 #19
0
        public static T TestResult<T>(
        DHCPv4Packet input,
        DHCPv4Packet result,
        Boolean emptyResponseExpected,
        Boolean expectedSuccessfullHandling,
        Guid? scopeId,
        DHCPv4RootScope rootScope) where T : DHCPv4PacketHandledEvent
        {
            var changes = rootScope.GetChanges();
            Assert.Single(changes);

            DomainEvent domainEvent = changes.First();
            Assert.IsAssignableFrom<T>(domainEvent);

            T castedDomainEvents = (T)domainEvent;

            if (scopeId.HasValue == false)
            {
                Assert.False(castedDomainEvents.ScopeId.HasValue);
            }
            else
            {
                Assert.True(castedDomainEvents.ScopeId.HasValue);
                Assert.Equal(scopeId.Value, castedDomainEvents.ScopeId.Value);
            }
            Assert.Equal(input, castedDomainEvents.Request);
            if (emptyResponseExpected == true)
            {
                Assert.Equal(DHCPv4Packet.Empty, result);
                Assert.Equal(DHCPv4Packet.Empty, castedDomainEvents.Response);
            }
            else
            {
                Assert.NotEqual(DHCPv4Packet.Empty, result);
                Assert.NotEqual(DHCPv4Packet.Empty, castedDomainEvents.Response);
                Assert.Equal(result, castedDomainEvents.Response);
            }
            if (expectedSuccessfullHandling == false)
            {
                Assert.False(castedDomainEvents.WasSuccessfullHandled);
            }
            else
            {
                Assert.True(castedDomainEvents.WasSuccessfullHandled);
            }

            return castedDomainEvents;
        }
예제 #20
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);
        }
예제 #21
0
        public async Task Handle(ValidDHCPv4PacketArrivedMessage notification, CancellationToken cancellationToken)
        {
            _logger.LogDebug("CURRENT STEP: Handling of packet");
            _logger.LogDebug("packet: {packetType}", notification.Packet.MessageType);

            DHCPv4Packet response = await _engine.HandlePacket(notification.Packet);

            if (response == DHCPv4Packet.Empty)
            {
                _logger.LogInformation("unable to get a repsonse for packet {packetType}", notification.Packet.MessageType);
                return;
            }

            _logger.LogDebug("STEP RESULT: Packet handled and response packet generated");
            _logger.LogDebug("NEXT STEP: Interface Engine");

            await _serviceBus.Publish(new DHCPv4PacketReadyToSendMessage(response));
        }
예제 #22
0
        public void DHCPv4RelayAgentSubnetResolver_PacketMeetsConditions2(
            String networkAddressInput,
            String maskInput,
            String relayAgentAddressInput,
            Boolean shouldPass
            )
        {
            Random random = new Random();

            IPv4SubnetMask mask           = IPv4SubnetMask.FromString(maskInput);
            IPv4Address    networkAddress = IPv4Address.FromString(networkAddressInput);

            String inputAddressValue = random.GetAlphanumericString(10);
            String inputMaskValue    = random.GetAlphanumericString(10);

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

            serializer.Setup(x => x.Deserialze <String>(mask.GetSlashNotation().ToString())).Returns(mask.GetSlashNotation().ToString());
            serializer.Setup(x => x.Deserialze <String>(networkAddress.ToString())).Returns(networkAddress.ToString());

            DHCPv4RelayAgentSubnetResolver resolver = new DHCPv4RelayAgentSubnetResolver();
            Dictionary <String, String>    values   = new Dictionary <String, String>()
            {
                { nameof(DHCPv4RelayAgentSubnetResolver.NetworkAddress), networkAddress.ToString() },
                { nameof(DHCPv4RelayAgentSubnetResolver.Mask), mask.GetSlashNotation().ToString() },
            };

            resolver.ApplyValues(values, serializer.Object);

            IPv4Address  gwAddress = IPv4Address.FromString(relayAgentAddressInput);
            DHCPv4Packet packet    = new DHCPv4Packet(
                new IPv4HeaderInformation(random.GetIPv4Address(), random.GetIPv4Address()),
                random.NextBytes(6),
                (UInt32)random.Next(),
                IPv4Address.Empty,
                gwAddress,
                IPv4Address.Empty
                );

            Boolean actual = resolver.PacketMeetsCondition(packet);

            Assert.Equal(shouldPass, actual);
        }
예제 #23
0
        public override Boolean PacketMeetsCondition(DHCPv4Packet packet)
        {
            Boolean positiveResultFound = false;

            foreach (var resolver in InnerResolvers)
            {
                Boolean resolverResult = resolver.PacketMeetsCondition(packet);
                if (resolverResult == true)
                {
                    if (positiveResultFound == true)
                    {
                        return(false);
                    }
                    else
                    {
                        positiveResultFound = true;
                    }
                }
            }

            return(positiveResultFound);
        }
예제 #24
0
        private void CheckHandeledEvent(
            Int32 index, ReleaseError error,
            DHCPv4Packet requestPacket,
            DHCPv4RootScope rootScope)
        {
            IEnumerable <DomainEvent> changes = rootScope.GetChanges();

            Assert.IsAssignableFrom <DHCPv4ReleaseHandledEvent>(changes.ElementAt(index));

            DHCPv4ReleaseHandledEvent handeledEvent = (DHCPv4ReleaseHandledEvent)changes.ElementAt(index);

            Assert.Equal(requestPacket, handeledEvent.Request);
            Assert.Equal(DHCPv4Packet.Empty, handeledEvent.Response);
            Assert.Equal(error, handeledEvent.Error);
            if (error == ReleaseError.NoError)
            {
                Assert.True(handeledEvent.WasSuccessfullHandled);
            }
            else
            {
                Assert.False(handeledEvent.WasSuccessfullHandled);
            }
        }
예제 #25
0
        protected void CheckPacketOptions(Guid scopeId, DHCPv4RootScope rootScope, DHCPv4Packet result)
        {
            var scope = rootScope.GetScopeById(scopeId);

            if (scope.Properties != null)
            {
                foreach (var item in scope.Properties.Properties)
                {
                }
            }

            var subnetOption = result.GetOptionByIdentifier((Byte)DHCPv4OptionTypes.SubnetMask) as DHCPv4PacketAddressOption;

            if (result.YourIPAdress == IPv4Address.Empty)
            {
                Assert.Null(subnetOption);
            }
            else
            {
                Assert.NotNull(subnetOption);
                Assert.True(ByteHelper.AreEqual(subnetOption.Address.GetBytes(), scope.AddressRelatedProperties.Mask.GetBytes()));
            }
        }
예제 #26
0
    public Packet buildDhcpOffer(MacAddress pSourceMacAddress, MacAddress pDestinationMacAddress, byte[] pTransactionId, byte[] pSecs)
    {
        IPAddress newClientIPAddress = IPAddress.Parse("0.0.0.0");
        bool      clientFound        = false;

        if (clientList.Count != 0)
        {
            foreach (Client item in clientList)
            {
                if (StructuralComparisons.StructuralEqualityComparer.Equals(item.macAddress, pDestinationMacAddress))
                {
                    newClientIPAddress = item.ipaddress;
                    clientFound        = true;

                    Debug.WriteLine("Listed Client has been found with IP-Binding: " + newClientIPAddress.ToString());
                }
            }
        }


        if (!clientFound)
        {
            newClientIPAddress = addressPool.getFreeIPAddress();
            Client client = new Client(newClientIPAddress.ToString(), newClientIPAddress, pTransactionId, pDestinationMacAddress);
            clientList.Add(client);

            Debug.WriteLine("Listed Client has been generated with IP-Binding: " + newClientIPAddress.ToString() + " and xid: " + BitConverter.ToString(pTransactionId) + " and MacAddress: " + pDestinationMacAddress.ToString());
        }

        IPAddress ipaddress = inter.getIPAddress();

        DHCPv4Option dhcpMessageTypeOption = new DHCPv4Option
        {
            optionId     = DHCPv4OptionIds.DhcpMessageType,
            optionLength = 0x01,
            optionValue  = new byte[] { 0x02 },
        };

        DHCPv4Option dhcpServerIdentifierOption = new DHCPv4Option
        {
            optionId     = DHCPv4OptionIds.ServerIdentifier,
            optionLength = 0x04,
            optionValue  = ipaddress.GetAddressBytes(),
        };

        DHCPv4Packet dhcpPacket = new DHCPv4Packet
        {
            op          = 0x02,
            htype       = 0x01,
            hlen        = 0x06,
            xid         = pTransactionId,
            secs        = pSecs,
            ciaddr      = new byte[] { 0x00, 0x00, 0x00, 0x00 },
            yiaddr      = newClientIPAddress.GetAddressBytes(),
            siaddr      = ipaddress.GetAddressBytes(),
            chaddr      = PhysicalAddress.Parse(pDestinationMacAddress.ToString().Replace(":", "-")).GetAddressBytes(),
            dhcpOptions = dhcpMessageTypeOption.buildDhcpOption().Concat(dhcpServerIdentifierOption.buildDhcpOption()).ToArray(),
        };

        EthernetLayer ethernetLayer = new EthernetLayer
        {
            Source      = pSourceMacAddress,
            Destination = pDestinationMacAddress
        };

        IpV4Layer ipV4Layer = new IpV4Layer
        {
            Source             = new IpV4Address(ipaddress.ToString()),
            CurrentDestination = new IpV4Address(newClientIPAddress.ToString()),
            Ttl = 128,
        };

        UdpLayer udpLayer = new UdpLayer
        {
            SourcePort      = (ushort)67,
            DestinationPort = (ushort)68,
        };

        PayloadLayer payloadLayer = new PayloadLayer
        {
            Data = new Datagram(dhcpPacket.buildPacket()),
        };

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

        return(builder.Build(DateTime.Now));
    }
예제 #27
0
    public Packet buildDhcpAck(MacAddress pSourceMacAddress, MacAddress pDestinationMacAddress, byte[] pTransactionId, byte[] pSecs)
    {
        IPAddress newClientIPAddress = IPAddress.Parse("0.0.0.0");
        bool      clientFound        = false;

        if (clientList.Count != 0)
        {
            foreach (Client item in clientList)
            {
                if (StructuralComparisons.StructuralEqualityComparer.Equals(item.macAddress, pDestinationMacAddress))
                {
                    newClientIPAddress = item.ipaddress;
                    clientFound        = true;

                    Debug.WriteLine("Listed Client has been found with IP-Binding: " + newClientIPAddress.ToString());
                }
            }
        }

        if (!clientFound)
        {
            Debug.WriteLine("Server sends a NAK. There is no TransactionId paired to a leased IP-Address! The Server did not received a DISCOVER from the Client");
        }

        IPAddress ipaddress  = inter.getIPAddress();
        IPAddress subnetmask = inter.getNetmask();

        DHCPv4Option dhcpMessageTypeOption = new DHCPv4Option
        {
            optionId     = DHCPv4OptionIds.DhcpMessageType,
            optionLength = 0x01,
            optionValue  = new byte[] { 0x05 },
        };

        DHCPv4Option dhcpServerIdentifierOption = new DHCPv4Option
        {
            optionId     = DHCPv4OptionIds.ServerIdentifier,
            optionLength = 0x04,
            optionValue  = ipaddress.GetAddressBytes(),
        };

        DHCPv4Option ipAddressLeaseTimeOption = new DHCPv4Option
        {
            optionId     = DHCPv4OptionIds.IpAddressLeaseTime,
            optionLength = 0x04,
            optionValue  = new byte[] { 0x00, 0x0d, 0x2f, 0x00 },
        };

        DHCPv4Option renewalTimeValueOption = new DHCPv4Option
        {
            optionId     = DHCPv4OptionIds.RenewalTimeValue,
            optionLength = 0x04,
            optionValue  = new byte[] { 0x00, 0x06, 0x97, 0x80 },
        };

        DHCPv4Option rebindTimeValueOption = new DHCPv4Option
        {
            optionId     = DHCPv4OptionIds.RebindingTimeValue,
            optionLength = 0x04,
            optionValue  = new byte[] { 0x00, 0x0b, 0x89, 0x20 },
        };


        DHCPv4Option subnetMaskOption = new DHCPv4Option
        {
            optionId     = DHCPv4OptionIds.Subnetmask,
            optionLength = 0x04,
            optionValue  = subnetmask.GetAddressBytes(),
        };

        DHCPv4Option routerOption = new DHCPv4Option
        {
            optionId     = DHCPv4OptionIds.Router,
            optionLength = 0x04,
            optionValue  = addressPool.getGatewayIpAddress().GetAddressBytes(),
        };

        DHCPv4Option domainNameServerOption = new DHCPv4Option
        {
            optionId     = DHCPv4OptionIds.DomainNameServer,
            optionLength = 0x04,
            optionValue  = ipaddress.GetAddressBytes(),
        };

        DHCPv4Option domainNameOption = new DHCPv4Option
        {
            optionId     = DHCPv4OptionIds.DomainName,
            optionLength = (byte)addressPool.getDomainName().Length,
            optionValue  = Encoding.ASCII.GetBytes(addressPool.getDomainName()),
        };

        DHCPv4Packet dhcpPacket = new DHCPv4Packet
        {
            op          = 0x02,
            htype       = 0x01,
            hlen        = 0x06,
            xid         = pTransactionId,
            secs        = pSecs,
            ciaddr      = new byte[] { 0x00, 0x00, 0x00, 0x00 },
            yiaddr      = newClientIPAddress.GetAddressBytes(),
            siaddr      = ipaddress.GetAddressBytes(),
            chaddr      = PhysicalAddress.Parse(pDestinationMacAddress.ToString().Replace(":", "-")).GetAddressBytes(),
            dhcpOptions = dhcpMessageTypeOption.buildDhcpOption().Concat(dhcpServerIdentifierOption.buildDhcpOption()).Concat(ipAddressLeaseTimeOption.buildDhcpOption()).Concat(renewalTimeValueOption.buildDhcpOption()).Concat(rebindTimeValueOption.buildDhcpOption()).Concat(subnetMaskOption.buildDhcpOption()).Concat(routerOption.buildDhcpOption()).Concat(domainNameServerOption.buildDhcpOption()).Concat(domainNameOption.buildDhcpOption()).ToArray(),
        };

        EthernetLayer ethernetLayer = new EthernetLayer
        {
            Source      = pSourceMacAddress,
            Destination = pDestinationMacAddress
        };

        IpV4Layer ipV4Layer = new IpV4Layer
        {
            Source             = new IpV4Address(ipaddress.ToString()),
            CurrentDestination = new IpV4Address(newClientIPAddress.ToString()),
            Ttl = 128,
        };

        UdpLayer udpLayer = new UdpLayer
        {
            SourcePort      = (ushort)67,
            DestinationPort = (ushort)68,
        };

        PayloadLayer payloadLayer = new PayloadLayer
        {
            Data = new Datagram(dhcpPacket.buildPacket()),
        };

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

        return(builder.Build(DateTime.Now));
    }
예제 #28
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);
        }
예제 #29
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);
        }
예제 #30
0
 public DHCPv4DeclineHandledEvent(DHCPv4Packet request) : this(request, DeclineErros.ScopeNotFound)
 {
 }