예제 #1
0
파일: Program.cs 프로젝트: vasili8m/DnsLibs
        private static DnsProxySettings CreateDnsProxySettings()
        {
            List <ListenerSettings> listeners = new List <ListenerSettings>();

            foreach (AGDnsApi.ag_listener_protocol protocol in
                     (AGDnsApi.ag_listener_protocol[])Enum.GetValues(typeof(AGDnsApi.ag_listener_protocol)))
            {
                foreach (IPAddress listenerAddress in new [] { IPAddress.Loopback, IPAddress.IPv6Loopback })
                {
                    ListenerSettings listener = new ListenerSettings
                    {
                        EndPoint      = new IPEndPoint(listenerAddress, DNS_PROXY_PORT),
                        Protocol      = protocol,
                        IsPersistent  = true,
                        IdleTimeoutMs = 3000
                    };

                    listeners.Add(listener);
                }
            }

            DnsProxySettings dnsProxySettings = new DnsProxySettings
            {
                Upstreams = new List <UpstreamOptions>
                {
                    CreateUpstreamOptions()
                },
                Fallbacks = new List <UpstreamOptions>(),
                Dns64     = new Dns64Settings
                {
                    Upstreams  = new List <UpstreamOptions>(),
                    MaxTries   = 5,
                    WaitTimeMs = 2000
                },
                BlockedResponseTtlSec = 0,
                BlockingMode          = AGDnsApi.ag_dnsproxy_blocking_mode.DEFAULT,
                BlockIpv6             = true,
                CustomBlockingIpv4    = null,
                CustomBlockingIpv6    = null,
                DnsCacheSize          = 128,
                EngineParams          = new EngineParams
                {
                    FilterParams = new List <FilterParams>
                    {
                        new FilterParams
                        {
                            Id   = 0,
                            Data = Path.Combine(
                                AppDomain.CurrentDomain.BaseDirectory,
                                SDNS_FILTER_RELATIVE_PATH),
                            InMemory = false
                        }
                    }
                },
                Listeners     = listeners,
                Ipv6Available = false
            };

            return(dnsProxySettings);
        }
예제 #2
0
        /// <summary>
        /// Starts DNS filtering
        /// </summary>
        /// <param name="dnsApiConfiguration">Dns proxy configuration
        /// (<seealso cref="DnsApiConfiguration"/>)</param>
        /// <exception cref="NotSupportedException">Thrown
        /// if current API version is not supported</exception>
        /// <exception cref="ArgumentNullException">Thrown,
        /// if <see cref="dnsApiConfiguration"/> is not specified</exception>
        /// <exception cref="InvalidOperationException">Thrown, if cannot starting the proxy server
        /// for any reason</exception>
        public void StartDnsFiltering(DnsApiConfiguration dnsApiConfiguration)
        {
            lock (SYNC_ROOT)
            {
                try
                {
                    if (dnsApiConfiguration == null)
                    {
                        throw new ArgumentNullException(
                                  "dnsApiConfiguration",
                                  "dnsApiConfiguration is not specified");
                    }

                    if (!dnsApiConfiguration.IsEnabled)
                    {
                        LOG.InfoFormat("DNS filtering is disabled, doing nothing");
                        return;
                    }

                    LOG.InfoFormat("Starting the DNS filtering");
                    m_DnsProxyServer = new Dns.DnsProxyServer.DnsProxyServer(
                        dnsApiConfiguration.DnsProxySettings,
                        dnsApiConfiguration.DnsProxyServerCallbackConfiguration);
                    m_CurrentDnsProxySettings = dnsApiConfiguration.DnsProxySettings;
                    m_DnsProxyServer.Start();
                    LOG.InfoFormat("Starting the DNS filtering has been successfully completed");
                }
                catch (Exception ex)
                {
                    LOG.ErrorFormat("Starting the DNS filtering failed with an error", ex);
                    throw;
                }
            }
        }
예제 #3
0
        internal static DnsProxySettings FromNativeObject(
            AGDnsApi.ag_dnsproxy_settings dnsProxySettingsC)
        {
            List <UpstreamOptions> upstreams = MarshalUtils.AgListToList <AGDnsApi.ag_upstream_options, UpstreamOptions>(
                dnsProxySettingsC.upstreams,
                FromNativeObject);

            List <UpstreamOptions> fallbacks = MarshalUtils.AgListToList <AGDnsApi.ag_upstream_options, UpstreamOptions>(
                dnsProxySettingsC.fallbacks,
                FromNativeObject);

            Dns64Settings           dns64        = FromNativeObject(dnsProxySettingsC.pDns64);
            EngineParams            engineParams = FromNativeObject(dnsProxySettingsC.FilterParams);
            List <ListenerSettings> listeners    =
                MarshalUtils.AgListToList <AGDnsApi.ag_listener_settings, ListenerSettings>(
                    dnsProxySettingsC.listeners,
                    FromNativeObject);
            DnsProxySettings dnsProxySettings = new DnsProxySettings
            {
                Upstreams    = upstreams,
                Fallbacks    = fallbacks,
                Dns64        = dns64,
                EngineParams = engineParams,
                Listeners    = listeners,
            };

            MarshalUtils.CopyFieldsToProperties(dnsProxySettingsC, dnsProxySettings);
            MarshalUtils.AllPtrsToStrings(dnsProxySettingsC, dnsProxySettings);
            return(dnsProxySettings);
        }
예제 #4
0
        /// <summary>
        /// Converts the managed <see cref="dnsProxySettings"/>
        /// (<seealso cref="DnsProxySettings"/>) to the native <see cref="AGDnsApi.ag_dnsproxy_settings"/> object
        /// </summary>
        /// <param name="dnsProxySettings"><see cref="DnsProxySettings"/> instance to convert</param>
        /// <param name="allocatedPointers">List of pointers, which were allocated.
        /// Pointers, which will be referred to a newly allocated memory
        /// (within the process of marshaling the string to the pointer)
        /// will be added to this list.
        /// If this list is not specified (null),
        /// a new created pointer will not be added anywhere</param>
        /// The resulting pointer (<seealso cref="IntPtr"/>) must be freed
        /// with <see cref="MarshalUtils.SafeFreeHGlobal(IntPtr)"/>>
        /// <returns>An instance of <see cref="AGDnsApi.ag_dnsproxy_settings"/></returns>
        internal static AGDnsApi.ag_dnsproxy_settings ToNativeObject(
            DnsProxySettings dnsProxySettings,
            Queue <IntPtr> allocatedPointers)
        {
            MarshalUtils.ag_list upstreamsC = MarshalUtils.ListToAgList(
                dnsProxySettings.Upstreams,
                ToNativeObject,
                allocatedPointers);

            MarshalUtils.ag_list fallbacksC = MarshalUtils.ListToAgList(
                dnsProxySettings.Fallbacks,
                ToNativeObject,
                allocatedPointers);

            MarshalUtils.ag_list fallbackDomains = MarshalUtils.ListToAgList(
                dnsProxySettings.FallbackDomains,
                MarshalUtils.StringToPtr,
                allocatedPointers);

            IntPtr pDns64C = IntPtr.Zero;

            if (dnsProxySettings.Dns64 != null)
            {
                AGDnsApi.ag_dns64_settings dns64C =
                    ToNativeObject(dnsProxySettings.Dns64, allocatedPointers);
                pDns64C = MarshalUtils.StructureToPtr(dns64C, allocatedPointers);
            }

            AGDnsApi.ag_filter_engine_params filterEngineParamsC =
                ToNativeObject(dnsProxySettings.EngineParams, allocatedPointers);
            MarshalUtils.ag_list listenersC = MarshalUtils.ListToAgList(
                dnsProxySettings.Listeners,
                ToNativeObject,
                allocatedPointers);

            IntPtr pOutboundProxySessionC = IntPtr.Zero;

            if (dnsProxySettings.OutboundProxySettings != null)
            {
                AGDnsApi.ag_outbound_proxy_settings outboundProxySettingsC =
                    ToNativeObject(dnsProxySettings.OutboundProxySettings, allocatedPointers);
                pOutboundProxySessionC = MarshalUtils.StructureToPtr(outboundProxySettingsC, allocatedPointers);
            }

            AGDnsApi.ag_dnsproxy_settings dnsProxySettingsC = new AGDnsApi.ag_dnsproxy_settings
            {
                upstreams       = upstreamsC,
                fallbacks       = fallbacksC,
                pDns64          = pDns64C,
                FilterParams    = filterEngineParamsC,
                listeners       = listenersC,
                outbound_proxy  = pOutboundProxySessionC,
                fallbackDomains = fallbackDomains,
            };

            MarshalUtils.CopyPropertiesToFields(dnsProxySettings, ref dnsProxySettingsC);
            MarshalUtils.AllStringsToPtrs(dnsProxySettings, ref dnsProxySettingsC, allocatedPointers);
            return(dnsProxySettingsC);
        }
예제 #5
0
        /// <summary>
        /// Gets the default DNS proxy settings as a <see cref="DnsProxySettings"/> object
        /// </summary>
        /// <returns>Current DNS proxy settings
        /// (<seealso cref="DnsProxySettings"/>)</returns>
        /// <exception cref="InvalidOperationException">Thrown,
        /// if cannot get the default dns proxy settings via native method</exception>
        public static DnsProxySettings GetDefaultDnsProxySettings()
        {
            LOG.Info("Get default DnsProxyServer settings");
            DnsProxySettings defaultDnsProxySettings =
                GetDnsProxySettings(AGDnsApi.ag_dnsproxy_settings_get_default);

            return(defaultDnsProxySettings);
        }
예제 #6
0
        /// <summary>
        /// Gets the default DNS proxy settings as a <see cref="DnsProxySettings"/> object
        /// </summary>
        /// <returns>Current DNS proxy settings
        /// (<seealso cref="DnsProxySettings"/>)</returns>
        /// <exception cref="InvalidOperationException">Thrown,
        /// if cannot get the default dns proxy settings via native method</exception>
        public static DnsProxySettings GetDefaultDnsProxySettings()
        {
            Logger.Info("Get default DnsProxyServer settings");
            IntPtr           pSettings = AGDnsApi.ag_dnsproxy_settings_get_default();
            DnsProxySettings defaultDnsProxySettings =
                GetDnsProxySettings(pSettings);

            return(defaultDnsProxySettings);
        }
예제 #7
0
파일: Program.cs 프로젝트: vasili8m/DnsLibs
        public static void Main(string[] args)
        {
            string redirectorAppExecutablePath = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                REDIRECTOR_EXECUTABLE_RELATIVE_PATH);
            bool isRedirectorExist = File.Exists(redirectorAppExecutablePath);

            try
            {
                m_LogProvider = new ColoredConsoleLogProvider();
                LogProvider.SetCurrentLogProvider(m_LogProvider);

#if LOG_TO_FILE
                ConsoleToFileRedirector.Start("Logs");
#endif
                m_DnsApi = DnsApi.Instance;
                m_DnsApi.InitLogger(LogLevel.Debug);
                DnsProxySettings dnsProxySettings = CreateDnsProxySettings();
                IDnsProxyServerCallbackConfiguration dnsProxyServerCallbackConfiguration =
                    new DnsProxyServerCallbackConfiguration();

                int dnsProxyProcessId = Process.GetCurrentProcess().Id;
                if (isRedirectorExist)
                {
                    m_CoreProcess =
                        WindowsTools.CreateProcess(
                            redirectorAppExecutablePath,
                            string.Format("{0} {1}", dnsProxyProcessId, DNS_PROXY_PORT),
                            true);
                    m_CoreProcess.Start();
                }

                m_DnsApi.StartDnsFiltering(new DnsApiConfiguration
                {
                    IsEnabled        = true,
                    DnsProxySettings = dnsProxySettings,
                    DnsProxyServerCallbackConfiguration = dnsProxyServerCallbackConfiguration
                });

                Console.ReadLine();
            }
            finally
            {
                m_DnsApi.StopDnsFiltering();
                if (isRedirectorExist && m_CoreProcess != null)
                {
                    m_CoreProcess.StandardInput.WriteLine("Switching off the core sample app...");
                    m_CoreProcess.Kill();
#if UNINSTALL_REDIRECT_DRIVER
                    UninstallRedirectDriver();
#endif
                }

                ConsoleToFileRedirector.Stop();
            }
        }
예제 #8
0
        public void TestDnsProxyServer()
        {
            DnsProxySettings currentDnsProxySettings      = new DnsProxySettings();
            IDnsProxyServerCallbackConfiguration callback = new DnsProxyServerCallbackConfiguration();

            Assert.DoesNotThrow(() =>
            {
                IDnsProxyServer server = new DnsProxyServer.DnsProxyServer(currentDnsProxySettings, callback);
            });
        }
예제 #9
0
        public void TestUpstreamOptionsConverter()
        {
            IDnsProxyServerCallbackConfiguration dnsCallback = new DnsProxyServerCallbackConfiguration();
            DnsProxySettings currentDnsProxySettings         = new DnsProxySettings();
            IDnsProxyServer  proxyServer = new DnsProxyServer.DnsProxyServer(currentDnsProxySettings, dnsCallback);

            AGDnsApi.AGDnsProxyServerCallbacks serverCallbackNative =
                DnsApiConverter.ToNativeObject(dnsCallback, proxyServer);
            Assert.NotNull(serverCallbackNative);
        }
예제 #10
0
        public void TestGetDefaultSettings()
        {
            DnsProxySettings defaultDnsProxySettings = DnsApi.Instance.GetDefaultDnsProxySettings();

            Assert.IsNotNull(defaultDnsProxySettings);
            Assert.IsNotNull(defaultDnsProxySettings.Upstreams);
            Assert.IsNotNull(defaultDnsProxySettings.Fallbacks);
            Assert.IsNotNull(defaultDnsProxySettings.Listeners);
            Assert.IsNotNull(defaultDnsProxySettings.EngineParams);
            Assert.IsNotNull(defaultDnsProxySettings.Dns64);
        }
예제 #11
0
        public static void Main(string[] args)
        {
            string redirectorAppExecutablePath = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                REDIRECTOR_EXECUTABLE_RELATIVE_PATH);
            bool isRedirectorExist = File.Exists(redirectorAppExecutablePath);

            try
            {
#if LOG_TO_FILE
                ConsoleToFileRedirector.Start("Logs");
#endif
                DnsSimpleApi.StartLogger();
                DnsProxySettings dnsProxySettings = CreateDnsProxySettings();
                IDnsProxyServerCallbackConfiguration dnsProxyServerCallbackConfiguration =
                    new DnsProxyServerCallbackConfiguration();
                int dnsProxyProcessId = Process.GetCurrentProcess().Id;
                if (isRedirectorExist)
                {
                    m_CoreProcess =
                        WindowsTools.CreateProcess(
                            redirectorAppExecutablePath,
                            $"{dnsProxyProcessId} {DNS_PROXY_PORT}",
                            true);
                    m_CoreProcess.Start();
                }

                dnsProxySettings.OptimisticCache = true;
                dnsProxySettings.EnableDNSSECOK  = true;

                DnsSimpleApi.StartDnsFiltering(new DnsApiConfiguration
                {
                    IsEnabled        = true,
                    DnsProxySettings = dnsProxySettings,
                    DnsProxyServerCallbackConfiguration = dnsProxyServerCallbackConfiguration
                });

                Console.ReadLine();
            }
            finally
            {
                DnsSimpleApi.StopDnsFiltering();
                if (isRedirectorExist && m_CoreProcess != null)
                {
                    m_CoreProcess.StandardInput.WriteLine("Switching off the core sample app...");
                    m_CoreProcess.Kill();
#if UNINSTALL_REDIRECT_DRIVER
                    UninstallRedirectDriver();
#endif
                }

                ConsoleToFileRedirector.Stop();
            }
        }
예제 #12
0
 /// <summary>
 /// Initializes the new instance of the DnsProxyServer
 /// </summary>
 /// <param name="dnsProxySettings">Dns proxy settings
 /// (<seealso cref="DnsProxySettings"/>)</param>
 /// <param name="callbackConfiguration">Callback config configuration
 /// (<seealso cref="IDnsProxyServerCallbackConfiguration"/>)</param>
 /// <exception cref="NotSupportedException">Thrown if current API version is not supported</exception>
 public DnsProxyServer(
     DnsProxySettings dnsProxySettings,
     IDnsProxyServerCallbackConfiguration callbackConfiguration)
 {
     lock (m_SyncRoot)
     {
         Logger.Info("Creating the DnsProxyServer");
         AGDnsApi.ValidateApi();
         m_DnsProxySettings      = dnsProxySettings;
         m_CallbackConfiguration = callbackConfiguration;
     }
 }
예제 #13
0
        internal static DnsProxySettings CreateDnsProxySettings()
        {
            DnsProxySettings dnsProxySettings = new DnsProxySettings
            {
                Upstreams = new List <UpstreamOptions>
                {
                    CreateUpstreamOptions()
                },
                Fallbacks = new List <UpstreamOptions>
                {
                    CreateUpstreamOptions()
                },
                Dns64 = new Dns64Settings
                {
                    Upstreams = new List <UpstreamOptions>
                    {
                        CreateUpstreamOptions()
                    },
                    MaxTries   = 5,
                    WaitTimeMs = 1000
                },
                BlockedResponseTtlSec = 5,
                BlockingMode          = AGDnsApi.ag_dnsproxy_blocking_mode.DEFAULT,
                BlockIpv6             = false,
                CustomBlockingIpv4    = null,
                CustomBlockingIpv6    = null,
                DnsCacheSize          = 500,
                EngineParams          = new EngineParams
                {
                    FilterParams = new List <FilterParams>
                    {
                        new FilterParams
                        {
                            Id       = 0,
                            Data     = "blablabla",
                            InMemory = true
                        }
                    }
                },
                Listeners = new List <ListenerSettings>
                {
                    new ListenerSettings
                    {
                        EndPoint      = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 45),
                        IsPersistent  = true,
                        IdleTimeoutMs = 500
                    }
                },
                Ipv6Available = true
            };

            return(dnsProxySettings);
        }
예제 #14
0
        /// <summary>
        /// Gets the DNS proxy settings,
        /// according to the specified <see cref="pCurrentDnsProxySettings"/>
        /// </summary>
        /// <param name="pCurrentDnsProxySettings">DNS proxy settings
        /// (<seealso cref="Func{TResult}"/>)</param>
        /// <exception cref="InvalidOperationException">Thrown,
        /// if cannot get the DNS proxy settings via native method</exception>
        /// <returns>The <see cref="DnsProxySettings"/> object</returns>
        private static DnsProxySettings GetDnsProxySettings(IntPtr pCurrentDnsProxySettings)
        {
            Logger.Info("Get DNS proxy settings settings");
            if (pCurrentDnsProxySettings == IntPtr.Zero)
            {
                throw new InvalidOperationException("Cannot get the DNS proxy settings");
            }

            AGDnsApi.ag_dnsproxy_settings currentDnsProxySettingsC =
                MarshalUtils.PtrToStructure <AGDnsApi.ag_dnsproxy_settings>(pCurrentDnsProxySettings);
            DnsProxySettings currentDnsProxySettings = DnsApiConverter.FromNativeObject(currentDnsProxySettingsC);

            Logger.Info("Finished getting the DNS proxy settings");
            return(currentDnsProxySettings);
        }
예제 #15
0
        /// <summary>
        /// Gets the current DNS proxy settings as a <see cref="DnsProxySettings"/> object
        /// </summary>
        /// <returns>Current DNS proxy settings
        /// (<seealso cref="DnsProxySettings"/>)</returns>
        /// <exception cref="InvalidOperationException">Thrown,
        /// if cannot get the current dns proxy settings via native method</exception>
        public DnsProxySettings GetCurrentDnsProxySettings()
        {
            LOG.Info("Get current DnsProxyServer settings");
            lock (m_SyncRoot)
            {
                if (!IsStarted)
                {
                    LOG.Info("DnsProxyServer is not started, doing nothing");
                    return(null);
                }

                DnsProxySettings currentDnsProxySettings =
                    GetDnsProxySettings(() => AGDnsApi.ag_dnsproxy_get_settings(m_pProxyServer));
                return(currentDnsProxySettings);
            }
        }
예제 #16
0
        private static void AddDnsSuffixesAndDefaultFallbacks(DnsProxySettings dnsProxySettings)
        {
            List <string> dnsSuffixes = GetSystemDNSSuffixes();

            if (dnsProxySettings.FallbackDomains == null)
            {
                dnsProxySettings.FallbackDomains = new List <string>();
            }

            List <string> fallbackDomains = dnsProxySettings.FallbackDomains;

            List <string> preparedDnsSuffixes = dnsSuffixes.Select(x => $"*.{x}").ToList();

            fallbackDomains.AddRange(preparedDnsSuffixes);
            dnsProxySettings.FallbackDomains = fallbackDomains.Distinct().ToList();
        }
예제 #17
0
 /// <summary>
 /// Gets the default DNS proxy settings as a <see cref="DnsProxySettings"/> object
 /// </summary>
 /// <returns>Current DNS proxy settings
 /// (<seealso cref="DnsProxySettings"/>)</returns>
 /// <exception cref="InvalidOperationException">Thrown,
 /// if cannot get the default dns proxy settings via native method</exception>
 public DnsProxySettings GetDefaultDnsProxySettings()
 {
     lock (SYNC_ROOT)
     {
         try
         {
             LOG.InfoFormat("Getting default DNS proxy settings");
             DnsProxySettings dnsProxySettings =
                 Dns.DnsProxyServer.DnsProxyServer.GetDefaultDnsProxySettings();
             LOG.InfoFormat("Getting default DNS proxy settings has been successfully completed");
             return(dnsProxySettings);
         }
         catch (Exception ex)
         {
             LOG.ErrorFormat("Getting default DNS proxy settings failed with an error", ex);
             throw;
         }
     }
 }
예제 #18
0
        internal static DnsProxySettings FromNativeObject(
            AGDnsApi.ag_dnsproxy_settings dnsProxySettingsC)
        {
            List <UpstreamOptions> upstreams = MarshalUtils.AgListToList <AGDnsApi.ag_upstream_options, UpstreamOptions>(
                dnsProxySettingsC.upstreams,
                FromNativeObject);

            List <UpstreamOptions> fallbacks = MarshalUtils.AgListToList <AGDnsApi.ag_upstream_options, UpstreamOptions>(
                dnsProxySettingsC.fallbacks,
                FromNativeObject);

            List <string> fallbackDomains = MarshalUtils.AgListToList <IntPtr, string>(
                dnsProxySettingsC.fallbackDomains,
                MarshalUtils.PtrToString);

            AGDnsApi.ag_dns64_settings dns64C =
                MarshalUtils.PtrToStructure <AGDnsApi.ag_dns64_settings>(dnsProxySettingsC.pDns64);
            Dns64Settings           dns64        = FromNativeObject(dns64C);
            EngineParams            engineParams = FromNativeObject(dnsProxySettingsC.FilterParams);
            List <ListenerSettings> listeners    =
                MarshalUtils.AgListToList <AGDnsApi.ag_listener_settings, ListenerSettings>(
                    dnsProxySettingsC.listeners,
                    FromNativeObject);

            AGDnsApi.ag_outbound_proxy_settings outboundProxySettingsC =
                MarshalUtils.PtrToStructure <AGDnsApi.ag_outbound_proxy_settings>(dnsProxySettingsC.outbound_proxy);
            OutboundProxySettings outboundProxySettings =
                FromNativeObject(outboundProxySettingsC);
            DnsProxySettings dnsProxySettings = new DnsProxySettings
            {
                Upstreams             = upstreams,
                Fallbacks             = fallbacks,
                FallbackDomains       = fallbackDomains,
                Dns64                 = dns64,
                EngineParams          = engineParams,
                Listeners             = listeners,
                OutboundProxySettings = outboundProxySettings
            };

            MarshalUtils.CopyFieldsToProperties(dnsProxySettingsC, dnsProxySettings);
            MarshalUtils.AllPtrsToStrings(dnsProxySettingsC, dnsProxySettings);
            return(dnsProxySettings);
        }
예제 #19
0
        public void TestGetCurrentDnsProxySettings()
        {
            DnsProxySettings defaultDnsProxySettings = DnsApi.Instance.GetDefaultDnsProxySettings();

            DnsApi.Instance.StartDnsFiltering(new DnsApiConfiguration
            {
                IsEnabled        = true,
                DnsProxySettings = defaultDnsProxySettings,
                DnsProxyServerCallbackConfiguration = new DnsProxyServerCallbackConfiguration()
            });
            DnsProxySettings currentDnsProxySettings = DnsApi.Instance.GetCurrentDnsProxySettings();

            Assert.IsNotNull(currentDnsProxySettings);
            Assert.IsNotNull(currentDnsProxySettings.Upstreams);
            Assert.IsNotNull(currentDnsProxySettings.Fallbacks);
            Assert.IsNotNull(currentDnsProxySettings.Listeners);
            Assert.IsNotNull(currentDnsProxySettings.EngineParams);
            Assert.IsNotNull(currentDnsProxySettings.Dns64);
            DnsApi.Instance.StopDnsFiltering();
            currentDnsProxySettings = DnsApi.Instance.GetCurrentDnsProxySettings();
            Assert.IsNull(currentDnsProxySettings);
        }
예제 #20
0
        /// <summary>
        /// Gets the current DNS proxy settings as a <see cref="DnsProxySettings"/> object
        /// </summary>
        /// <returns>Current DNS proxy settings
        /// (<seealso cref="DnsProxySettings"/>)</returns>
        /// <exception cref="InvalidOperationException">Thrown,
        /// if cannot get the current dns proxy settings via native method</exception>
        public DnsProxySettings GetCurrentDnsProxySettings()
        {
            lock (SYNC_ROOT)
            {
                try
                {
                    LOG.InfoFormat("Getting current DNS proxy settings");
                    if (m_DnsProxyServer == null)
                    {
                        return(null);
                    }

                    DnsProxySettings dnsProxySettings = m_DnsProxyServer.GetCurrentDnsProxySettings();
                    LOG.InfoFormat("Getting current DNS proxy settings has been successfully completed");
                    return(dnsProxySettings);
                }
                catch (Exception ex)
                {
                    LOG.ErrorFormat("Getting current DNS proxy settings failed with an error", ex);
                    throw;
                }
            }
        }
예제 #21
0
        public void TestDnsProxySettingsConverter()
        {
            DnsProxySettings dnsSettings = new DnsProxySettings
            {
                Upstreams = new List <UpstreamOptions>
                {
                    new UpstreamOptions
                    {
                        Id        = 1,
                        Bootstrap = new List <string>()
                    },
                    new UpstreamOptions
                    {
                        Id        = 2,
                        Bootstrap = new List <string>()
                    },
                    new UpstreamOptions
                    {
                        Id        = 3,
                        Bootstrap = new List <string>
                        {
                            "bootStrapBegin",
                            "bootStrapEnd"
                        }
                    }
                },
                Fallbacks = new List <UpstreamOptions>()
                {
                    new UpstreamOptions
                    {
                        Bootstrap = new List <string>()
                    }
                },
                BlockedResponseTtlSec = 64,
                Dns64 = new Dns64Settings
                {
                    Upstreams = new List <UpstreamOptions>()
                },
                EngineParams = new EngineParams
                {
                    FilterParams = new List <FilterParams>()
                },
                Listeners = new List <ListenerSettings>
                {
                    new ListenerSettings
                    {
                        EndPoint = new IPEndPoint(1234567, 9898)
                    }
                },
                FallbackDomains = new List <string>
                {
                    "Test.com"
                },
                Ipv6Available            = true,
                BlockIpv6                = true,
                AdblockRulesBlockingMode = AGDnsApi.ag_dnsproxy_blocking_mode.AGBM_ADDRESS,
                HostsRulesBlockingMode   = AGDnsApi.ag_dnsproxy_blocking_mode.AGBM_ADDRESS,
                CustomBlockingIpv4       = "1.2.3.4",
                CustomBlockingIpv6       = "::AA",
                DnsCacheSize             = 23,
                OptimisticCache          = true
            };
            Queue <IntPtr> allocatedPointers = new Queue <IntPtr>();

            AGDnsApi.ag_dnsproxy_settings nativeDnsSettings =
                DnsApiConverter.ToNativeObject(dnsSettings, allocatedPointers);
            Assert.AreNotEqual(IntPtr.Zero, nativeDnsSettings.fallbacks.entries);
            Assert.AreNotEqual(IntPtr.Zero, nativeDnsSettings.fallbackDomains.entries);
            Assert.AreNotEqual(IntPtr.Zero, nativeDnsSettings.listeners.entries);
            Assert.AreNotEqual(IntPtr.Zero, nativeDnsSettings.upstreams.entries);
            Assert.AreEqual(nativeDnsSettings.BlockedResponseTtlSec, dnsSettings.BlockedResponseTtlSec);
            Assert.AreEqual(nativeDnsSettings.Ipv6Available, dnsSettings.Ipv6Available);
            Assert.AreEqual(nativeDnsSettings.BlockIpv6, dnsSettings.BlockIpv6);
            Assert.AreEqual(nativeDnsSettings.AdblockRulesBlockingMode, dnsSettings.AdblockRulesBlockingMode);
            Assert.AreEqual(nativeDnsSettings.HostsRulesBlockingMode, dnsSettings.HostsRulesBlockingMode);
            Assert.AreEqual(MarshalUtils.PtrToString(nativeDnsSettings.CustomBlockingIpv4), dnsSettings.CustomBlockingIpv4);
            Assert.AreEqual(MarshalUtils.PtrToString(nativeDnsSettings.CustomBlockingIpv6), dnsSettings.CustomBlockingIpv6);
            Assert.AreEqual(nativeDnsSettings.DnsCacheSize, dnsSettings.DnsCacheSize);
            Assert.AreEqual(nativeDnsSettings.OptimisticCache, dnsSettings.OptimisticCache);

            DnsProxySettings dnsSettingsConverted = DnsApiConverter.FromNativeObject(nativeDnsSettings);

            Assert.AreEqual(dnsSettings.FallbackDomains, dnsSettingsConverted.FallbackDomains);
            Assert.AreEqual(dnsSettings.BlockedResponseTtlSec, dnsSettingsConverted.BlockedResponseTtlSec);
            Assert.AreEqual(dnsSettings.CustomBlockingIpv4, dnsSettingsConverted.CustomBlockingIpv4);
            Assert.AreEqual(dnsSettings.CustomBlockingIpv6, dnsSettingsConverted.CustomBlockingIpv6);
            Assert.AreEqual(dnsSettings.AdblockRulesBlockingMode, dnsSettingsConverted.AdblockRulesBlockingMode);
            Assert.AreEqual(dnsSettings.HostsRulesBlockingMode, dnsSettingsConverted.HostsRulesBlockingMode);
            bool isUpstreamsEqual = CollectionUtils.CollectionsEquals(dnsSettingsConverted.Upstreams, dnsSettings.Upstreams);

            Assert.IsTrue(isUpstreamsEqual);
        }
예제 #22
0
        /// <summary>
        /// Reloads DNS filtering
        /// <param name="newDnsApiConfiguration">Dns proxy configuration
        /// (<seealso cref="DnsApiConfiguration"/>)</param>
        /// <param name="force">Determines, whether the DNS filtering must be reloaded,
        /// independently of whether configuration changed or not</param>
        /// <exception cref="ArgumentNullException">Thrown, if <see cref="newDnsApiConfiguration"/>
        /// is not specified</exception>
        /// <exception cref="ArgumentException">Thrown, if <see cref="DnsProxySettings"/>
        /// is not specified within the <see cref="newDnsApiConfiguration"/></exception>
        /// <exception cref="NotSupportedException">Thrown
        /// if current API version is not supported</exception>
        /// <exception cref="InvalidOperationException">Thrown, if cannot starting the proxy server
        /// for any reason</exception>
        /// <exception cref="InvalidOperationException">Thrown, if cannot closing the proxy server
        /// for any reason</exception>
        /// </summary>
        public void ReloadDnsFiltering(DnsApiConfiguration newDnsApiConfiguration, bool force)
        {
            lock (SYNC_ROOT)
            {
                IDnsProxyServer newDnsProxyServer = null;
                try
                {
                    LOG.InfoFormat("Reloading the DNS filtering");
                    if (m_DnsProxyServer == null ||
                        m_CurrentDnsProxySettings == null)
                    {
                        LOG.InfoFormat(
                            "Start DNS filtering, because the DNS server is not started and/or configurations are not set");

                        StartDnsFiltering(newDnsApiConfiguration);
                        return;
                    }

                    if (newDnsApiConfiguration == null)
                    {
                        throw new ArgumentNullException(
                                  "newDnsApiConfiguration",
                                  "newDnsApiConfiguration is not specified");
                    }

                    if (newDnsApiConfiguration.DnsProxySettings == null)
                    {
                        throw new ArgumentException(
                                  "DnsProxySettings is not initialized",
                                  "newDnsApiConfiguration");
                    }

                    bool isConfigurationChanged = !m_CurrentDnsProxySettings.Equals(newDnsApiConfiguration.DnsProxySettings);
                    if (!force &&
                        !isConfigurationChanged)
                    {
                        LOG.InfoFormat("The DNS server configuration hasn't been changed, no need to reload");
                        return;
                    }

                    newDnsProxyServer = new Dns.DnsProxyServer.DnsProxyServer(
                        newDnsApiConfiguration.DnsProxySettings,
                        newDnsApiConfiguration.DnsProxyServerCallbackConfiguration);

                    m_DnsProxyServer.Stop();
                    m_DnsProxyServer = newDnsProxyServer;
                    if (newDnsApiConfiguration.IsEnabled)
                    {
                        LOG.InfoFormat("DNS filtering is enabled, starting DNS proxy server");
                        m_DnsProxyServer.Start();
                    }

                    m_CurrentDnsProxySettings = newDnsApiConfiguration.DnsProxySettings;
                    LOG.InfoFormat("Reloading the DNS filtering has been successfully completed");
                }
                catch (Exception ex)
                {
                    LOG.ErrorFormat("Reloading the DNS filtering failed with an error", ex);
                    if (newDnsProxyServer != null &&
                        newDnsProxyServer.IsStarted)
                    {
                        // if the new DNS proxy server has been already started we should stop it,
                        // otherwise - let the existed proxy server works
                        StopDnsFiltering();
                    }

                    throw;
                }
            }
        }
예제 #23
0
        private static DnsProxySettings CreateDnsProxySettings()
        {
            List <ListenerSettings> listeners = new List <ListenerSettings>();

            foreach (AGDnsApi.ag_listener_protocol protocol in
                     (AGDnsApi.ag_listener_protocol[])Enum.GetValues(typeof(AGDnsApi.ag_listener_protocol)))
            {
                foreach (IPAddress listenerAddress in new [] { IPAddress.Loopback, IPAddress.IPv6Loopback })
                {
                    ListenerSettings listener = new ListenerSettings
                    {
                        EndPoint      = new IPEndPoint(listenerAddress, DNS_PROXY_PORT),
                        Protocol      = protocol,
                        IsPersistent  = true,
                        IdleTimeoutMs = 3000
                    };

                    listeners.Add(listener);
                }
            }

            DnsProxySettings dnsProxySettings = new DnsProxySettings
            {
                Upstreams = new List <UpstreamOptions>
                {
                    CreateUpstreamOptions()
                },
                Fallbacks       = new List <UpstreamOptions>(),
                FallbackDomains = new List <string>(),
                Dns64           = new Dns64Settings
                {
                    Upstreams  = new List <UpstreamOptions>(),
                    MaxTries   = 5,
                    WaitTimeMs = 2000
                },
                BlockedResponseTtlSec    = 0,
                AdblockRulesBlockingMode = AGDnsApi.ag_dnsproxy_blocking_mode.AGBM_REFUSED,
                HostsRulesBlockingMode   = AGDnsApi.ag_dnsproxy_blocking_mode.AGBM_REFUSED,
                BlockIpv6          = true,
                CustomBlockingIpv4 = null,
                CustomBlockingIpv6 = null,
                DnsCacheSize       = 128,
                EngineParams       = new EngineParams
                {
                    FilterParams = new List <FilterParams>
                    {
                        new FilterParams
                        {
                            Id   = 0,
                            Data = Path.Combine(
                                AppDomain.CurrentDomain.BaseDirectory,
                                SDNS_FILTER_RELATIVE_PATH),
                            InMemory = false
                        }
                    }
                },
                Listeners             = listeners,
                OutboundProxySettings = new OutboundProxySettings
                {
                    Protocol = AGDnsApi.ag_outbound_proxy_protocol.AGOPP_SOCKS5,
                    Address  = "127.0.0.1",
                    AuthInfo = new OutboundProxyAuthInfo
                    {
                        Password = "******",
                        Username = "******"
                    },
                    Port = 6754,
                    TrustAnyCertificate = false
                },
                Ipv6Available   = false,
                OptimisticCache = false,
                EnableDNSSECOK  = false,
                EnableRetransmissionHandling = false
            };

            return(dnsProxySettings);
        }