public void GetInnerPacket_MultipleEncapsulated() { IPv6HeaderInformation header = new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")); Int32 depth = 10; DHCPv6Packet expectedInnerPacket = DHCPv6Packet.AsInner(1, DHCPv6PacketTypes.REPLY, Array.Empty <DHCPv6PacketOption>()); DHCPv6Packet innerPacket = expectedInnerPacket; for (int i = 0; i < depth; i++) { DHCPv6RelayPacket outerPacket = DHCPv6RelayPacket.AsInnerRelay( true, 1, IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2"), Array.Empty <DHCPv6PacketOption>(), innerPacket); innerPacket = outerPacket; } DHCPv6RelayPacket inputPacket = DHCPv6RelayPacket.AsOuterRelay( header, true, 1, IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2"), Array.Empty <DHCPv6PacketOption>(), innerPacket); DHCPv6Packet actualInnerPacket = inputPacket.GetInnerPacket(); Assert.Equal(expectedInnerPacket, actualInnerPacket); }
private DHCPv6Packet GetPacket(Random random, Byte[] remoteId, Int32 slotId, Int32 portId, Int32 enterpriseId = 0, Boolean includeRelevantOptions = true) { IPv6HeaderInformation headerInformation = new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")); var packetOptions = new List <DHCPv6PacketOption> { new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit), }; DHCPv6Packet innerPacket = DHCPv6Packet.AsInner(random.NextUInt16(), DHCPv6PacketTypes.Solicit, packetOptions); DHCPv6Packet innerRelayPacket = DHCPv6RelayPacket.AsInnerRelay(true, 1, random.GetIPv6Address(), random.GetIPv6Address(), new DHCPv6PacketOption[] { new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, new UUIDDUID(random.NextGuid())), includeRelevantOptions == true ? (DHCPv6PacketOption)(new DHCPv6PacketRemoteIdentifierOption((UInt32)enterpriseId, remoteId)) : new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit), includeRelevantOptions == true ? (DHCPv6PacketOption)(new DHCPv6PacketByteArrayOption(DHCPv6PacketOptionTypes.InterfaceId, GetExpectedByteSequence(slotId, portId))) : new DHCPv6PacketTimeOption(DHCPv6PacketOptionTypes.ElapsedTime, 10, DHCPv6PacketTimeOption.DHCPv6PacketTimeOptionUnits.Minutes) }, innerPacket); DHCPv6Packet outerRelayPacket = DHCPv6RelayPacket.AsOuterRelay(headerInformation, true, 1, random.GetIPv6Address(), random.GetIPv6Address(), new DHCPv6PacketOption[] { new DHCPv6PacketByteArrayOption(DHCPv6PacketOptionTypes.InterfaceId, random.NextBytes(10)), new DHCPv6PacketRemoteIdentifierOption(9, random.NextBytes(12)) }, innerRelayPacket); return(outerRelayPacket); }
public void PacketMeetsCondition_False_WrongPacketType() { Random random = new Random(); UInt32 enterpriseNumber = random.NextUInt32(); Int32 agentIndex = 2; DHCPv6RemoteIdentifierEnterpriseNumberResolver resolver = new DHCPv6RemoteIdentifierEnterpriseNumberResolver( Mock.Of <ILogger <DHCPv6RemoteIdentifierEnterpriseNumberResolver> >()); Mock <ISerializer> serializerMock = new Mock <ISerializer>(MockBehavior.Strict); serializerMock.Setup(x => x.Deserialze <UInt32>(enterpriseNumber.ToString())).Returns(enterpriseNumber).Verifiable(); serializerMock.Setup(x => x.Deserialze <Int32?>(agentIndex.ToString())).Returns(agentIndex).Verifiable(); resolver.ApplyValues(new Dictionary <String, String> { { "EnterpriseNumber", enterpriseNumber.ToString() }, { "RelayAgentIndex", agentIndex.ToString() }, }, serializerMock.Object); DHCPv6Packet packet = DHCPv6Packet.AsInner(random.NextUInt16(), DHCPv6PacketTypes.Solicit, Array.Empty <DHCPv6PacketOption>()); Boolean result = resolver.PacketMeetsCondition(packet); Assert.False(result); serializerMock.Verify(); }
public void PacketMeetsCondition(Boolean isInSubnet) { Random random = new Random(); String ipAddress = "fe80::0"; Byte subnetmaskLength = 32; IPv6Address address = IPv6Address.FromString(ipAddress); IPv6SubnetMask mask = new IPv6SubnetMask(new IPv6SubnetMaskIdentifier(subnetmaskLength)); Mock <ISerializer> serializerMock = new Mock <ISerializer>(MockBehavior.Strict); serializerMock.Setup(x => x.Deserialze <IPv6Address>(ipAddress)).Returns(address).Verifiable(); serializerMock.Setup(x => x.Deserialze <IPv6SubnetMask>(subnetmaskLength.ToString())).Returns(mask).Verifiable(); DHCPv6RelayAgentSubnetResolver resolver = new DHCPv6RelayAgentSubnetResolver(); resolver.ApplyValues(new Dictionary <String, String> { { "NetworkAddress", ipAddress }, { "SubnetMask", subnetmaskLength.ToString() }, }, serializerMock.Object); var packet = DHCPv6RelayPacket.AsOuterRelay(new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")), true, 1, random.GetIPv6Address(), random.GetIPv6Address(), Array.Empty <DHCPv6PacketOption>(), DHCPv6RelayPacket.AsInnerRelay( true, 0, isInSubnet == true ? IPv6Address.FromString("fe80::1") : IPv6Address.FromString("2004::1"), IPv6Address.FromString("fe80::1"), new DHCPv6PacketOption[] { }, DHCPv6Packet.AsInner(random.NextUInt16(), DHCPv6PacketTypes.Solicit, Array.Empty <DHCPv6PacketOption>()))); Boolean result = resolver.PacketMeetsCondition(packet); Assert.Equal(isInSubnet, result); serializerMock.Verify(); }
private DHCPv6Packet GetPacket(Random random, Byte[] remoteId, Boolean includeRemoteIdOption = true) { IPv6HeaderInformation headerInformation = new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")); var packetOptions = new List <DHCPv6PacketOption> { new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit), }; DHCPv6Packet innerPacket = DHCPv6Packet.AsInner(random.NextUInt16(), DHCPv6PacketTypes.Solicit, packetOptions); DHCPv6Packet innerRelayPacket = DHCPv6RelayPacket.AsInnerRelay(true, 1, random.GetIPv6Address(), random.GetIPv6Address(), new DHCPv6PacketOption[] { new DHCPv6PacketByteArrayOption(DHCPv6PacketOptionTypes.InterfaceId, random.NextBytes(10)), includeRemoteIdOption == true ? (DHCPv6PacketOption)(new DHCPv6PacketRemoteIdentifierOption(3561, remoteId)) : new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit) }, innerPacket); DHCPv6Packet outerRelayPacket = DHCPv6RelayPacket.AsOuterRelay(headerInformation, true, 1, random.GetIPv6Address(), random.GetIPv6Address(), new DHCPv6PacketOption[] { new DHCPv6PacketByteArrayOption(DHCPv6PacketOptionTypes.InterfaceId, random.NextBytes(10)), new DHCPv6PacketRemoteIdentifierOption(9, random.NextBytes(12)) }, innerRelayPacket); return(outerRelayPacket); }
public void FromByteArray_RelayPacket_SingleRelayPacket() { Random random = new Random(); UInt32 transactionId = (UInt32)random.Next(0, 256 * 256 * 256); IPv6HeaderInformation header = new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")); DHCPv6Packet innerPacket = DHCPv6Packet.AsInner(transactionId, DHCPv6PacketTypes.Solicit, new List <DHCPv6PacketOption> { new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit), new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.ReconfigureAccepte), }); DHCPv6RelayPacket relayPacket = DHCPv6RelayPacket.AsOuterRelay( header, true, random.NextByte(), IPv6Address.FromString("fe80::acde"), IPv6Address.FromString("fe80::acdf"), new List <DHCPv6PacketOption> { new DHCPv6PacketByteArrayOption(DHCPv6PacketOptionTypes.InterfaceId, random.NextBytes(23)), new DHCPv6PacketRemoteIdentifierOption(random.NextUInt32(), random.NextBytes(15)) }, innerPacket); CheckByteRepresentation(relayPacket, header); }
public async Task ShouldPacketBeFilterd_True(Int32 filterAmount, Int32 index) { DHCPv6Packet packet = DHCPv6Packet.AsInner(1, DHCPv6PacketTypes.Solicit, new List <DHCPv6PacketOption>()); List <Mock <IDHCPv6PacketFilter> > filterMocks = new List <Mock <IDHCPv6PacketFilter> >(); for (int i = 0; i < filterAmount; i++) { Mock <IDHCPv6PacketFilter> filterMock = new Mock <IDHCPv6PacketFilter>(MockBehavior.Strict); filterMock.Setup(x => x.ShouldPacketBeFiltered(packet)).ReturnsAsync(i == index).Verifiable(); filterMocks.Add(filterMock); } IDHCPv6PacketFilterEngine engine = new SimpleDHCPv6PacketFilterEngine(filterMocks.Select(x => x.Object), Mock.Of <ILogger <SimpleDHCPv6PacketFilterEngine> >()); (bool, string)result = await engine.ShouldPacketBeFilterd(packet); Assert.True(result.Item1); Assert.False(String.IsNullOrEmpty(result.Item2)); for (int i = 0; i < filterMocks.Count; i++) { var filterMock = filterMocks[i]; if (i <= index) { filterMock.Verify(); } else { filterMock.Verify(x => x.ShouldPacketBeFiltered(packet), Times.Never); } } }
public async Task ShouldPacketBeFilterd_False() { DHCPv6Packet packet = DHCPv6Packet.AsInner(1, DHCPv6PacketTypes.Solicit, new List <DHCPv6PacketOption>()); List <Mock <IDHCPv6PacketFilter> > filterMocks = new List <Mock <IDHCPv6PacketFilter> >(); for (int i = 0; i < 10; i++) { Mock <IDHCPv6PacketFilter> filterMock = new Mock <IDHCPv6PacketFilter>(MockBehavior.Strict); filterMock.Setup(x => x.ShouldPacketBeFiltered(packet)).ReturnsAsync(false).Verifiable(); filterMocks.Add(filterMock); } IDHCPv6PacketFilterEngine engine = new SimpleDHCPv6PacketFilterEngine(filterMocks.Select(x => x.Object), Mock.Of <ILogger <SimpleDHCPv6PacketFilterEngine> >()); (bool, string)result = await engine.ShouldPacketBeFilterd(packet); Assert.False(result.Item1); Assert.True(String.IsNullOrEmpty(result.Item2)); foreach (var item in filterMocks) { item.Verify(); } }
public void PacketMeetsCondition(Boolean shouldMeetCondition) { Random random = new Random(); String duidBytes = "000300015CA62DD98800"; LinkLayerAddressDUID duid = new LinkLayerAddressDUID( LinkLayerAddressDUID.DUIDLinkLayerTypes.Ethernet, new Byte[] { 0x5c, 0xa6, 0x2d, 0xd9, 0x88, 0x00 }); Mock <ISerializer> serializerMock = new Mock <ISerializer>(MockBehavior.Strict); serializerMock.Setup(x => x.Deserialze <String>(duidBytes)).Returns(duidBytes).Verifiable(); var resolver = new DHCPv6ClientDUIDResolver(); resolver.ApplyValues(new Dictionary <String, String> { { "ClientDuid", duidBytes }, }, serializerMock.Object); var packet = DHCPv6RelayPacket.AsOuterRelay(new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")), true, 1, random.GetIPv6Address(), random.GetIPv6Address(), Array.Empty <DHCPv6PacketOption>(), DHCPv6RelayPacket.AsInnerRelay( true, 0, IPv6Address.FromString("2004::1"), IPv6Address.FromString("fe80::1"), new DHCPv6PacketOption[] { }, DHCPv6Packet.AsInner(random.NextUInt16(), DHCPv6PacketTypes.Solicit, new[] { new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, shouldMeetCondition == true ? (DUID)duid : new UUIDDUID(random.NextGuid())) }))); Boolean result = resolver.PacketMeetsCondition(packet); Assert.Equal(shouldMeetCondition, result); serializerMock.Verify(); }
public void PacketMeetsCondition(Boolean shouldMeetCondition) { Random random = new Random(); String ipAddress = "fe80::1"; IPv6Address address = IPv6Address.FromString(ipAddress); Mock <ISerializer> serializerMock = new Mock <ISerializer>(MockBehavior.Strict); serializerMock.Setup(x => x.Deserialze <IPv6Address>(ipAddress)).Returns(address).Verifiable(); var resolver = new DHCPv6RelayAgentResolver(); resolver.ApplyValues(new Dictionary <String, String> { { "RelayAgentAddress", ipAddress }, }, serializerMock.Object); var packet = DHCPv6RelayPacket.AsOuterRelay(new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")), true, 1, random.GetIPv6Address(), random.GetIPv6Address(), Array.Empty <DHCPv6PacketOption>(), DHCPv6RelayPacket.AsInnerRelay( true, 0, shouldMeetCondition == true ? IPv6Address.FromString(ipAddress) : IPv6Address.FromString("2004::1"), IPv6Address.FromString("fe80::1"), new DHCPv6PacketOption[] { }, DHCPv6Packet.AsInner(random.NextUInt16(), DHCPv6PacketTypes.Solicit, Array.Empty <DHCPv6PacketOption>()))); Boolean result = resolver.PacketMeetsCondition(packet); Assert.Equal(shouldMeetCondition, result); serializerMock.Verify(); }
private DHCPv6Packet GetRelayedRebindPacket( 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 innerPacket = DHCPv6Packet.AsInner(random.NextUInt16(), DHCPv6PacketTypes.REBIND, packetOptions); DHCPv6Packet packet = DHCPv6RelayPacket.AsOuterRelay(headerInformation, true, 1, random.GetIPv6Address(), random.GetIPv6Address(), new DHCPv6PacketOption[] { new DHCPv6PacketByteArrayOption(DHCPv6PacketOptionTypes.InterfaceId, random.NextBytes(10)) }, innerPacket); return(packet); }
private static DHCPv6RelayPacket GeneratePacket(Random random, uint enterpriseNumber) { return(DHCPv6RelayPacket.AsOuterRelay( new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")), true, 0, IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::1"), new DHCPv6PacketOption[] { new DHCPv6PacketRemoteIdentifierOption(enterpriseNumber, random.NextBytes(20)), }, DHCPv6Packet.AsInner(random.NextUInt16(), DHCPv6PacketTypes.Solicit, Array.Empty <DHCPv6PacketOption>()))); }
public async Task HandleInvalidPacket() { Random random = new Random(); String dbName = $"{random.Next()}"; var(client, serviceBus) = GetTestClient(dbName); try { IPv6HeaderInformation headerInformation = new IPv6HeaderInformation( IPv6Address.FromString("fe80::2"), IPv6Address.FromString("fe80::1")); DHCPv6Packet packet = DHCPv6RelayPacket.AsOuterRelay(headerInformation, true, 1, IPv6Address.FromString("fe80::3"), IPv6Address.FromString("fe80::4"), Array.Empty <DHCPv6PacketOption>(), DHCPv6Packet.AsInner(1, DHCPv6PacketTypes.ADVERTISE, new List <DHCPv6PacketOption>())); var message = new DHCPv6PacketArrivedMessage(packet); await serviceBus.Publish(message); await Task.Delay(2000); StorageContext initicalContext = DatabaseTestingUtility.GetTestDatabaseContext(dbName); Int32 tries = 10; while (tries-- > 0) { if (initicalContext.DHCPv6PacketEntries.Count() == 1) { break; } await Task.Delay(1000); } Assert.Equal(1, await initicalContext.DHCPv6PacketEntries.AsQueryable().CountAsync()); var firstEntry = await initicalContext.DHCPv6PacketEntries.AsQueryable().FirstAsync(); Assert.NotEqual(Guid.Empty, firstEntry.Id); Assert.False(firstEntry.InvalidRequest); Assert.Equal(packet.GetSize(), firstEntry.RequestSize); Assert.Equal(DHCPv6PacketTypes.ADVERTISE, firstEntry.RequestType); Assert.Equal(nameof(DHCPv6PacketConsistencyFilter), firstEntry.FilteredBy); Assert.True((DateTime.UtcNow - firstEntry.Timestamp).TotalSeconds < 20); Assert.NotEqual(DateTime.MinValue, firstEntry.TimestampDay); Assert.NotEqual(DateTime.MinValue, firstEntry.TimestampWeek); Assert.NotEqual(DateTime.MinValue, firstEntry.TimestampMonth); } finally { await DatabaseTestingUtility.DeleteDatabase(dbName); } }
public void ConstructPacket_MultipleRelayPackets() { IPv6HeaderInformation header = new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")); Int32 depth = 10; DHCPv6Packet receivedInnerPacket = DHCPv6Packet.AsInner(1, DHCPv6PacketTypes.Solicit, Array.Empty <DHCPv6PacketOption>()); DHCPv6Packet innerPacket = receivedInnerPacket; List <IPv6Address> expectedLinkAddresses = new List <IPv6Address>(); for (int i = 0; i < depth; i++) { IPv6Address linkAddress = IPv6Address.FromString($"fe{i}::1"); DHCPv6RelayPacket outerPacket = DHCPv6RelayPacket.AsInnerRelay( true, 1, linkAddress, IPv6Address.FromString($"fe{i}::2"), Array.Empty <DHCPv6PacketOption>(), innerPacket); innerPacket = outerPacket; expectedLinkAddresses.Insert(0, linkAddress); } DHCPv6RelayPacket inputPacket = DHCPv6RelayPacket.AsOuterRelay( header, true, 1, IPv6Address.FromString("ff70::1"), IPv6Address.FromString("fe80::2"), Array.Empty <DHCPv6PacketOption>(), innerPacket); expectedLinkAddresses.Insert(0, IPv6Address.FromString("ff70::1")); DHCPv6Packet sendInnerPacket = DHCPv6Packet.AsInner(1, DHCPv6PacketTypes.ADVERTISE, Array.Empty <DHCPv6PacketOption>()); DHCPv6Packet packet = DHCPv6Packet.ConstructPacket(inputPacket, sendInnerPacket); Assert.IsAssignableFrom <DHCPv6RelayPacket>(packet); DHCPv6RelayPacket relayPacket = (DHCPv6RelayPacket)packet; DHCPv6Packet innerUsedPacket = relayPacket.GetInnerPacket(); Assert.Equal(sendInnerPacket, innerUsedPacket); for (int i = 0; i < expectedLinkAddresses.Count; i++) { DHCPv6RelayPacket innerRelayPacket = GetInnerRelayPacket(relayPacket, i); Assert.Equal(innerRelayPacket.LinkAddress, expectedLinkAddresses[i]); Assert.Equal((Byte)(expectedLinkAddresses.Count - i - 1), innerRelayPacket.HopCount); } }
private DHCPv6Packet GetRelayedConfirmPacket( Random random, out IPv6Address usedAddress, out DUID clientDuid, out UInt32 iaId, out DHCPv6PrefixDelegation prefixDelegation, Boolean withAddress, Boolean withPrefix) { IPv6HeaderInformation headerInformation = new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")); clientDuid = new UUIDDUID(random.NextGuid()); usedAddress = IPv6Address.Empty; prefixDelegation = DHCPv6PrefixDelegation.None; iaId = 0; var packetOptions = new List <DHCPv6PacketOption>() { new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, clientDuid), }; if (withAddress == true) { iaId = random.NextUInt32(); usedAddress = random.GetIPv6Address(); 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>()) })); } if (withPrefix == true) { IPv6Address prefix = IPv6Address.FromString("2acd:adce::0"); UInt32 prefixId = random.NextBoolean() == false?random.NextUInt32() : 0; Byte mask = (Byte)random.Next(64, 80); prefixDelegation = DHCPv6PrefixDelegation.FromValues(prefix, new IPv6SubnetMask(new IPv6SubnetMaskIdentifier(mask)), prefixId); packetOptions.Add(new DHCPv6PacketIdentityAssociationPrefixDelegationOption(prefixId, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), new DHCPv6PacketSuboption[] { new DHCPv6PacketIdentityAssociationPrefixDelegationSuboption(TimeSpan.Zero, TimeSpan.Zero, mask, prefix, Array.Empty <DHCPv6PacketSuboption>()) })); } DHCPv6Packet innerPacket = DHCPv6Packet.AsInner(random.NextUInt16(), DHCPv6PacketTypes.CONFIRM, packetOptions); DHCPv6Packet packet = DHCPv6RelayPacket.AsOuterRelay(headerInformation, true, 1, random.GetIPv6Address(), random.GetIPv6Address(), new DHCPv6PacketOption[] { new DHCPv6PacketByteArrayOption(DHCPv6PacketOptionTypes.InterfaceId, random.NextBytes(10)) }, innerPacket); return(packet); }
public void GetInnerPacket_SingleEncapsulated() { IPv6HeaderInformation header = new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")); DHCPv6Packet innerPacket = DHCPv6Packet.AsInner(1, DHCPv6PacketTypes.REPLY, Array.Empty <DHCPv6PacketOption>()); DHCPv6RelayPacket outerPacket = DHCPv6RelayPacket.AsOuterRelay( header, true, 1, IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2"), Array.Empty <DHCPv6PacketOption>(), innerPacket); DHCPv6Packet actualInnerPacket = outerPacket.GetInnerPacket(); Assert.Equal(innerPacket, actualInnerPacket); }
public async Task Filter_IsClientRequest_IsConsistent() { Random random = new Random(); DHCPv6PacketConsistencyFilter filter = new DHCPv6PacketConsistencyFilter( Mock.Of <ILogger <DHCPv6PacketConsistencyFilter> >()); DHCPv6Packet packet = DHCPv6Packet.AsInner( 1, DHCPv6PacketTypes.Solicit, new List <DHCPv6PacketOption> { new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, new UUIDDUID(random.NextGuid())), }); Boolean result = await filter.ShouldPacketBeFiltered(packet); Assert.False(result); }
public void GetUniqueIdentifier() { LinkLayerAddressDUID duid = new LinkLayerAddressDUID( LinkLayerAddressDUID.DUIDLinkLayerTypes.Ethernet, new Byte[] { 0x5c, 0xa6, 0x2d, 0xd9, 0x88, 0x00 }); Random random = new Random(); var packet = DHCPv6RelayPacket.AsOuterRelay(new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")), true, 1, random.GetIPv6Address(), random.GetIPv6Address(), Array.Empty <DHCPv6PacketOption>(), DHCPv6RelayPacket.AsInnerRelay( true, 0, IPv6Address.FromString("2004::1"), IPv6Address.FromString("fe80::1"), new DHCPv6PacketOption[] { }, DHCPv6Packet.AsInner(random.NextUInt16(), DHCPv6PacketTypes.Solicit, new[] { new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, duid) }))); var resolver = new DeviceBasedDHCPv6ClientDUIDResolver(Mock.Of <IDeviceService>(MockBehavior.Strict)); Assert.Equal(duid.GetAsByteStream(), resolver.GetUniqueIdentifier(packet)); }
public async Task Handle(Boolean storageResult) { IPv6HeaderInformation headerInformation = new IPv6HeaderInformation( IPv6Address.FromString("fe80::2"), IPv6Address.FromString("fe80::1")); DHCPv6Packet packet = DHCPv6RelayPacket.AsOuterRelay(headerInformation, true, 1, IPv6Address.FromString("fe80::3"), IPv6Address.FromString("fe80::4"), Array.Empty <DHCPv6PacketOption>(), DHCPv6Packet.AsInner(1, DHCPv6PacketTypes.Unkown, new List <DHCPv6PacketOption>())); Mock <IDHCPv6StorageEngine> storageEngineMock = new Mock <IDHCPv6StorageEngine>(MockBehavior.Strict); storageEngineMock.Setup(x => x.LogInvalidDHCPv6Packet(packet)).ReturnsAsync(storageResult); InvalidDHCPv6PacketArrivedMessageHandler handler = new InvalidDHCPv6PacketArrivedMessageHandler( storageEngineMock.Object, Mock.Of <ILogger <InvalidDHCPv6PacketArrivedMessageHandler> >()); await handler.Handle(new InvalidDHCPv6PacketArrivedMessage(packet), CancellationToken.None); storageEngineMock.Verify(); }
public async Task Filter_CouldHaveValue_ValueNotMatchesServerDUID() { Random random = new Random(); UUIDDUID serverDuid = new UUIDDUID(random.NextGuid()); DHCPv6PacketServerIdentifierFilter filter = new DHCPv6PacketServerIdentifierFilter( serverDuid, Mock.Of <ILogger <DHCPv6PacketServerIdentifierFilter> >()); DHCPv6Packet packet = DHCPv6Packet.AsInner( 1, DHCPv6PacketTypes.INFORMATION_REQUEST, new List <DHCPv6PacketOption> { new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ServerIdentifer, new UUIDDUID(random.NextGuid())), }); Boolean result = await filter.ShouldPacketBeFiltered(packet); Assert.True(result); }
public void GetRelayPacketChain() { IPv6HeaderInformation header = new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")); Int32 depth = 10; DHCPv6Packet innerPacket = DHCPv6Packet.AsInner(1, DHCPv6PacketTypes.REPLY, Array.Empty <DHCPv6PacketOption>());; for (int i = 0; i < depth; i++) { DHCPv6RelayPacket outerPacket = DHCPv6RelayPacket.AsInnerRelay( true, 1, IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2"), Array.Empty <DHCPv6PacketOption>(), innerPacket); innerPacket = outerPacket; } DHCPv6RelayPacket inputPacket = DHCPv6RelayPacket.AsOuterRelay( header, true, 1, IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2"), Array.Empty <DHCPv6PacketOption>(), innerPacket); var chain = inputPacket.GetRelayPacketChain(); Assert.NotEmpty(chain); Assert.Equal(depth + 1, chain.Count); Assert.NotEqual(DHCPv6PacketTypes.RELAY_FORW, chain[0].InnerPacket.PacketType); Assert.NotEqual(DHCPv6PacketTypes.RELAY_REPL, chain[0].InnerPacket.PacketType); for (int i = 1; i < chain.Count; i++) { Assert.Equal(chain[i].InnerPacket, chain[i - 1]); } Assert.Equal(inputPacket, chain[depth]); }
public async Task Handle_PacketNotFiltered() { DHCPv6Packet packet = DHCPv6Packet.AsInner(1, DHCPv6PacketTypes.Solicit, new List <DHCPv6PacketOption>()); Mock <IDHCPv6PacketFilterEngine> filterEngineMock = new Mock <IDHCPv6PacketFilterEngine>(MockBehavior.Strict); filterEngineMock.Setup(x => x.ShouldPacketBeFilterd(packet)).ReturnsAsync((false, null)).Verifiable(); Mock <IServiceBus> serviceBusMock = new Mock <IServiceBus>(MockBehavior.Strict); serviceBusMock.Setup(x => x.Publish(It.Is <ValidDHCPv6PacketArrivedMessage>(y => y.Packet == packet))).Returns(Task.CompletedTask).Verifiable(); DHCPv6PacketArrivedMessageHandler handler = new DHCPv6PacketArrivedMessageHandler( serviceBusMock.Object, filterEngineMock.Object, Mock.Of <ILogger <DHCPv6PacketArrivedMessageHandler> >()); await handler.Handle(new DHCPv6PacketArrivedMessage(packet), CancellationToken.None); filterEngineMock.Verify(); serviceBusMock.Verify(); }
protected void CheckMeetsConditions( Func <IScopeResolverContainingOtherResolvers <DHCPv6Packet, IPv6Address> > resolverCreater, IEnumerable <Tuple <Boolean, Boolean, Boolean> > inputs) { foreach (var item in inputs) { var resolver = resolverCreater(); DHCPv6Packet packet = DHCPv6Packet.AsInner(2, DHCPv6PacketTypes.Solicit, Array.Empty <DHCPv6PacketOption>()); Mock <IScopeResolver <DHCPv6Packet, IPv6Address> > firstInnerMock = new Mock <IScopeResolver <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict); firstInnerMock.Setup(x => x.PacketMeetsCondition(packet)).Returns(item.Item1); Mock <IScopeResolver <DHCPv6Packet, IPv6Address> > secondInnerMock = new Mock <IScopeResolver <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict); secondInnerMock.Setup(x => x.PacketMeetsCondition(packet)).Returns(item.Item2); resolver.AddResolver(firstInnerMock.Object); resolver.AddResolver(secondInnerMock.Object); Boolean result = resolver.PacketMeetsCondition(packet); Assert.Equal(item.Item3, result); } }
public async Task Handle(Boolean storageResult) { Random random = new Random(); String filtername = random.GetAlphanumericString(); IPv6HeaderInformation headerInformation = new IPv6HeaderInformation( IPv6Address.FromString("fe80::2"), IPv6Address.FromString("fe80::1")); DHCPv6Packet packet = DHCPv6RelayPacket.AsOuterRelay(headerInformation, true, 1, IPv6Address.FromString("fe80::3"), IPv6Address.FromString("fe80::4"), Array.Empty <DHCPv6PacketOption>(), DHCPv6Packet.AsInner(1, DHCPv6PacketTypes.ADVERTISE, new List <DHCPv6PacketOption>())); Mock <IDHCPv6StorageEngine> storageEngineMock = new Mock <IDHCPv6StorageEngine>(MockBehavior.Strict); storageEngineMock.Setup(x => x.LogFilteredDHCPv6Packet(packet, filtername)).ReturnsAsync(storageResult); DHCPv6PacketFileteredMessageHandler handler = new DHCPv6PacketFileteredMessageHandler( storageEngineMock.Object, Mock.Of <ILogger <DHCPv6PacketFileteredMessageHandler> >()); await handler.Handle(new DHCPv6PacketFilteredMessage(packet, filtername), CancellationToken.None); storageEngineMock.Verify(); }
public async Task Filter_ShouldNotHaveValue(Boolean valueIsPresented) { Random random = new Random(); UUIDDUID serverDuid = new UUIDDUID(random.NextGuid()); DHCPv6PacketServerIdentifierFilter filter = new DHCPv6PacketServerIdentifierFilter( serverDuid, Mock.Of <ILogger <DHCPv6PacketServerIdentifierFilter> >()); var options = new List <DHCPv6PacketOption>(); if (valueIsPresented == true) { options.Add(new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ServerIdentifer, serverDuid)); } DHCPv6Packet packet = DHCPv6Packet.AsInner( 1, DHCPv6PacketTypes.Solicit, options); Boolean result = await filter.ShouldPacketBeFiltered(packet); Assert.False(result); }
public void PacketMeetsCondition(Boolean shouldMeetCondition) { Random random = new Random(); Guid deviceId = random.NextGuid(); String ipAddress = "fe80::1"; IPv6Address address = IPv6Address.FromString(ipAddress); Mock <ISerializer> serializerMock = new Mock <ISerializer>(MockBehavior.Strict); serializerMock.Setup(x => x.Deserialze <Guid>(deviceId.ToString())).Returns(deviceId).Verifiable(); Mock <IDeviceService> deviceServiceMock = new Mock <IDeviceService>(MockBehavior.Strict); deviceServiceMock.Setup(x => x.GetIPv6LinkLocalAddressFromDevice(deviceId)).Returns(address).Verifiable(); var resolver = new DeviceBasedDHCPv6PeerAddressResolver(deviceServiceMock.Object); resolver.ApplyValues(new Dictionary <String, String> { { "DeviceId", deviceId.ToString() }, }, serializerMock.Object); var packet = DHCPv6RelayPacket.AsOuterRelay(new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")), true, 1, random.GetIPv6Address(), random.GetIPv6Address(), Array.Empty <DHCPv6PacketOption>(), DHCPv6RelayPacket.AsInnerRelay( true, 0, IPv6Address.FromString("fe80::1"), shouldMeetCondition == true ? IPv6Address.FromString(ipAddress) : IPv6Address.FromString("2004::1"), new DHCPv6PacketOption[] { }, DHCPv6Packet.AsInner(random.NextUInt16(), DHCPv6PacketTypes.Solicit, Array.Empty <DHCPv6PacketOption>()))); Boolean result = resolver.PacketMeetsCondition(packet); Assert.Equal(shouldMeetCondition, result); serializerMock.Verify(); }
//[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); } }
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(); } }
public async Task SaveAndHydrateRootScope_AddAndRemoveLeases() { Random random = new Random(); await ExecuteWithStreamErase(random, async (eventStore) => { Mock <IDHCPv6ServerPropertiesResolver> propertyResolverMock; DHCPv6StorageEngine engine; PrepareEngine(random, eventStore, out propertyResolverMock, out engine); DHCPv6RootScope initialRootScope = await engine.GetRootScope(); Guid rootScopeId = random.NextGuid(); 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: false, 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), random.NextUInt16().ToString() }, { nameof(DHCPv6RemoteIdentifierEnterpriseNumberResolver.RelayAgentIndex), 0.ToString() }, } }, Name = "Testscope", Id = rootScopeId, }); var clientDuid = new UUIDDUID(random.NextGuid()); DHCPv6Packet solicitPacket = DHCPv6Packet.AsInner(14, DHCPv6PacketTypes.Solicit, new List <DHCPv6PacketOption> { new DHCPv6PacketTrueOption(DHCPv6PacketOptionTypes.RapitCommit), new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, clientDuid), new DHCPv6PacketIdentityAssociationNonTemporaryAddressesOption(15, TimeSpan.Zero, TimeSpan.Zero, new List <DHCPv6PacketSuboption>()), }); DHCPv6RelayPacket outerSolicitPacket = DHCPv6RelayPacket.AsOuterRelay(new IPv6HeaderInformation(random.GetIPv6Address(), random.GetIPv6Address()), true, 0, IPv6Address.FromString("fe80::2"), IPv6Address.FromString("fe80::2"), new DHCPv6PacketOption[] { new DHCPv6PacketRemoteIdentifierOption(random.NextUInt16(), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }), }, solicitPacket); initialRootScope.HandleSolicit(outerSolicitPacket, propertyResolverMock.Object); var firstLease = initialRootScope.GetRootScopes().First().Leases.GetAllLeases().First(); await engine.Save(initialRootScope); initialRootScope = await engine.GetRootScope(); DHCPv6Packet releasePacket = DHCPv6Packet.AsInner(14, DHCPv6PacketTypes.RELEASE, new List <DHCPv6PacketOption> { new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, clientDuid), new DHCPv6PacketIdentityAssociationNonTemporaryAddressesOption(15, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), new DHCPv6PacketSuboption[] { new DHCPv6PacketIdentityAssociationAddressSuboption(firstLease.Address, TimeSpan.FromSeconds(random.Next()), TimeSpan.FromSeconds(random.Next()), Array.Empty <DHCPv6PacketSuboption>()) }) }); DHCPv6RelayPacket outerreleasePacket = DHCPv6RelayPacket.AsOuterRelay(new IPv6HeaderInformation(random.GetIPv6Address(), random.GetIPv6Address()), true, 0, IPv6Address.FromString("fe80::2"), IPv6Address.FromString("fe80::2"), new DHCPv6PacketOption[] { new DHCPv6PacketRemoteIdentifierOption(random.NextUInt16(), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }), }, releasePacket); firstLease = initialRootScope.GetRootScopes().First().Leases.GetAllLeases().First(); initialRootScope.HandleRelease(outerreleasePacket, propertyResolverMock.Object); Assert.Equal(LeaseStates.Released, firstLease.State); Assert.Empty(initialRootScope.GetRootScopes().First().Leases.GetAllLeases()); await engine.Save(initialRootScope); await Task.Delay(1000); initialRootScope.DropUnusedLeasesOlderThan(DateTime.Now); Assert.Empty(initialRootScope.GetRootScopes().First().Leases.GetAllLeases()); await engine.Save(initialRootScope); var rehydratedRootScope = await engine.GetRootScope(); Assert.Empty(rehydratedRootScope.GetRootScopes().First().Leases.GetAllLeases()); }); }
public void TestNotifcationTriggerForSolicitMessages(Boolean reuse, Boolean prefixRequest, Boolean hadPrefix, Boolean shouldHaveOldBinding, Boolean shouldHaveNewBinding) { Random random = new Random(); IPv6HeaderInformation headerInformation = new IPv6HeaderInformation(IPv6Address.FromString("fe80::1"), IPv6Address.FromString("fe80::2")); DUID clientDuid = new UUIDDUID(random.NextGuid()); UInt32 iaId = random.NextBoolean() == false?random.NextUInt32() : 0; IPv6Address leasedAddress = IPv6Address.FromString("fe80::5"); UInt32 prefixIaId = random.NextBoolean() == false?random.NextUInt32() : 0; Byte exisitngPrefixLength = 62; DHCPv6PrefixDelegation existingDelegation = DHCPv6PrefixDelegation.FromValues( IPv6Address.FromString("2a4c::0"), new IPv6SubnetMask(new IPv6SubnetMaskIdentifier(exisitngPrefixLength)), prefixIaId); var packetOptions = new List <DHCPv6PacketOption> { new DHCPv6PacketIdentifierOption(DHCPv6PacketOptionTypes.ClientIdentifier, clientDuid), new DHCPv6PacketIdentityAssociationNonTemporaryAddressesOption(iaId, TimeSpan.Zero, TimeSpan.Zero, Array.Empty <DHCPv6PacketSuboption>()), }; if (prefixRequest == true) { packetOptions.Add( new DHCPv6PacketIdentityAssociationPrefixDelegationOption(prefixIaId, TimeSpan.Zero, TimeSpan.Zero, Array.Empty <DHCPv6PacketSuboption>())); } DHCPv6Packet innerPacket = DHCPv6Packet.AsInner(random.NextUInt16(), DHCPv6PacketTypes.REBIND, packetOptions); DHCPv6Packet packet = DHCPv6RelayPacket.AsOuterRelay(headerInformation, true, 1, random.GetIPv6Address(), random.GetIPv6Address(), new DHCPv6PacketOption[] { new DHCPv6PacketByteArrayOption(DHCPv6PacketOptionTypes.InterfaceId, random.NextBytes(10)) }, innerPacket); CreateScopeResolverInformation resolverInformations = new CreateScopeResolverInformation { Typename = "something" }; Mock <IScopeResolver <DHCPv6Packet, IPv6Address> > resolverMock = new Mock <IScopeResolver <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict); resolverMock.Setup(x => x.PacketMeetsCondition(packet)).Returns(true); resolverMock.SetupGet(x => x.HasUniqueIdentifier).Returns(false); var scopeResolverMock = new Mock <IScopeResolverManager <DHCPv6Packet, IPv6Address> >(MockBehavior.Strict); scopeResolverMock.Setup(x => x.InitializeResolver(resolverInformations)).Returns(resolverMock.Object); Mock <ILoggerFactory> factoryMock = new Mock <ILoggerFactory>(MockBehavior.Strict); factoryMock.Setup(x => x.CreateLogger(It.IsAny <String>())).Returns(Mock.Of <ILogger <DHCPv6RootScope> >()); var rootScope = new DHCPv6RootScope(Guid.NewGuid(), scopeResolverMock.Object, factoryMock.Object); Guid scopeId = random.NextGuid(); Guid leaseId = random.NextGuid(); var expetecNewLeaseAddress = IPv6Address.FromString("fe80::0"); var events = new List <DomainEvent> { new DHCPv6ScopeEvents.DHCPv6ScopeAddedEvent( new DHCPv6ScopeCreateInstruction { AddressProperties = new DHCPv6ScopeAddressProperties( IPv6Address.FromString("fe80::0"), IPv6Address.FromString("fe80::ff"), new List <IPv6Address> { IPv6Address.FromString("fe80::1") }, t1: DHCPv6TimeScale.FromDouble(0.5), t2: DHCPv6TimeScale.FromDouble(0.75), preferredLifeTime: TimeSpan.FromDays(0.5), validLifeTime: TimeSpan.FromDays(1), reuseAddressIfPossible: reuse, prefixDelgationInfo: DHCPv6PrefixDelgationInfo.FromValues(existingDelegation.NetworkAddress, new IPv6SubnetMaskIdentifier(40), new IPv6SubnetMaskIdentifier(64)), addressAllocationStrategy: DHCPv6ScopeAddressProperties.AddressAllocationStrategies.Next), ResolverInformation = resolverInformations, Name = "Testscope", Id = scopeId, }), new DHCPv6LeaseCreatedEvent { EntityId = leaseId, Address = leasedAddress, ClientIdentifier = clientDuid, IdentityAssocationId = iaId, ScopeId = scopeId, HasPrefixDelegation = hadPrefix, UniqueIdentiifer = Array.Empty <Byte>(), PrefixLength = hadPrefix == true ? exisitngPrefixLength : (Byte)0, IdentityAssocationIdForPrefix = hadPrefix == true ? prefixIaId : (UInt32)0, DelegatedNetworkAddress = hadPrefix == true ? existingDelegation.NetworkAddress : IPv6Address.Empty, StartedAt = DateTime.UtcNow.AddDays(-1), ValidUntil = DateTime.UtcNow.AddDays(1), }, new DHCPv6LeaseActivatedEvent { EntityId = leaseId, ScopeId = scopeId, } }; rootScope.Load(events); var serverPropertiesResolverMock = new Mock <IDHCPv6ServerPropertiesResolver>(MockBehavior.Strict); serverPropertiesResolverMock.Setup(x => x.GetServerDuid()).Returns(new UUIDDUID(Guid.NewGuid())); var _ = rootScope.HandleRebind(packet, serverPropertiesResolverMock.Object); if (shouldHaveNewBinding == false && shouldHaveOldBinding == false) { CheckEmptyTrigger(rootScope); } else { var trigger = CheckTrigger <PrefixEdgeRouterBindingUpdatedTrigger>(rootScope); Assert.Equal(scopeId, trigger.ScopeId); if (shouldHaveNewBinding == true) { Assert.NotNull(trigger.NewBinding); Assert.Equal(64, trigger.NewBinding.Mask.Identifier); if (reuse == true) { Assert.Equal(leasedAddress, trigger.NewBinding.Host); } else { Assert.Equal(expetecNewLeaseAddress, trigger.NewBinding.Host); } } else { Assert.Null(trigger.NewBinding); } if (shouldHaveOldBinding == true) { Assert.NotNull(trigger.OldBinding); Assert.Equal(exisitngPrefixLength, trigger.OldBinding.Mask.Identifier); Assert.Equal(existingDelegation.NetworkAddress, trigger.OldBinding.Prefix); Assert.Equal(leasedAddress, trigger.OldBinding.Host); } else { Assert.Null(trigger.OldBinding); } } }