internal Deployment(DeploymentGetResponse response)
            : this()
        {
            if (response.PersistentVMDowntime != null)
            {
                PersistentVMDowntime = new PersistentVMDowntimeInfo(response.PersistentVMDowntime);
            }

            Name = response.Name;
            DeploymentSlot = response.DeploymentSlot == Management.Compute.Models.DeploymentSlot.Staging ? "Staging" : "Production";
            PrivateID = response.PrivateId;
            Status = DeploymentStatusFactory.From(response.Status);
            Label = response.Label;
            Url = response.Uri;
            Configuration = response.Configuration;
            foreach (var roleInstance in response.RoleInstances.Select(ri => new RoleInstance(ri)))
            {
                RoleInstanceList.Add(roleInstance);
            }

            if (response.UpgradeStatus != null)
            {
                UpgradeStatus = new UpgradeStatus(response.UpgradeStatus);
            }

            UpgradeDomainCount = response.UpgradeDomainCount;
            if (response.Roles != null)
            {
                foreach (var role in response.Roles.Select(r => new Role(r)))
                {
                    RoleList.Add(role);
                }
            }
            SdkVersion = response.SdkVersion;
            Locked = response.Locked;
            RollbackAllowed = response.RollbackAllowed;
            VirtualNetworkName = response.VirtualNetworkName;
            CreatedTime = response.CreatedTime;
            LastModifiedTime = response.LastModifiedTime;

            if (response.ExtendedProperties != null)
            {
                foreach (var prop in response.ExtendedProperties.Keys)
                {
                    ExtendedProperties[prop] = response.ExtendedProperties[prop];
                }
            }

            if (response.DnsSettings != null)
            {
                Dns = new DnsSettings(response.DnsSettings);
            }
            if (response.VirtualIPAddresses != null)
            {
                foreach (var vip in response.VirtualIPAddresses.Select(v => new VirtualIP(v)))
                {
                    VirtualIPs.Add(vip);
                }
            }
        }
 public GetAzureDnsCmdletInfo(DnsSettings settings)
 {
     cmdletName = Utilities.GetAzureDnsCmdletName;
     if (settings != null)
     {
         this.cmdletParams.Add(new CmdletParam("DnsSettings", settings));
     }
 }
        public void WhenConstructorCalled_AndConnectionSettingsAreNull_ThenArgumentNullExceptionIsThrown()
        {
            // Arrange.
            IDateTimeProvider   dateTimeProvider   = new Mock <IDateTimeProvider>().Object;
            ILoggerFactory      loggerFactory      = new Mock <ILoggerFactory>().Object;
            IPeerAddressManager peerAddressManager = new Mock <IPeerAddressManager>().Object;
            IDnsServer          dnsServer          = new Mock <IDnsServer>().Object;
            DnsSettings         dnsSettings        = new DnsSettings(NodeSettings.Default(this.Network));

            dnsSettings.DnsHostName = "stratis.test.com";

            Action a = () => { new WhitelistManager(dateTimeProvider, loggerFactory, peerAddressManager, dnsServer, null, dnsSettings, this.peerBanning); };

            // Act and Assert.
            a.Should().Throw <ArgumentNullException>().Which.Message.Should().Contain("connectionSettings");
        }
Example #4
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="system">TBD</param>
        public DnsExt(ExtendedActorSystem system)
        {
            _system = system;

            var config = system.Settings.Config.GetConfig("akka.io.dns");

            if (config.IsNullOrEmpty())
            {
                throw ConfigurationException.NullOrEmptyConfig <DnsSettings>("akka.io.dns");
            }

            Settings = new DnsSettings(config);
            //TODO: system.dynamicAccess.getClassFor[DnsProvider](Settings.ProviderObjectName).get.newInstance()
            Provider = (IDnsProvider)Activator.CreateInstance(Type.GetType(Settings.ProviderObjectName));
            Cache    = Provider.Cache;
        }
            public TestContext(Network network)
            {
                this.dnsServer        = new Mock <IDnsServer>();
                this.whitelistManager = new Mock <IWhitelistManager>();

                var logger = new Mock <ILogger>(MockBehavior.Loose);

                this.loggerFactory = new Mock <ILoggerFactory>();
                this.loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

                this.nodeLifetime           = new Mock <INodeLifetime>();
                this.nodeSettings           = new NodeSettings(network, args: new string[] { $"-datadir={Directory.GetCurrentDirectory()}" });
                this.dnsSettings            = new DnsSettings(this.nodeSettings);
                this.dataFolder             = CreateDataFolder(this);
                this.asyncLoopFactory       = new Mock <IAsyncLoopFactory>().Object;
                this.connectionManager      = this.BuildConnectionManager();
                this.unreliablePeerBehavior = this.BuildUnreliablePeerBehavior();
            }
 internal FirewallPolicyData(string id, string name, string type, string location, IDictionary <string, string> tags, string etag, ManagedServiceIdentity identity, IReadOnlyList <WritableSubResource> ruleCollectionGroups, ProvisioningState?provisioningState, WritableSubResource basePolicy, IReadOnlyList <WritableSubResource> firewalls, IReadOnlyList <WritableSubResource> childPolicies, AzureFirewallThreatIntelMode?threatIntelMode, FirewallPolicyThreatIntelWhitelist threatIntelWhitelist, FirewallPolicyInsights insights, FirewallPolicySnat snat, DnsSettings dnsSettings, FirewallPolicyIntrusionDetection intrusionDetection, FirewallPolicyTransportSecurity transportSecurity, FirewallPolicySku sku) : base(id, name, type, location, tags)
 {
     Etag                 = etag;
     Identity             = identity;
     RuleCollectionGroups = ruleCollectionGroups;
     ProvisioningState    = provisioningState;
     BasePolicy           = basePolicy;
     Firewalls            = firewalls;
     ChildPolicies        = childPolicies;
     ThreatIntelMode      = threatIntelMode;
     ThreatIntelWhitelist = threatIntelWhitelist;
     Insights             = insights;
     Snat                 = snat;
     DnsSettings          = dnsSettings;
     IntrusionDetection   = intrusionDetection;
     TransportSecurity    = transportSecurity;
     Sku = sku;
 }
Example #7
0
        public void WhenDnsServerInitialized_ThenSaveMasterfileLoopStarted()
        {
            // Arrange.
            var udpClient  = new Mock <IUdpClient>();
            var masterFile = new Mock <IMasterFile>();

            masterFile.Setup(m => m.Get(It.IsAny <Question>())).Returns(new List <IResourceRecord>());
            masterFile.Setup(m => m.Save(It.IsAny <Stream>())).Verifiable();

            var source       = new CancellationTokenSource(5000);
            var nodeLifetime = new Mock <INodeLifetime>();

            nodeLifetime.Setup(n => n.ApplicationStopping).Returns(source.Token);

            var logger        = new Mock <ILogger>();
            var loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            IAsyncProvider asyncProvider = new AsyncProvider(loggerFactory.Object, new Mock <ISignals>().Object, new Mock <INodeLifetime>().Object);

            IDateTimeProvider dateTimeProvider = new Mock <IDateTimeProvider>().Object;
            DnsSettings       dnsSettings      = new DnsSettings(NodeSettings.Default(this.Network));

            dnsSettings.DnsHostName   = "host.example.com";
            dnsSettings.DnsNameServer = "ns1.host.example.com";
            dnsSettings.DnsMailBox    = "*****@*****.**";
            DataFolder dataFolder = CreateDataFolder(this);

            // Act.
            var server = new DnsSeedServer(udpClient.Object, masterFile.Object, asyncProvider, nodeLifetime.Object, loggerFactory.Object, dateTimeProvider, dnsSettings, dataFolder);

            server.Initialize();
            bool waited = source.Token.WaitHandle.WaitOne();

            // Assert.
            server.Should().NotBeNull();
            waited.Should().BeTrue();
            masterFile.Verify(m => m.Save(It.IsAny <Stream>()), Times.AtLeastOnce);
        }
Example #8
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="resultSettings"></param>
 /// <param name="expDns"></param>
 /// <returns></returns>
 internal static bool AzureDns(DnsSettings resultSettings, DnsServer expDns)
 {
     try
     {
         DnsServerList dnsList = vmPowershellCmdlets.GetAzureDns(resultSettings);
         foreach (DnsServer dnsServer in dnsList)
         {
             Console.WriteLine("DNS Server Name: {0}, DNS Server Address: {1}", dnsServer.Name, dnsServer.Address);
             if (MatchDns(expDns, dnsServer))
             {
                 Console.WriteLine("Matched Dns found!");
                 return(true);
             }
         }
         return(false);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
         throw;
     }
 }
Example #9
0
        /// <summary>
        /// The async entry point for the Cirrus Dns process.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        /// <returns>A task used to await the operation.</returns>
        public static async Task Main(string[] args)
        {
            try
            {
                var nodeSettings = new NodeSettings(networksSelector: CirrusNetwork.NetworksSelector, protocolVersion: ProtocolVersion.CIRRUS_VERSION, args: args)
                {
                    MinProtocolVersion = ProtocolVersion.ALT_PROTOCOL_VERSION
                };

                var dnsSettings = new DnsSettings(nodeSettings);

                if (string.IsNullOrWhiteSpace(dnsSettings.DnsHostName) || string.IsNullOrWhiteSpace(dnsSettings.DnsNameServer) || string.IsNullOrWhiteSpace(dnsSettings.DnsMailBox))
                {
                    throw new ConfigurationException("When running as a DNS Seed service, the -dnshostname, -dnsnameserver and -dnsmailbox arguments must be specified on the command line.");
                }

                IFullNode node;
                if (dnsSettings.DnsFullNode)
                {
                    // Build the Dns full node.
                    node = GetFederatedPegFullNode(nodeSettings);
                }
                else
                {
                    // Build the Dns node.
                    node = GetFederatedPegDnsNode(nodeSettings);
                }

                // Run node.
                if (node != null)
                {
                    await node.RunAsync();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("There was a problem initializing the node. Details: '{0}'", ex.ToString());
            }
        }
        private void SettingButton_Click(object sender, RoutedEventArgs e)
        {
            new SettingsWindow().ShowDialog();

            IsLog.IsChecked    = DnsSettings.DebugLog;
            IsGlobal.IsChecked = Equals(DnsSettings.ListenIp, IPAddress.Any);

            if (DnsSettings.BlackListEnable && File.Exists("black.list"))
            {
                DnsSettings.ReadBlackList();
            }

            if (DnsSettings.WhiteListEnable && File.Exists("white.list"))
            {
                DnsSettings.ReadWhiteList();
            }

            if (DnsSettings.WhiteListEnable && File.Exists("rewrite.list"))
            {
                DnsSettings.ReadWhiteList("rewrite.list");
            }
        }
Example #11
0
        /// <summary>
        /// The async entry point for the Stratis Dns process.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        /// <returns>A task used to await the operation.</returns>
        public static async Task MainAsync(string[] args)
        {
            try
            {
                var nodeSettings = new NodeSettings(networksSelector: FederatedPegNetwork.NetworksSelector, protocolVersion: ProtocolVersion.ALT_PROTOCOL_VERSION, args: args);

                var dnsSettings = new DnsSettings(nodeSettings);

                if (string.IsNullOrWhiteSpace(dnsSettings.DnsHostName) || string.IsNullOrWhiteSpace(dnsSettings.DnsNameServer) || string.IsNullOrWhiteSpace(dnsSettings.DnsMailBox))
                {
                    throw new ConfigurationException("When running as a DNS Seed service, the -dnshostname, -dnsnameserver and -dnsmailbox arguments must be specified on the command line.");
                }

                // Build the Dns full node.
                IFullNode node = new FullNodeBuilder()
                                 .UseNodeSettings(nodeSettings)
                                 .UseBlockStore()
                                 .AddSmartContracts()
                                 .UseSmartContractPoAConsensus()
                                 .UseSmartContractPoAMining()
                                 .UseSmartContractWallet()
                                 .UseReflectionExecutor()
                                 .UseMempool()
                                 .UseApi()
                                 .UseDns()
                                 .Build();

                // Run node.
                if (node != null)
                {
                    await node.RunAsync();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("There was a problem initializing the node. Details: '{0}'", ex.ToString());
            }
        }
Example #12
0
        public void WhenDnsServerListening_AndSocketExceptionRaised_ThenDnsServerFailsToStart()
        {
            // Arrange.
            var udpClient = new Mock <IUdpClient>();

            udpClient.Setup(c => c.StartListening(It.IsAny <int>())).Throws(new SocketException());

            var masterFile = new Mock <IMasterFile>();

            IAsyncProvider asyncProvider = new Mock <IAsyncProvider>().Object;
            INodeLifetime  nodeLifetime  = new Mock <INodeLifetime>().Object;

            var logger        = new Mock <ILogger>(MockBehavior.Loose);
            var loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            IDateTimeProvider dateTimeProvider = new Mock <IDateTimeProvider>().Object;
            DnsSettings       dnsSettings      = new DnsSettings(NodeSettings.Default(this.Network));

            dnsSettings.DnsHostName   = "host.example.com";
            dnsSettings.DnsNameServer = "ns1.host.example.com";
            dnsSettings.DnsMailBox    = "*****@*****.**";
            DataFolder dataFolder = CreateDataFolder(this);

            // Act.
            var         source = new CancellationTokenSource();
            var         server = new DnsSeedServer(udpClient.Object, masterFile.Object, asyncProvider, nodeLifetime, loggerFactory.Object, dateTimeProvider, dnsSettings, dataFolder);
            Func <Task> func   = async() => await server.ListenAsync(53, source.Token);

            // Assert.
            server.Should().NotBeNull();
            func.Should().Throw <SocketException>();
            server.Metrics.DnsServerFailureCountSinceStart.Should().Be(1);
            server.Metrics.CurrentSnapshot.DnsServerFailureCountSinceLastPeriod.Should().Be(1);
        }
        public DnsServerList GetAzureDns(DnsSettings settings)
        {
            GetAzureDnsCmdletInfo getAzureDnsCmdletInfo = new GetAzureDnsCmdletInfo(settings);
            WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureDnsCmdletInfo);

            Collection<PSObject> result = azurePowershellCmdlet.Run();
            DnsServerList dnsList = new DnsServerList();

            foreach (PSObject re in result)
            {
                dnsList.Add((DnsServer)re.BaseObject);
            }
            return dnsList;
        }
        public void WhenConstructorCalled_AndNodeLifetimeIsNull_ThenArgumentNullExceptionIsThrown()
        {
            // Arrange.
            IUdpClient        udpClient        = new Mock <IUdpClient>().Object;
            IMasterFile       masterFile       = new Mock <IMasterFile>().Object;
            IAsyncLoopFactory asyncLoopFactory = new Mock <IAsyncLoopFactory>().Object;
            ILoggerFactory    loggerFactory    = new Mock <ILoggerFactory>().Object;
            IDateTimeProvider dateTimeProvider = new Mock <IDateTimeProvider>().Object;
            NodeSettings      nodeSettings     = NodeSettings.Default();

            nodeSettings.DataDir = @"C:\";
            DataFolder dataFolders = new Mock <DataFolder>(nodeSettings).Object;
            Action     a           = () => { new DnsSeedServer(udpClient, masterFile, asyncLoopFactory, null, loggerFactory, dateTimeProvider, DnsSettings.Load(nodeSettings), dataFolders); };

            // Act and Assert.
            a.ShouldThrow <ArgumentNullException>().Which.Message.Should().Contain("nodeLifetime");
        }
        public void WhenConstructorCalled_AndAllParametersValid_ThenTypeCreated()
        {
            // Arrange.
            IUdpClient        udpClient        = new Mock <IUdpClient>().Object;
            IMasterFile       masterFile       = new Mock <IMasterFile>().Object;
            IAsyncLoopFactory asyncLoopFactory = new Mock <IAsyncLoopFactory>().Object;
            INodeLifetime     nodeLifetime     = new Mock <INodeLifetime>().Object;
            ILoggerFactory    loggerFactory    = new Mock <ILoggerFactory>().Object;
            IDateTimeProvider dateTimeProvider = new Mock <IDateTimeProvider>().Object;
            NodeSettings      nodeSettings     = NodeSettings.Default();

            nodeSettings.DataDir = @"C:\";
            DataFolder dataFolders = new Mock <DataFolder>(nodeSettings).Object;

            // Act.
            DnsSeedServer server = new DnsSeedServer(udpClient, masterFile, asyncLoopFactory, nodeLifetime, loggerFactory, dateTimeProvider, DnsSettings.Load(nodeSettings), dataFolders);

            // Assert.
            server.Should().NotBeNull();
        }
Example #16
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="resultSettings"></param>
 /// <param name="expDns"></param>
 /// <returns></returns>
 internal static bool AzureDns(DnsSettings resultSettings, DnsServer expDns)
 {
     try
     {
         DnsServerList dnsList = vmPowershellCmdlets.GetAzureDns(resultSettings);
         foreach (DnsServer dnsServer in dnsList)
         {
             Console.WriteLine("DNS Server Name: {0}, DNS Server Address: {1}", dnsServer.Name, dnsServer.Address);
             if (MatchDns(expDns, dnsServer))
             {
                 Console.WriteLine("Matched Dns found!");
                 return true;
             }
         }
         return false;
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
         throw;
     }
 }
Example #17
0
        public void WhenRefreshWhitelist_AndOwnIPInPeers_AndAreRunningFullNode_ThenWhitelistDoesContainOwnIP()
        {
            // Arrange.
            var mockDateTimeProvider = new Mock <IDateTimeProvider>();

            var mockLogger        = new Mock <ILogger>();
            var mockLoggerFactory = new Mock <ILoggerFactory>();

            mockLoggerFactory.Setup(l => l.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object);
            ILoggerFactory loggerFactory = mockLoggerFactory.Object;

            mockDateTimeProvider.Setup(d => d.GetTimeOffset()).Returns(new DateTimeOffset(new DateTime(2017, 8, 30, 1, 2, 3))).Verifiable();
            IDateTimeProvider dateTimeProvider = mockDateTimeProvider.Object;

            int inactiveTimePeriod = 5000;

            IPAddress activeIpAddressOne = IPAddress.Parse("::ffff:192.168.0.1");
            var       activeEndpointOne  = new IPEndPoint(activeIpAddressOne, 80);

            IPAddress activeIpAddressTwo = IPAddress.Parse("::ffff:192.168.0.2");
            var       activeEndpointTwo  = new IPEndPoint(activeIpAddressTwo, 80);

            IPAddress activeIpAddressThree = IPAddress.Parse("::ffff:192.168.0.3");
            var       activeEndpointThree  = new IPEndPoint(activeIpAddressThree, 80);

            IPAddress externalIPAdress = IPAddress.Parse("::ffff:192.168.99.99");
            int       externalPort     = 80;
            var       externalEndpoint = new IPEndPoint(externalIPAdress, externalPort);

            var activeTestDataSet = new List <Tuple <IPEndPoint, DateTimeOffset> >()
            {
                new Tuple <IPEndPoint, DateTimeOffset> (activeEndpointOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(10)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(20)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(30)),
                new Tuple <IPEndPoint, DateTimeOffset> (externalEndpoint, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(40))
            };

            IPeerAddressManager peerAddressManager = this.CreateTestPeerAddressManager(activeTestDataSet);

            var args = new string[] {
                $"-dnspeeractivethreshold={inactiveTimePeriod.ToString()}",
                $"-externalip={externalEndpoint.Address.ToString()}",
                $"-port={externalPort.ToString()}",
            };

            IMasterFile spiedMasterFile = null;
            var         mockDnsServer   = new Mock <IDnsServer>();

            mockDnsServer.Setup(d => d.SwapMasterfile(It.IsAny <IMasterFile>()))
            .Callback <IMasterFile>(m =>
            {
                spiedMasterFile = m;
            })
            .Verifiable();

            Network     network      = KnownNetworks.StratisTest;
            var         nodeSettings = new NodeSettings(network, args: args);
            DnsSettings dnsSettings  = new DnsSettings(NodeSettings.Default(this.Network));

            dnsSettings.DnsFullNode = true;
            dnsSettings.DnsPeerBlacklistThresholdInSeconds = inactiveTimePeriod;
            dnsSettings.DnsHostName = "stratis.test.com";
            ConnectionManagerSettings connectionSettings = new ConnectionManagerSettings(nodeSettings);

            var whitelistManager = new WhitelistManager(dateTimeProvider, loggerFactory, peerAddressManager, mockDnsServer.Object, connectionSettings, dnsSettings, this.peerBanning);

            // Act.
            whitelistManager.RefreshWhitelist();

            // Assert.
            spiedMasterFile.Should().NotBeNull();

            var question = new Question(new Domain(dnsSettings.DnsHostName), RecordType.A);
            IList <IResourceRecord> resourceRecords = spiedMasterFile.Get(question);

            resourceRecords.Should().NotBeNullOrEmpty();

            IList <IPAddressResourceRecord> ipAddressResourceRecords = resourceRecords.OfType <IPAddressResourceRecord>().ToList();

            ipAddressResourceRecords.Should().HaveSameCount(activeTestDataSet);

            foreach (Tuple <IPEndPoint, DateTimeOffset> testData in activeTestDataSet)
            {
                ipAddressResourceRecords.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address.MapToIPv4())).Should().NotBeNull();
            }
        }
Example #18
0
        public void WhenConstructorCalled_AndNodeSettingsDnsHostNameIsNull_ThenArgumentNullExceptionIsThrown()
        {
            // Arrange.
            IDateTimeProvider   dateTimeProvider   = new Mock <IDateTimeProvider>().Object;
            ILoggerFactory      loggerFactory      = new Mock <ILoggerFactory>().Object;
            IPeerAddressManager peerAddressManager = new Mock <IPeerAddressManager>().Object;
            IDnsServer          dnsServer          = new Mock <IDnsServer>().Object;
            NodeSettings        nodeSettings       = NodeSettings.Default();

            Action a = () => { new WhitelistManager(dateTimeProvider, loggerFactory, peerAddressManager, dnsServer, nodeSettings, DnsSettings.Load(nodeSettings)); };

            // Act and Assert.
            a.ShouldThrow <ArgumentNullException>().Which.Message.Should().Contain("DnsHostName");
        }
        public void ButtonSave_OnClick(object sender, RoutedEventArgs e)
        {
            DnsSettings.DebugLog           = Convert.ToBoolean(Log.IsChecked);
            DnsSettings.EDnsCustomize      = Convert.ToBoolean(EDNSCustomize.IsChecked);
            DnsSettings.DnsCacheEnable     = Convert.ToBoolean(DNSCache.IsChecked);
            DnsSettings.WhiteListEnable    = Convert.ToBoolean(WhiteList.IsChecked);
            DnsSettings.ProxyEnable        = Convert.ToBoolean(Proxy.IsChecked);
            DnsSettings.AutoCleanLogEnable = Convert.ToBoolean(AutoClean.IsChecked);
            DnsSettings.DnsMsgEnable       = Convert.ToBoolean(DNSMsg.IsChecked);
            DnsSettings.Http2Enable        = Convert.ToBoolean(HTTP2Client.IsChecked);
            DnsSettings.TtlRewrite         = Convert.ToBoolean(MinimumTTL.IsChecked);

            if (!string.IsNullOrWhiteSpace(DoHUrlText.Text) &&
                !string.IsNullOrWhiteSpace(SecondDoHUrlText.Text) &&
                !string.IsNullOrWhiteSpace(EDNSClientIP.Text) &&
                !string.IsNullOrWhiteSpace(ListenIP.Text))
            {
                if (string.IsNullOrWhiteSpace(SecondDNS.Text))
                {
                    DnsSettings.StartupOverDoH = true;
                    DnsSettings.SecondDnsIp    = IPAddress.Any;
                }
                else
                {
                    DnsSettings.SecondDnsIp = IPAddress.Parse(SecondDNS.Text);
                }

                DnsSettings.HttpsDnsUrl       = DoHUrlText.Text.Trim();
                DnsSettings.SecondHttpsDnsUrl = SecondDoHUrlText.Text.Trim();
                DnsSettings.EDnsIp            = IPAddress.Parse(EDNSClientIP.Text);
                DnsSettings.ListenIp          = IPAddress.Parse(ListenIP.Text);

                DnsSettings.WProxy = Proxy.IsChecked == true
                    ? new WebProxy(ProxyServer.Text + ":" + ProxyServerPort.Text)
                    : new WebProxy("127.0.0.1:1080");

                if (DnsSettings.BlackListEnable && File.Exists("black.list"))
                {
                    DnsSettings.ReadBlackList(MainWindow.SetupBasePath + "black.list");
                }
                if (DnsSettings.ChinaListEnable && File.Exists("china.list"))
                {
                    DnsSettings.ReadChinaList(MainWindow.SetupBasePath + "china.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists("white.list"))
                {
                    DnsSettings.ReadWhiteList(MainWindow.SetupBasePath + "white.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists("rewrite.list"))
                {
                    DnsSettings.ReadWhiteList(MainWindow.SetupBasePath + "rewrite.list");
                }

                try
                {
                    File.WriteAllText($"{MainWindow.SetupBasePath}config.json",
                                      "{\n" +
                                      $"\"Listen\" : \"{DnsSettings.ListenIp}\",\n" +
                                      $"\"SecondDns\" : \"{DnsSettings.SecondDnsIp}\",\n" +
                                      $"\"BlackList\" : {DnsSettings.BlackListEnable.ToString().ToLower()},\n" +
                                      $"\"ChinaList\" : {DnsSettings.ChinaListEnable.ToString().ToLower()},\n" +
                                      $"\"RewriteList\" : {DnsSettings.WhiteListEnable.ToString().ToLower()},\n" +
                                      $"\"DebugLog\" : {DnsSettings.DebugLog.ToString().ToLower()},\n" +
                                      $"\"EDnsCustomize\" : {DnsSettings.EDnsCustomize.ToString().ToLower()},\n" +
                                      $"\"EDnsClientIp\" : \"{DnsSettings.EDnsIp}\",\n" +
                                      $"\"ProxyEnable\" : {DnsSettings.ProxyEnable.ToString().ToLower()},\n" +
                                      $"\"HttpsDns\" : \"{DnsSettings.HttpsDnsUrl.Trim()}\",\n" +
                                      $"\"SecondHttpsDns\" : \"{DnsSettings.SecondHttpsDnsUrl}\",\n" +
                                      $"\"Proxy\" : \"{ProxyServer.Text + ":" + ProxyServerPort.Text}\",\n" +
                                      $"\"EnableDnsCache\" : {DnsSettings.DnsCacheEnable.ToString().ToLower()},\n" +
                                      $"\"EnableDnsMessage\" : {DnsSettings.DnsMsgEnable.ToString().ToLower()},\n" +
                                      $"\"EnableAutoCleanLog\" : {DnsSettings.AutoCleanLogEnable.ToString().ToLower()},\n" +
                                      $"\"Ipv6Disable\" : {DnsSettings.Ipv6Disable.ToString().ToLower()},\n" +
                                      $"\"Ipv4Disable\" : {DnsSettings.Ipv4Disable.ToString().ToLower()},\n" +
                                      $"\"StartupOverDoH\" : {DnsSettings.StartupOverDoH.ToString().ToLower()},\n" +
                                      $"\"AllowSelfSignedCert\" : {DnsSettings.AllowSelfSignedCert.ToString().ToLower()},\n" +
                                      $"\"AllowAutoRedirect\" : {DnsSettings.AllowAutoRedirect.ToString().ToLower()},\n" +
                                      $"\"HTTPStatusNotify\" : {DnsSettings.HTTPStatusNotify.ToString().ToLower()},\n" +
                                      $"\"TTLRewrite\" : {DnsSettings.TtlRewrite.ToString().ToLower()},\n" +
                                      $"\"TTLMinTime\" : {DnsSettings.TtlMinTime.ToString().ToLower()},\n" +
                                      $"\"EnableHttp2\" : {DnsSettings.Http2Enable.ToString().ToLower()} \n" +
                                      "}");
                }
                catch (UnauthorizedAccessException exp)
                {
                    MessageBoxResult msgResult =
                        MessageBox.Show(
                            "Error: 尝试写入配置文权限不足或IO安全故障,点击确定现在尝试以管理员权限启动。点击取消中止程序运行。" +
                            $"{Environment.NewLine}Original error: {exp}");
                    if (msgResult == MessageBoxResult.OK)
                    {
                        new MainWindow().RunAsAdmin();
                    }
                    else
                    {
                        Close();
                    }
                }
                catch (Exception exp)
                {
                    MessageBox.Show($"Error: 尝试写入配置文件错误{Environment.NewLine}Original error: {exp}");
                }

                Snackbar.MessageQueue.Enqueue(new TextBlock()
                {
                    Text = @"设置已保存!"
                });
            }
            else
            {
                Snackbar.MessageQueue.Enqueue(new TextBlock()
                {
                    Text = @"不应为空,请填写完全。"
                });
            }
        }
Example #20
0
        public void WhenDnsServerFailsToStart_ThenDnsFeatureRetries()
        {
            // Arrange.
            Mock <IDnsServer> dnsServer            = new Mock <IDnsServer>();
            Action <int, CancellationToken> action = (port, token) =>
            {
                throw new ArgumentException("Bad port");
            };

            dnsServer.Setup(s => s.ListenAsync(It.IsAny <int>(), It.IsAny <CancellationToken>())).Callback(action);

            Mock <IWhitelistManager> mockWhitelistManager = new Mock <IWhitelistManager>();
            IWhitelistManager        whitelistManager     = mockWhitelistManager.Object;

            CancellationTokenSource source       = new CancellationTokenSource(3000);
            Mock <INodeLifetime>    nodeLifetime = new Mock <INodeLifetime>();

            nodeLifetime.Setup(n => n.StopApplication()).Callback(() => source.Cancel());
            nodeLifetime.Setup(n => n.ApplicationStopping).Returns(source.Token);
            INodeLifetime nodeLifetimeObject = nodeLifetime.Object;

            NodeSettings nodeSettings = NodeSettings.Default();

            nodeSettings.DataDir = Directory.GetCurrentDirectory();
            DataFolder dataFolder = CreateDataFolder(this);

            Mock <ILogger> logger      = new Mock <ILogger>();
            bool           serverError = false;

            logger.Setup(l => l.Log(LogLevel.Error, It.IsAny <EventId>(), It.IsAny <FormattedLogValues>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >())).Callback <LogLevel, EventId, object, Exception, Func <object, Exception, string> >((level, id, state, e, f) => serverError = state.ToString().StartsWith("Failed whilst running the DNS server"));
            Mock <ILoggerFactory> loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            IAsyncLoopFactory asyncLoopFactory = new AsyncLoopFactory(loggerFactory.Object);

            // Act.
            DnsFeature feature = new DnsFeature(dnsServer.Object, whitelistManager, loggerFactory.Object, nodeLifetimeObject, DnsSettings.Load(nodeSettings), nodeSettings, dataFolder, asyncLoopFactory);

            feature.Initialize();
            bool waited = source.Token.WaitHandle.WaitOne(5000);

            // Assert.
            feature.Should().NotBeNull();
            waited.Should().BeTrue();
            dnsServer.Verify(s => s.ListenAsync(It.IsAny <int>(), It.IsAny <CancellationToken>()), Times.AtLeastOnce);
            serverError.Should().BeTrue();
        }
Example #21
0
        public void WhenDnsFeatureInitialized_ThenDnsServerSuccessfullyStarts()
        {
            // Arrange.
            Mock <IDnsServer>               dnsServer  = new Mock <IDnsServer>();
            ManualResetEventSlim            waitObject = new ManualResetEventSlim(false);
            Action <int, CancellationToken> action     = (port, token) =>
            {
                waitObject.Set();
                throw new OperationCanceledException();
            };

            dnsServer.Setup(s => s.ListenAsync(It.IsAny <int>(), It.IsAny <CancellationToken>())).Callback(action);

            Mock <IWhitelistManager> whitelistManager = new Mock <IWhitelistManager>();

            Mock <INodeLifetime> nodeLifetime = new Mock <INodeLifetime>();
            NodeSettings         nodeSettings = NodeSettings.Default();

            nodeSettings.DataDir = Directory.GetCurrentDirectory();
            DataFolder dataFolder = CreateDataFolder(this);

            Mock <ILogger>        logger        = new Mock <ILogger>(MockBehavior.Loose);
            Mock <ILoggerFactory> loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            IAsyncLoopFactory asyncLoopFactory = new AsyncLoopFactory(loggerFactory.Object);

            // Act.
            DnsFeature feature = new DnsFeature(dnsServer.Object, whitelistManager.Object, loggerFactory.Object, nodeLifetime.Object, DnsSettings.Load(nodeSettings), nodeSettings, dataFolder, asyncLoopFactory);

            feature.Initialize();
            bool waited = waitObject.Wait(5000);

            // Assert.
            feature.Should().NotBeNull();
            waited.Should().BeTrue();
            dnsServer.Verify(s => s.ListenAsync(It.IsAny <int>(), It.IsAny <CancellationToken>()), Times.Once);
        }
Example #22
0
        public void WhenConstructorCalled_AndNodeSettingsIsNull_ThenArgumentNullExceptionIsThrown()
        {
            // Arrange.
            IDnsServer        dnsServer        = new Mock <IDnsServer>().Object;
            IWhitelistManager whitelistManager = new Mock <IWhitelistManager>().Object;
            ILoggerFactory    loggerFactory    = new Mock <ILoggerFactory>().Object;
            INodeLifetime     nodeLifetime     = new Mock <INodeLifetime>().Object;
            NodeSettings      nodeSettings     = NodeSettings.Default();
            DataFolder        dataFolder       = CreateDataFolder(this);
            IAsyncLoopFactory asyncLoopFactory = new Mock <IAsyncLoopFactory>().Object;
            Action            a = () => { new DnsFeature(dnsServer, whitelistManager, loggerFactory, nodeLifetime, DnsSettings.Load(nodeSettings), null, dataFolder, asyncLoopFactory); };

            // Act and Assert.
            a.ShouldThrow <ArgumentNullException>().Which.Message.Should().Contain("nodeSettings");
        }
Example #23
0
        public async Task WhenDnsServerListening_AndDnsRequestReceived_ThenDnsServerSuccessfullyProcessesRequest_Async()
        {
            // Arrange.
            bool startedListening = false;
            bool sentResponse     = false;
            var  udpClient        = new Mock <IUdpClient>();

            udpClient.Setup(c => c.StartListening(It.IsAny <int>())).Callback(() => startedListening = true);
            udpClient.Setup(c => c.ReceiveAsync()).ReturnsAsync(new Tuple <IPEndPoint, byte[]>(new IPEndPoint(IPAddress.Loopback, 80), this.GetDnsRequest()));
            udpClient.Setup(c => c.SendAsync(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <IPEndPoint>())).Callback <byte[], int, IPEndPoint>((p, s, ip) => sentResponse = true).ReturnsAsync(1);

            var masterFile = new Mock <IMasterFile>();

            masterFile.Setup(m => m.Get(It.IsAny <Question>())).Returns(new List <IResourceRecord>()
            {
                new IPAddressResourceRecord(Domain.FromString("google.com"), IPAddress.Loopback)
            });

            IAsyncProvider asyncProvider = new Mock <IAsyncProvider>().Object;
            INodeLifetime  nodeLifetime  = new Mock <INodeLifetime>().Object;
            DnsSettings    dnsSettings   = new DnsSettings(NodeSettings.Default(this.Network));

            dnsSettings.DnsHostName   = "host.example.com";
            dnsSettings.DnsNameServer = "ns1.host.example.com";
            dnsSettings.DnsMailBox    = "*****@*****.**";
            DataFolder dataFolder = CreateDataFolder(this);

            var  logger          = new Mock <ILogger>();
            bool receivedRequest = false;

            logger.Setup(l => l.Log(LogLevel.Trace, It.IsAny <EventId>(), It.IsAny <FormattedLogValues>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >())).Callback <LogLevel, EventId, object, Exception, Func <object, Exception, string> >((level, id, state, e, f) =>
            {
                // Don't reset if we found the trace message we were looking for
                if (!receivedRequest)
                {
                    // Not yet set, check trace message
                    receivedRequest = state.ToString().StartsWith("DNS request received");
                }
            });
            var loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            IDateTimeProvider dateTimeProvider = new Mock <IDateTimeProvider>().Object;

            // Act.
            var source = new CancellationTokenSource(2000);
            var server = new DnsSeedServer(udpClient.Object, masterFile.Object, asyncProvider, nodeLifetime, loggerFactory.Object, dateTimeProvider, dnsSettings, dataFolder);

            try
            {
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected
            }

            // Assert.
            server.Should().NotBeNull();
            startedListening.Should().BeTrue();
            receivedRequest.Should().BeTrue();
            sentResponse.Should().BeTrue();
            server.Metrics.DnsRequestCountSinceStart.Should().BeGreaterThan(0);
            server.Metrics.DnsRequestFailureCountSinceStart.Should().Be(0);
            server.Metrics.DnsServerFailureCountSinceStart.Should().Be(0);
            server.Metrics.CurrentSnapshot.DnsRequestCountSinceLastPeriod.Should().BeGreaterThan(0);
            server.Metrics.CurrentSnapshot.DnsRequestFailureCountSinceLastPeriod.Should().Be(0);
            server.Metrics.CurrentSnapshot.DnsServerFailureCountSinceLastPeriod.Should().Be(0);
            server.Metrics.CurrentSnapshot.DnsRequestElapsedTicksSinceLastPeriod.Should().BeGreaterThan(0);
            server.Metrics.CurrentSnapshot.LastDnsRequestElapsedTicks.Should().BeGreaterThan(0);
        }
        internal static FirewallPolicyData DeserializeFirewallPolicyData(JsonElement element)
        {
            Optional <string> etag = default;
            Optional <ManagedServiceIdentity> identity = default;
            Optional <string> id       = default;
            Optional <string> name     = default;
            Optional <string> type     = default;
            Optional <string> location = default;
            Optional <IDictionary <string, string> >        tags = default;
            Optional <IReadOnlyList <WritableSubResource> > ruleCollectionGroups = default;
            Optional <ProvisioningState>   provisioningState                     = default;
            Optional <WritableSubResource> basePolicy                            = default;
            Optional <IReadOnlyList <WritableSubResource> > firewalls            = default;
            Optional <IReadOnlyList <WritableSubResource> > childPolicies        = default;
            Optional <AzureFirewallThreatIntelMode>         threatIntelMode      = default;
            Optional <FirewallPolicyThreatIntelWhitelist>   threatIntelWhitelist = default;
            Optional <FirewallPolicyInsights>           insights                 = default;
            Optional <FirewallPolicySnat>               snat                     = default;
            Optional <DnsSettings>                      dnsSettings              = default;
            Optional <FirewallPolicyIntrusionDetection> intrusionDetection       = default;
            Optional <FirewallPolicyTransportSecurity>  transportSecurity        = default;
            Optional <FirewallPolicySku>                sku                      = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("etag"))
                {
                    etag = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("identity"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    identity = JsonSerializer.Deserialize <ManagedServiceIdentity>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    Dictionary <string, string> dictionary = new Dictionary <string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("ruleCollectionGroups"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <WritableSubResource> array = new List <WritableSubResource>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(JsonSerializer.Deserialize <WritableSubResource>(item.ToString()));
                            }
                            ruleCollectionGroups = array;
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            provisioningState = new ProvisioningState(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("basePolicy"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            basePolicy = JsonSerializer.Deserialize <WritableSubResource>(property0.Value.ToString());
                            continue;
                        }
                        if (property0.NameEquals("firewalls"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <WritableSubResource> array = new List <WritableSubResource>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(JsonSerializer.Deserialize <WritableSubResource>(item.ToString()));
                            }
                            firewalls = array;
                            continue;
                        }
                        if (property0.NameEquals("childPolicies"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <WritableSubResource> array = new List <WritableSubResource>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(JsonSerializer.Deserialize <WritableSubResource>(item.ToString()));
                            }
                            childPolicies = array;
                            continue;
                        }
                        if (property0.NameEquals("threatIntelMode"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            threatIntelMode = new AzureFirewallThreatIntelMode(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("threatIntelWhitelist"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            threatIntelWhitelist = FirewallPolicyThreatIntelWhitelist.DeserializeFirewallPolicyThreatIntelWhitelist(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("insights"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            insights = FirewallPolicyInsights.DeserializeFirewallPolicyInsights(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("snat"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            snat = FirewallPolicySnat.DeserializeFirewallPolicySnat(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("dnsSettings"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            dnsSettings = DnsSettings.DeserializeDnsSettings(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("intrusionDetection"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            intrusionDetection = FirewallPolicyIntrusionDetection.DeserializeFirewallPolicyIntrusionDetection(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("transportSecurity"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            transportSecurity = FirewallPolicyTransportSecurity.DeserializeFirewallPolicyTransportSecurity(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("sku"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            sku = FirewallPolicySku.DeserializeFirewallPolicySku(property0.Value);
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new FirewallPolicyData(id.Value, name.Value, type.Value, location.Value, Optional.ToDictionary(tags), etag.Value, identity, Optional.ToList(ruleCollectionGroups), Optional.ToNullable(provisioningState), basePolicy, Optional.ToList(firewalls), Optional.ToList(childPolicies), Optional.ToNullable(threatIntelMode), threatIntelWhitelist.Value, insights.Value, snat.Value, dnsSettings.Value, intrusionDetection.Value, transportSecurity.Value, sku.Value));
        }
Example #25
0
        public void WhenRefreshWhitelist_AndActivePeersAvailable_ThenWhitelistContainsActivePeers()
        {
            // Arrange.
            var mockDateTimeProvider = new Mock <IDateTimeProvider>();

            var mockLogger        = new Mock <ILogger>();
            var mockLoggerFactory = new Mock <ILoggerFactory>();

            mockLoggerFactory.Setup(l => l.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object);
            ILoggerFactory loggerFactory = mockLoggerFactory.Object;

            mockDateTimeProvider.Setup(d => d.GetTimeOffset()).Returns(new DateTimeOffset(new DateTime(2017, 8, 30, 1, 2, 3))).Verifiable();
            IDateTimeProvider dateTimeProvider = mockDateTimeProvider.Object;

            int inactiveTimePeriod = 2000;

            IPAddress activeIpAddressOne = IPAddress.Parse("::ffff:192.168.0.1");
            var       activeEndpointOne  = new IPEndPoint(activeIpAddressOne, 80);

            IPAddress activeIpAddressTwo = IPAddress.Parse("::ffff:192.168.0.2");
            var       activeEndpointTwo  = new IPEndPoint(activeIpAddressTwo, 80);

            IPAddress activeIpAddressThree = IPAddress.Parse("::ffff:192.168.0.3");
            var       activeEndpointThree  = new IPEndPoint(activeIpAddressThree, 80);

            IPAddress activeIpAddressFour = IPAddress.Parse("::ffff:192.168.0.4");
            var       activeEndpointFour  = new IPEndPoint(activeIpAddressFour, 80);

            IPAddress activeIpAddressFive = IPAddress.Parse("2607:f8b0:4009:80e::200e");
            var       activeEndpointFive  = new IPEndPoint(activeIpAddressFive, 80);

            var testDataSet = new List <Tuple <IPEndPoint, DateTimeOffset> >()
            {
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(10)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(20)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(30)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointFour, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(40)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointFive, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(50))
            };

            // PeerAddressManager does not support IPv4 addresses that are not represented as embedded IPv4 addresses in an IPv6 address.
            IPeerAddressManager peerAddressManager = this.CreateTestPeerAddressManager(testDataSet);

            IMasterFile spiedMasterFile = null;
            var         mockDnsServer   = new Mock <IDnsServer>();

            mockDnsServer.Setup(d => d.SwapMasterfile(It.IsAny <IMasterFile>()))
            .Callback <IMasterFile>(m =>
            {
                spiedMasterFile = m;
            })
            .Verifiable();

            NodeSettings nodeSettings = NodeSettings.Default(this.Network);
            DnsSettings  dnsSettings  = new DnsSettings(NodeSettings.Default(this.Network));

            dnsSettings.DnsPeerBlacklistThresholdInSeconds = inactiveTimePeriod;
            dnsSettings.DnsHostName = "stratis.test.com";
            ConnectionManagerSettings connectionSettings = new ConnectionManagerSettings(nodeSettings);

            var whitelistManager = new WhitelistManager(dateTimeProvider, loggerFactory, peerAddressManager, mockDnsServer.Object, connectionSettings, dnsSettings, this.peerBanning);

            // Act.
            whitelistManager.RefreshWhitelist();

            // Assert.
            spiedMasterFile.Should().NotBeNull();

            // Check for A records (IPv4 embedded in IPv6 and IPv4 addresses).
            var question4 = new Question(new Domain(dnsSettings.DnsHostName), RecordType.A);
            IList <IResourceRecord> resourceRecordsIpv4 = spiedMasterFile.Get(question4);

            resourceRecordsIpv4.Should().NotBeNullOrEmpty();

            IList <IPAddressResourceRecord> ipAddressResourceRecords4 = resourceRecordsIpv4.OfType <IPAddressResourceRecord>().ToList();

            ipAddressResourceRecords4.Should().HaveCount(4);

            // Check for AAAA records (IPv6 addresses).
            var question6 = new Question(new Domain(dnsSettings.DnsHostName), RecordType.AAAA);
            IList <IResourceRecord> resourceRecordsIpv6 = spiedMasterFile.Get(question6);

            resourceRecordsIpv6.Should().NotBeNullOrEmpty();

            IList <IPAddressResourceRecord> ipAddressResourceRecords6 = resourceRecordsIpv6.OfType <IPAddressResourceRecord>().ToList();

            ipAddressResourceRecords6.Should().HaveCount(1);

            foreach (Tuple <IPEndPoint, DateTimeOffset> testData in testDataSet)
            {
                if (testData.Item1.Address.IsIPv4MappedToIPv6)
                {
                    ipAddressResourceRecords4.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address.MapToIPv4())).Should().NotBeNull();
                }
                else
                {
                    ipAddressResourceRecords6.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address)).Should().NotBeNull();
                }
            }
        }
Example #26
0
        void ReleaseDesignerOutlets()
        {
            if (AntiTrackerSettings != null)
            {
                AntiTrackerSettings.Dispose();
                AntiTrackerSettings = null;
            }

            if (ConnectionSettingsView != null)
            {
                ConnectionSettingsView.Dispose();
                ConnectionSettingsView = null;
            }

            if (DnsSettings != null)
            {
                DnsSettings.Dispose();
                DnsSettings = null;
            }

            if (FirewallSettingsView != null)
            {
                FirewallSettingsView.Dispose();
                FirewallSettingsView = null;
            }

            if (GeneralSettingsView != null)
            {
                GeneralSettingsView.Dispose();
                GeneralSettingsView = null;
            }

            if (GuiBtnFirewallTypeAlwaysOn != null)
            {
                GuiBtnFirewallTypeAlwaysOn.Dispose();
                GuiBtnFirewallTypeAlwaysOn = null;
            }

            if (GuiBtnFirewallTypeOnDemand != null)
            {
                GuiBtnFirewallTypeOnDemand.Dispose();
                GuiBtnFirewallTypeOnDemand = null;
            }

            if (GuiBtnLaunchAtLogin != null)
            {
                GuiBtnLaunchAtLogin.Dispose();
                GuiBtnLaunchAtLogin = null;
            }

            if (GuiBtnProtocolTypeOpenVPN != null)
            {
                GuiBtnProtocolTypeOpenVPN.Dispose();
                GuiBtnProtocolTypeOpenVPN = null;
            }

            if (GuiBtnProtocolTypeWireGuard != null)
            {
                GuiBtnProtocolTypeWireGuard.Dispose();
                GuiBtnProtocolTypeWireGuard = null;
            }

            if (GuiBtnWireguardTooltip != null)
            {
                GuiBtnWireguardTooltip.Dispose();
                GuiBtnWireguardTooltip = null;
            }

            if (GuiButtonOpenvpnTooltip != null)
            {
                GuiButtonOpenvpnTooltip.Dispose();
                GuiButtonOpenvpnTooltip = null;
            }

            if (GuiPanelOpenvpnTooltip != null)
            {
                GuiPanelOpenvpnTooltip.Dispose();
                GuiPanelOpenvpnTooltip = null;
            }

            if (GuiPanelWireguardConfigDetails != null)
            {
                GuiPanelWireguardConfigDetails.Dispose();
                GuiPanelWireguardConfigDetails = null;
            }

            if (GuiPanelWireguardTooltip != null)
            {
                GuiPanelWireguardTooltip.Dispose();
                GuiPanelWireguardTooltip = null;
            }

            if (GuiProgressViewWireguardKeysGeneration != null)
            {
                GuiProgressViewWireguardKeysGeneration.Dispose();
                GuiProgressViewWireguardKeysGeneration = null;
            }

            if (GuiProgressWireguardKeysGeneration != null)
            {
                GuiProgressWireguardKeysGeneration.Dispose();
                GuiProgressWireguardKeysGeneration = null;
            }

            if (GuiProtocolsConfigTabView != null)
            {
                GuiProtocolsConfigTabView.Dispose();
                GuiProtocolsConfigTabView = null;
            }

            if (GuiTabConfigOpenVPN != null)
            {
                GuiTabConfigOpenVPN.Dispose();
                GuiTabConfigOpenVPN = null;
            }

            if (GuiTabConfigWireGuard != null)
            {
                GuiTabConfigWireGuard.Dispose();
                GuiTabConfigWireGuard = null;
            }

            if (GuiViewWireguardConfig != null)
            {
                GuiViewWireguardConfig.Dispose();
                GuiViewWireguardConfig = null;
            }

            if (GuiWireguardConfigDetailsProgressIndicator != null)
            {
                GuiWireguardConfigDetailsProgressIndicator.Dispose();
                GuiWireguardConfigDetailsProgressIndicator = null;
            }

            if (GuiWireguardConfigDetailsView != null)
            {
                GuiWireguardConfigDetailsView.Dispose();
                GuiWireguardConfigDetailsView = null;
            }

            if (GuiWireguardConfigDetailsViewProgress != null)
            {
                GuiWireguardConfigDetailsViewProgress.Dispose();
                GuiWireguardConfigDetailsViewProgress = null;
            }

            if (GuiWireGuardDescription != null)
            {
                GuiWireGuardDescription.Dispose();
                GuiWireGuardDescription = null;
            }

            if (NetworksDefaultActionBtn != null)
            {
                NetworksDefaultActionBtn.Dispose();
                NetworksDefaultActionBtn = null;
            }

            if (NetworksSettings != null)
            {
                NetworksSettings.Dispose();
                NetworksSettings = null;
            }

            if (NetworksView != null)
            {
                NetworksView.Dispose();
                NetworksView = null;
            }

            if (OpenVPNSettings != null)
            {
                OpenVPNSettings.Dispose();
                OpenVPNSettings = null;
            }

            if (OpenVpnViewExtraParameters != null)
            {
                OpenVpnViewExtraParameters.Dispose();
                OpenVpnViewExtraParameters = null;
            }

            if (SettingsView != null)
            {
                SettingsView.Dispose();
                SettingsView = null;
            }

            if (Toolbar != null)
            {
                Toolbar.Dispose();
                Toolbar = null;
            }

            if (GuiOpenVpnUserConfigFile != null)
            {
                GuiOpenVpnUserConfigFile.Dispose();
                GuiOpenVpnUserConfigFile = null;
            }
        }
Example #27
0
        public void WhenConstructorCalled_AndAllParametersValid_ThenTypeCreated()
        {
            // Arrange.
            IDnsServer        dnsServer        = new Mock <IDnsServer>().Object;
            IWhitelistManager whitelistManager = new Mock <IWhitelistManager>().Object;
            INodeLifetime     nodeLifetime     = new Mock <INodeLifetime>().Object;
            NodeSettings      nodeSettings     = NodeSettings.Default();
            DataFolder        dataFolder       = CreateDataFolder(this);
            ILoggerFactory    loggerFactory    = new Mock <ILoggerFactory>().Object;
            IAsyncLoopFactory asyncLoopFactory = new Mock <IAsyncLoopFactory>().Object;

            // Act.
            DnsFeature feature = new DnsFeature(dnsServer, whitelistManager, loggerFactory, nodeLifetime, DnsSettings.Load(nodeSettings), nodeSettings, dataFolder, asyncLoopFactory);

            // Assert.
            feature.Should().NotBeNull();
        }
Example #28
0
        public void WhenRefreshWhitelist_AndInactivePeersInWhitelist_ThenWhitelistDoesNotContainInactivePeers()
        {
            // Arrange.
            var mockDateTimeProvider = new Mock <IDateTimeProvider>();

            var mockLogger        = new Mock <ILogger>();
            var mockLoggerFactory = new Mock <ILoggerFactory>();

            mockLoggerFactory.Setup(l => l.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object);
            ILoggerFactory loggerFactory = mockLoggerFactory.Object;

            mockDateTimeProvider.Setup(d => d.GetTimeOffset()).Returns(new DateTimeOffset(new DateTime(2017, 8, 30, 1, 2, 3))).Verifiable();
            IDateTimeProvider dateTimeProvider = mockDateTimeProvider.Object;

            int inactiveTimePeriod = 3000;

            IPAddress activeIpAddressOne = IPAddress.Parse("::ffff:192.168.0.1");
            var       activeEndpointOne  = new IPEndPoint(activeIpAddressOne, 80);

            IPAddress activeIpAddressTwo = IPAddress.Parse("::ffff:192.168.0.2");
            var       activeEndpointTwo  = new IPEndPoint(activeIpAddressTwo, 80);

            IPAddress activeIpAddressThree = IPAddress.Parse("::ffff:192.168.0.3");
            var       activeEndpointThree  = new IPEndPoint(activeIpAddressThree, 80);

            IPAddress activeIpAddressFour = IPAddress.Parse("::ffff:192.168.0.4");
            var       activeEndpointFour  = new IPEndPoint(activeIpAddressFour, 80);

            var activeTestDataSet = new List <Tuple <IPEndPoint, DateTimeOffset> >()
            {
                new Tuple <IPEndPoint, DateTimeOffset> (activeEndpointOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(10)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(20)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(30)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointFour, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(40))
            };

            IPAddress inactiveIpAddressOne = IPAddress.Parse("::ffff:192.168.100.1");
            var       inactiveEndpointOne  = new IPEndPoint(inactiveIpAddressOne, 80);

            IPAddress inactiveIpAddressTwo = IPAddress.Parse("::ffff:192.168.100.2");
            var       inactiveEndpointTwo  = new IPEndPoint(inactiveIpAddressTwo, 80);

            IPAddress inactiveIpAddressThree = IPAddress.Parse("::ffff:192.168.100.3");
            var       inactiveEndpointThree  = new IPEndPoint(inactiveIpAddressThree, 80);

            var inactiveTestDataSet = new List <Tuple <IPEndPoint, DateTimeOffset> >()
            {
                new Tuple <IPEndPoint, DateTimeOffset> (inactiveEndpointOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(-10)),
                new Tuple <IPEndPoint, DateTimeOffset>(inactiveEndpointTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(-20)),
                new Tuple <IPEndPoint, DateTimeOffset>(inactiveEndpointThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(-30))
            };

            IPeerAddressManager peerAddressManager = this.CreateTestPeerAddressManager(activeTestDataSet.Concat(inactiveTestDataSet).ToList());

            IMasterFile spiedMasterFile = null;
            var         mockDnsServer   = new Mock <IDnsServer>();

            mockDnsServer.Setup(d => d.SwapMasterfile(It.IsAny <IMasterFile>()))
            .Callback <IMasterFile>(m =>
            {
                spiedMasterFile = m;
            })
            .Verifiable();

            NodeSettings nodeSettings = NodeSettings.Default(this.Network);
            DnsSettings  dnsSettings  = new DnsSettings(NodeSettings.Default(this.Network));

            dnsSettings.DnsPeerBlacklistThresholdInSeconds = inactiveTimePeriod;
            dnsSettings.DnsHostName = "stratis.test.com";
            ConnectionManagerSettings connectionSettings = new ConnectionManagerSettings(nodeSettings);

            var whitelistManager = new WhitelistManager(dateTimeProvider, loggerFactory, peerAddressManager, mockDnsServer.Object, connectionSettings, dnsSettings, this.peerBanning);

            // Act.
            whitelistManager.RefreshWhitelist();

            // Assert.
            spiedMasterFile.Should().NotBeNull();

            var question = new Question(new Domain(dnsSettings.DnsHostName), RecordType.A);
            IList <IResourceRecord> resourceRecords = spiedMasterFile.Get(question);

            resourceRecords.Should().NotBeNullOrEmpty();

            IList <IPAddressResourceRecord> ipAddressResourceRecords = resourceRecords.OfType <IPAddressResourceRecord>().ToList();

            ipAddressResourceRecords.Should().HaveSameCount(activeTestDataSet);

            foreach (Tuple <IPEndPoint, DateTimeOffset> testData in activeTestDataSet)
            {
                ipAddressResourceRecords.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address.MapToIPv4())).Should().NotBeNull("the ip address is active and should be in DNS");
            }

            foreach (Tuple <IPEndPoint, DateTimeOffset> testData in inactiveTestDataSet)
            {
                ipAddressResourceRecords.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address.MapToIPv4())).Should().BeNull("the ip address is inactive and should not be returned from DNS");
            }
        }
Example #29
0
        public void WhenDnsFeatureStopped_ThenDnsServerSuccessfullyStops()
        {
            // Arrange.
            Mock <IDnsServer> dnsServer            = new Mock <IDnsServer>();
            Action <int, CancellationToken> action = (port, token) =>
            {
                while (true)
                {
                    token.ThrowIfCancellationRequested();
                    Thread.Sleep(50);
                }
            };

            dnsServer.Setup(s => s.ListenAsync(It.IsAny <int>(), It.IsAny <CancellationToken>())).Callback(action);

            Mock <IWhitelistManager> mockWhitelistManager = new Mock <IWhitelistManager>();
            IWhitelistManager        whitelistManager     = mockWhitelistManager.Object;

            CancellationTokenSource source       = new CancellationTokenSource();
            Mock <INodeLifetime>    nodeLifetime = new Mock <INodeLifetime>();

            nodeLifetime.Setup(n => n.StopApplication()).Callback(() => source.Cancel());
            nodeLifetime.Setup(n => n.ApplicationStopping).Returns(source.Token);
            INodeLifetime nodeLifetimeObject = nodeLifetime.Object;

            NodeSettings nodeSettings = NodeSettings.Default();

            nodeSettings.DataDir = Directory.GetCurrentDirectory();
            DataFolder dataFolder = CreateDataFolder(this);

            Mock <ILogger>        logger        = new Mock <ILogger>(MockBehavior.Loose);
            Mock <ILoggerFactory> loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            IAsyncLoopFactory asyncLoopFactory = new AsyncLoopFactory(loggerFactory.Object);

            // Act.
            DnsFeature feature = new DnsFeature(dnsServer.Object, whitelistManager, loggerFactory.Object, nodeLifetimeObject, DnsSettings.Load(nodeSettings), nodeSettings, dataFolder, asyncLoopFactory);

            feature.Initialize();
            nodeLifetimeObject.StopApplication();
            bool waited = source.Token.WaitHandle.WaitOne(5000);

            // Assert.
            feature.Should().NotBeNull();
            waited.Should().BeTrue();
            dnsServer.Verify(s => s.ListenAsync(It.IsAny <int>(), It.IsAny <CancellationToken>()), Times.Once);
        }
Example #30
0
        public MainWindow()
        {
            InitializeComponent();

            WindowStyle = WindowStyle.SingleBorderWindow;
            Grid.Effect = new BlurEffect {
                Radius = 5, RenderingBias = RenderingBias.Performance
            };

            if (TimeZoneInfo.Local.Id.Contains("China Standard Time") && RegionInfo.CurrentRegion.GeoId == 45)
            {
                //Mainland China PRC
                DnsSettings.SecondDnsIp = IPAddress.Parse("119.29.29.29");
                DnsSettings.HttpsDnsUrl = "https://neatdns.ustclug.org/resolve";
                UrlSettings.MDnsList    = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-CN.list";
                UrlSettings.WhatMyIpApi = "https://myip.ustclug.org/";
            }
            else if (TimeZoneInfo.Local.Id.Contains("Taipei Standard Time") && RegionInfo.CurrentRegion.GeoId == 237)
            {
                //Taiwan ROC
                DnsSettings.SecondDnsIp = IPAddress.Parse("101.101.101.101");
                DnsSettings.HttpsDnsUrl = "https://dns.twnic.tw/dns-query";
                UrlSettings.MDnsList    = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-TW.list";
            }
            else if (RegionInfo.CurrentRegion.GeoId == 104)
            {
                //HongKong SAR
                UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-HK.list";
            }

            if (!File.Exists($"{SetupBasePath}config.json"))
            {
                if (MyTools.IsBadSoftExist())
                {
                    MessageBox.Show("Tips: AuroraDNS 强烈不建议您使用国产安全软件产品!");
                }
                if (!MyTools.IsNslookupLocDns())
                {
                    MessageBoxResult msgResult =
                        MessageBox.Show(
                            "Question: 初次启动,是否要将您的系统默认 DNS 服务器设为 AuroraDNS?"
                            , "Question", MessageBoxButton.OKCancel);
                    if (msgResult == MessageBoxResult.OK)
                    {
                        IsSysDns_OnClick(null, null);
                    }
                }
            }

            if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged"))
            {
                try
                {
                    UrlReg.Reg("doh");
                    UrlReg.Reg("dns-over-https");
                    UrlReg.Reg("aurora-doh-list");

                    File.Create(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
                                "\\AuroraDNS.UrlReged");
                    File.SetAttributes(
                        Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
                        "\\AuroraDNS.UrlReged", FileAttributes.Hidden);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            try
            {
                if (File.Exists($"{SetupBasePath}url.json"))
                {
                    UrlSettings.ReadConfig($"{SetupBasePath}url.json");
                }
                if (File.Exists($"{SetupBasePath}config.json"))
                {
                    DnsSettings.ReadConfig($"{SetupBasePath}config.json");
                }
                if (DnsSettings.BlackListEnable && File.Exists($"{SetupBasePath}black.list"))
                {
                    DnsSettings.ReadBlackList($"{SetupBasePath}black.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.list"))
                {
                    DnsSettings.ReadWhiteList($"{SetupBasePath}white.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.list"))
                {
                    DnsSettings.ReadWhiteList($"{SetupBasePath}rewrite.list");
                }
                if (DnsSettings.ChinaListEnable && File.Exists("china.list"))
                {
                    DnsSettings.ReadChinaList(SetupBasePath + "china.list");
                }
            }
            catch (UnauthorizedAccessException e)
            {
                MessageBoxResult msgResult =
                    MessageBox.Show(
                        "Error: 尝试读取配置文件权限不足或IO安全故障,点击确定现在尝试以管理员权限启动。点击取消中止程序运行。" +
                        $"{Environment.NewLine}Original error: {e}", "错误", MessageBoxButton.OKCancel);
                if (msgResult == MessageBoxResult.OK)
                {
                    RunAsAdmin();
                }
                else
                {
                    Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show($"Error: 尝试读取配置文件错误{Environment.NewLine}Original error: {e}");
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
            if (DnsSettings.AllowSelfSignedCert)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, cert, chain, sslPolicyErrors) => true;
            }

//            switch (0.0)
//            {
//                case 1:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
//                    break;
//                case 1.1:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
//                    break;
//                case 1.2:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//                    break;
//                default:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
//                    break;
//            }

            MDnsServer = new DnsServer(DnsSettings.ListenIp, 10, 10);
            MDnsServer.QueryReceived += QueryResolve.ServerOnQueryReceived;
            MDnsSvrWorker.DoWork     += (sender, args) => MDnsServer.Start();
            MDnsSvrWorker.Disposed   += (sender, args) => MDnsServer.Stop();

            using (BackgroundWorker worker = new BackgroundWorker())
            {
                worker.DoWork += (sender, args) =>
                {
                    LocIPAddr = IPAddress.Parse(IpTools.GetLocIp());
                    if (!Equals(DnsSettings.EDnsIp, IPAddress.Loopback))
                    {
                        IntIPAddr = IPAddress.Parse(IpTools.GetIntIp());
                    }

                    try
                    {
                        if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.sub.list"))
                        {
                            DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}white.sub.list");
                        }
                        if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.sub.list"))
                        {
                            DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}rewrite.sub.list");
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show($"Error: 尝试下载订阅列表失败{Environment.NewLine}Original error: {e}");
                    }

                    MemoryCache.Default.Trim(100);
                };
                worker.RunWorkerAsync();
            }

            NotifyIcon = new NotifyIcon()
            {
                Text = @"AuroraDNS", Visible = false,
                Icon = Properties.Resources.AuroraWhite
            };
            WinFormMenuItem showItem    = new WinFormMenuItem("最小化 / 恢复", MinimizedNormal);
            WinFormMenuItem restartItem = new WinFormMenuItem("重新启动", (sender, args) =>
            {
                if (MDnsSvrWorker.IsBusy)
                {
                    MDnsSvrWorker.Dispose();
                }
                Process.Start(new ProcessStartInfo {
                    FileName = GetType().Assembly.Location
                });
                Environment.Exit(Environment.ExitCode);
            });
            WinFormMenuItem notepadLogItem = new WinFormMenuItem("查阅日志", (sender, args) =>
            {
                if (File.Exists(
                        $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log"))
                {
                    Process.Start(new ProcessStartInfo(
                                      $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log"));
                }
                else
                {
                    MessageBox.Show("找不到当前日志文件,或当前未产生日志文件。");
                }
            });
            WinFormMenuItem abootItem    = new WinFormMenuItem("关于…", (sender, args) => new AboutWindow().Show());
            WinFormMenuItem updateItem   = new WinFormMenuItem("检查更新…", (sender, args) => MyTools.CheckUpdate(GetType().Assembly.Location));
            WinFormMenuItem settingsItem = new WinFormMenuItem("设置…", (sender, args) => new SettingsWindow().Show());
            WinFormMenuItem exitItem     = new WinFormMenuItem("退出", (sender, args) =>
            {
                try
                {
                    UrlReg.UnReg("doh");
                    UrlReg.UnReg("dns-over-https");
                    UrlReg.UnReg("aurora-doh-list");
                    File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
                                "\\AuroraDNS.UrlReged");
                    if (!DnsSettings.AutoCleanLogEnable)
                    {
                        return;
                    }
                    foreach (var item in Directory.GetFiles($"{SetupBasePath}Log"))
                    {
                        if (item != $"{SetupBasePath}Log" +
                            $"\\{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log")
                        {
                            File.Delete(item);
                        }
                    }
                    if (File.Exists(Path.GetTempPath() + "setdns.cmd"))
                    {
                        File.Delete(Path.GetTempPath() + "setdns.cmd");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                Close();
                Environment.Exit(Environment.ExitCode);
            });

            NotifyIcon.ContextMenu =
                new WinFormContextMenu(new[]
            {
                showItem, notepadLogItem, new WinFormMenuItem("-"), abootItem, updateItem, settingsItem, new WinFormMenuItem("-"), restartItem, exitItem
            });

            NotifyIcon.DoubleClick += MinimizedNormal;

            IsSysDns.IsChecked = MyTools.IsNslookupLocDns();
            if (IsSysDns.IsChecked == true)
            {
                IsSysDns.ToolTip = "已设为系统 DNS";
            }
        }
Example #31
0
        public void WhenInitialize_ThenRefreshLoopIsStarted()
        {
            // Arrange.
            Mock <IWhitelistManager> mockWhitelistManager = new Mock <IWhitelistManager>();

            mockWhitelistManager.Setup(w => w.RefreshWhitelist()).Verifiable("the RefreshWhitelist method should be called on the WhitelistManager");

            IWhitelistManager whitelistManager = mockWhitelistManager.Object;

            Mock <ILogger>        mockLogger        = new Mock <ILogger>();
            Mock <ILoggerFactory> mockLoggerFactory = new Mock <ILoggerFactory>();

            mockLoggerFactory.Setup(l => l.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object);
            ILoggerFactory loggerFactory = mockLoggerFactory.Object;

            IAsyncLoopFactory asyncLoopFactory = new AsyncLoopFactory(loggerFactory);
            INodeLifetime     nodeLifeTime     = new NodeLifetime();

            IDnsServer dnsServer = new Mock <IDnsServer>().Object;

            CancellationTokenSource source       = new CancellationTokenSource(3000);
            Mock <INodeLifetime>    nodeLifetime = new Mock <INodeLifetime>();

            nodeLifetime.Setup(n => n.StopApplication()).Callback(() => source.Cancel());
            nodeLifetime.Setup(n => n.ApplicationStopping).Returns(source.Token);
            INodeLifetime nodeLifetimeObject = nodeLifetime.Object;

            NodeSettings nodeSettings = NodeSettings.Default();

            nodeSettings.DataDir = Directory.GetCurrentDirectory();
            DataFolder dataFolder = CreateDataFolder(this);

            using (DnsFeature feature = new DnsFeature(dnsServer, whitelistManager, loggerFactory, nodeLifetimeObject, DnsSettings.Load(nodeSettings), nodeSettings, dataFolder, asyncLoopFactory))
            {
                // Act.
                feature.Initialize();
                bool waited = source.Token.WaitHandle.WaitOne(5000);

                // Assert.
                feature.Should().NotBeNull();
                waited.Should().BeTrue();
                mockWhitelistManager.Verify();
            }
        }
        public async Task WhenDnsServerListening_AndDnsBadRequestReceived_ThenDnsServerFailsToProcessesRequest_Async()
        {
            // Arrange.
            bool startedListening = false;
            var  udpClient        = new Mock <IUdpClient>();

            udpClient.Setup(c => c.StartListening(It.IsAny <int>())).Callback(() => startedListening = true);
            udpClient.Setup(c => c.ReceiveAsync()).ReturnsAsync(new Tuple <IPEndPoint, byte[]>(new IPEndPoint(IPAddress.Loopback, 80), this.GetBadDnsRequest()));

            var masterFile = new Mock <IMasterFile>();

            masterFile.Setup(m => m.Get(It.IsAny <Question>())).Returns(new List <IResourceRecord>()
            {
                new IPAddressResourceRecord(Domain.FromString("google.com"), IPAddress.Loopback)
            });

            IAsyncProvider asyncProvider = new Mock <IAsyncProvider>().Object;
            INodeLifetime  nodeLifetime  = new Mock <INodeLifetime>().Object;
            DnsSettings    dnsSettings   = new DnsSettings(NodeSettings.Default(this.Network));

            dnsSettings.DnsHostName   = "host.example.com";
            dnsSettings.DnsNameServer = "ns1.host.example.com";
            dnsSettings.DnsMailBox    = "*****@*****.**";
            DataFolder dataFolder = CreateDataFolder(this);

            var  logger          = new Mock <ILogger>();
            bool receivedRequest = false;

            bool receivedBadRequest = false;

            logger
            .Setup(f => f.Log(It.IsAny <LogLevel>(), It.IsAny <EventId>(), It.IsAny <It.IsAnyType>(), It.IsAny <Exception>(), (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()))
            .Callback(new InvocationAction(invocation =>
            {
                if (!receivedRequest && (LogLevel)invocation.Arguments[0] == LogLevel.Debug)
                {
                    // Not yet set, check trace message
                    receivedRequest = invocation.Arguments[2].ToString().StartsWith("DNS request received");
                }

                if (!receivedBadRequest && (LogLevel)invocation.Arguments[0] == LogLevel.Warning)
                {
                    // Not yet set, check trace message
                    receivedBadRequest = invocation.Arguments[2].ToString().StartsWith("Failed to process DNS request");
                }
            }));
            var loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            IDateTimeProvider dateTimeProvider = new Mock <IDateTimeProvider>().Object;

            // Act.
            var source = new CancellationTokenSource(2000);
            var server = new DnsSeedServer(udpClient.Object, masterFile.Object, asyncProvider, nodeLifetime, loggerFactory.Object, dateTimeProvider, dnsSettings, dataFolder);

            try
            {
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected
            }

            // Assert.
            server.Should().NotBeNull();
            startedListening.Should().BeTrue();
            receivedRequest.Should().BeTrue();
            receivedBadRequest.Should().BeTrue();
            server.Metrics.DnsRequestCountSinceStart.Should().BeGreaterThan(0);
            server.Metrics.DnsRequestFailureCountSinceStart.Should().BeGreaterThan(0);
            server.Metrics.DnsServerFailureCountSinceStart.Should().Be(0);
            server.Metrics.CurrentSnapshot.DnsRequestCountSinceLastPeriod.Should().BeGreaterThan(0);
            server.Metrics.CurrentSnapshot.DnsRequestFailureCountSinceLastPeriod.Should().BeGreaterThan(0);
            server.Metrics.CurrentSnapshot.DnsServerFailureCountSinceLastPeriod.Should().Be(0);
        }
Example #33
0
        public MainWindow()
        {
            InitializeComponent();

            WindowStyle = WindowStyle.SingleBorderWindow;
            Grid.Effect = new BlurEffect {
                Radius = 5, RenderingBias = RenderingBias.Performance
            };

            if (TimeZoneInfo.Local.Id.Contains("China Standard Time") && RegionInfo.CurrentRegion.GeoId == 45)
            {
                //Mainland China PRC
                DnsSettings.SecondDnsIp = IPAddress.Parse("119.29.29.29");
                DnsSettings.HttpsDnsUrl = "https://neatdns.ustclug.org/resolve";
                UrlSettings.MDnsList    = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-CN.list";
                UrlSettings.WhatMyIpApi = "https://myip.ustclug.org/";
            }
            else if (TimeZoneInfo.Local.Id.Contains("Taipei Standard Time") && RegionInfo.CurrentRegion.GeoId == 237)
            {
                //Taiwan ROC
                DnsSettings.SecondDnsIp = IPAddress.Parse("101.101.101.101");
                DnsSettings.HttpsDnsUrl = "https://dns.twnic.tw/dns-query";
                UrlSettings.MDnsList    = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-TW.list";
            }
            else if (RegionInfo.CurrentRegion.GeoId == 104)
            {
                //HongKong SAR
                UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-HK.list";
            }

            if (!File.Exists($"{SetupBasePath}config.json"))
            {
                if (MyTools.IsBadSoftExist())
                {
                    MessageBox.Show("Tips: AuroraDNS 强烈不建议您使用国产安全软件产品!");
                }
                if (!MyTools.IsNslookupLocDns())
                {
                    var msgResult =
                        MessageBox.Show(
                            "Question: 初次启动,是否要将您的系统默认 DNS 服务器设为 AuroraDNS?"
                            , "Question", MessageBoxButton.OKCancel);
                    if (msgResult == MessageBoxResult.OK)
                    {
                        IsSysDns_OnClick(null, null);
                    }
                }
            }

            if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged"))
            {
                try
                {
                    UrlReg.Reg("doh");
                    UrlReg.Reg("dns-over-https");
                    UrlReg.Reg("aurora-doh-list");

                    File.Create(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
                                "\\AuroraDNS.UrlReged");
                    File.SetAttributes(
                        Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
                        "\\AuroraDNS.UrlReged", FileAttributes.Hidden);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            try
            {
                if (File.Exists($"{SetupBasePath}url.json"))
                {
                    UrlSettings.ReadConfig($"{SetupBasePath}url.json");
                }
                if (File.Exists($"{SetupBasePath}config.json"))
                {
                    DnsSettings.ReadConfig($"{SetupBasePath}config.json");
                }
                if (DnsSettings.BlackListEnable && File.Exists($"{SetupBasePath}black.list"))
                {
                    DnsSettings.ReadBlackList($"{SetupBasePath}black.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.list"))
                {
                    DnsSettings.ReadWhiteList($"{SetupBasePath}white.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.list"))
                {
                    DnsSettings.ReadWhiteList($"{SetupBasePath}rewrite.list");
                }
                if (DnsSettings.ChinaListEnable && File.Exists("china.list"))
                {
                    DnsSettings.ReadChinaList(SetupBasePath + "china.list");
                }
            }
            catch (UnauthorizedAccessException e)
            {
                MessageBoxResult msgResult =
                    MessageBox.Show(
                        "Error: 尝试读取配置文件权限不足或IO安全故障,点击确定现在尝试以管理员权限启动。点击取消中止程序运行。" +
                        $"{Environment.NewLine}Original error: {e}", "错误", MessageBoxButton.OKCancel);
                if (msgResult == MessageBoxResult.OK)
                {
                    RunAsAdmin();
                }
                else
                {
                    Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show($"Error: 尝试读取配置文件错误{Environment.NewLine}Original error: {e}");
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
            if (DnsSettings.AllowSelfSignedCert)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, cert, chain, sslPolicyErrors) => true;
            }

//            switch (0.0)
//            {
//                case 1:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
//                    break;
//                case 1.1:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
//                    break;
//                case 1.2:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//                    break;
//                default:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
//                    break;
//            }

            MDnsServer = new DnsServer(DnsSettings.ListenIp, 10, 10);
            MDnsServer.QueryReceived += QueryResolve.ServerOnQueryReceived;
            //MDnsSvrWorker.DoWork += (sender, args) => MDnsServer.Start();
            //MDnsSvrWorker.Disposed += (sender, args) => MDnsServer.Stop();

            using (BackgroundWorker worker = new BackgroundWorker())
            {
                worker.DoWork += (a, s) =>
                {
                    LocIPAddr = IPAddress.Parse(IpTools.GetLocIp());
                    if (!(Equals(DnsSettings.EDnsIp, IPAddress.Any) && DnsSettings.EDnsCustomize))
                    {
                        IntIPAddr = IPAddress.Parse(IpTools.GetIntIp());
                        var local = IpTools.GeoIpLocal(IntIPAddr.ToString());
                        Dispatcher?.Invoke(() => { TitleTextItem.Header = $"{IntIPAddr}{Environment.NewLine}{local}"; });
                    }

                    try
                    {
                        if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.sub.list"))
                        {
                            DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}white.sub.list");
                        }
                        if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.sub.list"))
                        {
                            DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}rewrite.sub.list");
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show($"Error: 尝试下载订阅列表失败{Environment.NewLine}Original error: {e}");
                    }

                    MemoryCache.Default.Trim(100);
                };
                worker.RunWorkerAsync();
            }

            IsSysDns.IsChecked = MyTools.IsNslookupLocDns();
        }
Example #34
0
        public async Task WhenDnsServerListening_AndDnsRequestReceivedRepeatedly_ThenResponsesReturnedInRoundRobinOrder_Async()
        {
            // Arrange.
            var sources   = new Queue <CancellationTokenSource>();
            var responses = new Queue <byte[]>();
            var udpClient = new Mock <IUdpClient>();

            udpClient.Setup(c => c.ReceiveAsync()).ReturnsAsync(new Tuple <IPEndPoint, byte[]>(new IPEndPoint(IPAddress.Loopback, 80), this.GetDnsRequest()));
            udpClient.Setup(c => c.SendAsync(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <IPEndPoint>())).Callback <byte[], int, IPEndPoint>((p, s, ip) =>
            {
                // One response at a time.
                responses.Enqueue(p);
                CancellationTokenSource source = sources.Dequeue();
                source.Cancel();
            }).ReturnsAsync(1);

            var masterFile = new DnsSeedMasterFile(new List <IResourceRecord>
            {
                new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.1")),
                new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.2")),
                new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.3")),
                new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.4"))
            });

            IAsyncProvider asyncProvider = new Mock <IAsyncProvider>().Object;
            INodeLifetime  nodeLifetime  = new Mock <INodeLifetime>().Object;
            DnsSettings    dnsSettings   = new DnsSettings(NodeSettings.Default(this.Network));

            dnsSettings.DnsHostName   = "host.example.com";
            dnsSettings.DnsNameServer = "ns1.host.example.com";
            dnsSettings.DnsMailBox    = "*****@*****.**";
            DataFolder dataFolder = CreateDataFolder(this);

            var logger        = new Mock <ILogger>();
            var loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            IDateTimeProvider dateTimeProvider = new Mock <IDateTimeProvider>().Object;

            // Act (Part 1).
            var server = new DnsSeedServer(udpClient.Object, masterFile, asyncProvider, nodeLifetime, loggerFactory.Object, dateTimeProvider, dnsSettings, dataFolder);

            try
            {
                var source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 1).
            responses.Count.Should().Be(1);
            byte[]    response    = responses.Dequeue();
            IResponse dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.1");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 2).
            try
            {
                var source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 2).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.2");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 3).
            try
            {
                var source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 3).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.3");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 4).
            try
            {
                var source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 4).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.4");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 5).
            try
            {
                var source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 5).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            // This should start back at the beginning again.
            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.1");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }
        }