├── .gitignore
├── DnsProxy.Service
├── App.config
├── DnsProxy.Service.csproj
├── Program.cs
├── ProjectInstaller.Designer.cs
├── ProjectInstaller.cs
├── ProjectInstaller.resx
├── Properties
│ └── AssemblyInfo.cs
├── Service.Designer.cs
├── Service.cs
├── Service.resx
├── ServiceManager.cs
├── dns.ico
└── packages.config
├── DnsProxy.SetupPackage
├── DnsProxy.SetupPackage.wixproj
├── Product.wxs
└── packages.config
├── LICENSE
├── README.md
└── hyperv-dnsproxy.sln
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 |
24 | # Visual Studio 2015 cache/options directory
25 | .vs/
26 | # Uncomment if you have tasks that create the project's static files in wwwroot
27 | #wwwroot/
28 |
29 | # MSTest test Results
30 | [Tt]est[Rr]esult*/
31 | [Bb]uild[Ll]og.*
32 |
33 | # NUNIT
34 | *.VisualState.xml
35 | TestResult.xml
36 |
37 | # Build Results of an ATL Project
38 | [Dd]ebugPS/
39 | [Rr]eleasePS/
40 | dlldata.c
41 |
42 | # DNX
43 | project.lock.json
44 | artifacts/
45 |
46 | *_i.c
47 | *_p.c
48 | *_i.h
49 | *.ilk
50 | *.meta
51 | *.obj
52 | *.pch
53 | *.pdb
54 | *.pgc
55 | *.pgd
56 | *.rsp
57 | *.sbr
58 | *.tlb
59 | *.tli
60 | *.tlh
61 | *.tmp
62 | *.tmp_proj
63 | *.log
64 | *.vspscc
65 | *.vssscc
66 | .builds
67 | *.pidb
68 | *.svclog
69 | *.scc
70 |
71 | # Chutzpah Test files
72 | _Chutzpah*
73 |
74 | # Visual C++ cache files
75 | ipch/
76 | *.aps
77 | *.ncb
78 | *.opendb
79 | *.opensdf
80 | *.sdf
81 | *.cachefile
82 |
83 | # Visual Studio profiler
84 | *.psess
85 | *.vsp
86 | *.vspx
87 | *.sap
88 |
89 | # TFS 2012 Local Workspace
90 | $tf/
91 |
92 | # Guidance Automation Toolkit
93 | *.gpState
94 |
95 | # ReSharper is a .NET coding add-in
96 | _ReSharper*/
97 | *.[Rr]e[Ss]harper
98 | *.DotSettings.user
99 |
100 | # JustCode is a .NET coding add-in
101 | .JustCode
102 |
103 | # TeamCity is a build add-in
104 | _TeamCity*
105 |
106 | # DotCover is a Code Coverage Tool
107 | *.dotCover
108 |
109 | # NCrunch
110 | _NCrunch_*
111 | .*crunch*.local.xml
112 | nCrunchTemp_*
113 |
114 | # MightyMoose
115 | *.mm.*
116 | AutoTest.Net/
117 |
118 | # Web workbench (sass)
119 | .sass-cache/
120 |
121 | # Installshield output folder
122 | [Ee]xpress/
123 |
124 | # DocProject is a documentation generator add-in
125 | DocProject/buildhelp/
126 | DocProject/Help/*.HxT
127 | DocProject/Help/*.HxC
128 | DocProject/Help/*.hhc
129 | DocProject/Help/*.hhk
130 | DocProject/Help/*.hhp
131 | DocProject/Help/Html2
132 | DocProject/Help/html
133 |
134 | # Click-Once directory
135 | publish/
136 |
137 | # Publish Web Output
138 | *.[Pp]ublish.xml
139 | *.azurePubxml
140 | # TODO: Comment the next line if you want to checkin your web deploy settings
141 | # but database connection strings (with potential passwords) will be unencrypted
142 | *.pubxml
143 | *.publishproj
144 |
145 | # NuGet Packages
146 | *.nupkg
147 | # The packages folder can be ignored because of Package Restore
148 | **/packages/*
149 | # except build/, which is used as an MSBuild target.
150 | !**/packages/build/
151 | # Uncomment if necessary however generally it will be regenerated when needed
152 | #!**/packages/repositories.config
153 | # NuGet v3's project.json files produces more ignoreable files
154 | *.nuget.props
155 | *.nuget.targets
156 |
157 | # Microsoft Azure Build Output
158 | csx/
159 | *.build.csdef
160 |
161 | # Microsoft Azure Emulator
162 | ecf/
163 | rcf/
164 |
165 | # Microsoft Azure ApplicationInsights config file
166 | ApplicationInsights.config
167 |
168 | # Windows Store app package directory
169 | AppPackages/
170 | BundleArtifacts/
171 |
172 | # Visual Studio cache files
173 | # files ending in .cache can be ignored
174 | *.[Cc]ache
175 | # but keep track of directories ending in .cache
176 | !*.[Cc]ache/
177 |
178 | # Others
179 | ClientBin/
180 | ~$*
181 | *~
182 | *.dbmdl
183 | *.dbproj.schemaview
184 | *.publishsettings
185 | node_modules/
186 | orleans.codegen.cs
187 |
188 | # RIA/Silverlight projects
189 | Generated_Code/
190 |
191 | # Backup & report files from converting an old project file
192 | # to a newer Visual Studio version. Backup files are not needed,
193 | # because we have git ;-)
194 | _UpgradeReport_Files/
195 | Backup*/
196 | UpgradeLog*.XML
197 | UpgradeLog*.htm
198 |
199 | # SQL Server files
200 | *.mdf
201 | *.ldf
202 |
203 | # Business Intelligence projects
204 | *.rdl.data
205 | *.bim.layout
206 | *.bim_*.settings
207 |
208 | # Microsoft Fakes
209 | FakesAssemblies/
210 |
211 | # GhostDoc plugin setting file
212 | *.GhostDoc.xml
213 |
214 | # Node.js Tools for Visual Studio
215 | .ntvs_analysis.dat
216 |
217 | # Visual Studio 6 build log
218 | *.plg
219 |
220 | # Visual Studio 6 workspace options file
221 | *.opt
222 |
223 | # Visual Studio LightSwitch build output
224 | **/*.HTMLClient/GeneratedArtifacts
225 | **/*.DesktopClient/GeneratedArtifacts
226 | **/*.DesktopClient/ModelManifest.xml
227 | **/*.Server/GeneratedArtifacts
228 | **/*.Server/ModelManifest.xml
229 | _Pvt_Extensions
230 |
231 | # Paket dependency manager
232 | .paket/paket.exe
233 |
234 | # FAKE - F# Make
235 | .fake/
236 |
--------------------------------------------------------------------------------
/DnsProxy.Service/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/DnsProxy.Service/DnsProxy.Service.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {89D75CFC-27E7-4D7A-BADF-DC4874BC5474}
8 | WinExe
9 | Properties
10 | DnsProxy
11 | DnsProxyService
12 | v4.6
13 | 512
14 | true
15 | publish\
16 | true
17 | Disk
18 | false
19 | Foreground
20 | 7
21 | Days
22 | false
23 | false
24 | true
25 | 0
26 | 1.0.0.%2a
27 | false
28 | false
29 | true
30 |
31 |
32 | AnyCPU
33 | true
34 | full
35 | false
36 | bin\Debug\
37 | DEBUG;TRACE
38 | prompt
39 | 4
40 |
41 |
42 | AnyCPU
43 | pdbonly
44 | true
45 | bin\Release\
46 | TRACE
47 | prompt
48 | 4
49 |
50 |
51 | DnsProxy.Program
52 |
53 |
54 |
55 | ..\packages\ARSoft.Tools.Net.2.2.6\lib\net45\ARSoft.Tools.Net.dll
56 | True
57 |
58 |
59 | ..\packages\BouncyCastle.1.8.1\lib\BouncyCastle.Crypto.dll
60 | True
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | Component
73 |
74 |
75 | ProjectInstaller.cs
76 |
77 |
78 | Component
79 |
80 |
81 | Service.cs
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 | ProjectInstaller.cs
93 |
94 |
95 | Service.cs
96 |
97 |
98 |
99 |
100 | False
101 | Microsoft .NET Framework 4.6 %28x86 and x64%29
102 | true
103 |
104 |
105 | False
106 | .NET Framework 3.5 SP1
107 | false
108 |
109 |
110 |
111 |
112 | Always
113 |
114 |
115 |
116 |
123 |
--------------------------------------------------------------------------------
/DnsProxy.Service/Program.cs:
--------------------------------------------------------------------------------
1 | using System.ServiceProcess;
2 |
3 | namespace DnsProxy
4 | {
5 | static class Program
6 | {
7 | ///
8 | /// The main entry point for the application.
9 | ///
10 | static void Main()
11 | {
12 | #if !(DEBUG)
13 | ServiceBase[] ServicesToRun;
14 | ServicesToRun = new ServiceBase[]
15 | {
16 | new Service()
17 | };
18 | ServiceBase.Run(ServicesToRun);
19 | #else
20 | var service = new Service();
21 | service.DebugRun(new string[] { });
22 | System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
23 | #endif
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/DnsProxy.Service/ProjectInstaller.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace DnsProxy
2 | {
3 | partial class ProjectInstaller
4 | {
5 | ///
6 | /// Required designer variable.
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// Clean up any resources being used.
12 | ///
13 | /// true if managed resources should be disposed; otherwise, false.
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Component Designer generated code
24 |
25 | ///
26 | /// Required method for Designer support - do not modify
27 | /// the contents of this method with the code editor.
28 | ///
29 | private void InitializeComponent()
30 | {
31 | this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
32 | this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
33 | //
34 | // serviceProcessInstaller1
35 | //
36 | this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
37 | this.serviceProcessInstaller1.Password = null;
38 | this.serviceProcessInstaller1.Username = null;
39 | //
40 | // serviceInstaller1
41 | //
42 | this.serviceInstaller1.Description = "This DNS service listens to the client requests and uses Host\'s resolver to retur" +
43 | "n responses. Used in conjunction with the NAT virtual switch for Hyper-V which d" +
44 | "oes not provide DNS resolution.";
45 | this.serviceInstaller1.DisplayName = "Dns Proxy For Hyper-V";
46 | this.serviceInstaller1.ServiceName = "DnsProxy";
47 | this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
48 | //
49 | // ProjectInstaller
50 | //
51 | this.Installers.AddRange(new System.Configuration.Install.Installer[] {
52 | this.serviceProcessInstaller1,
53 | this.serviceInstaller1});
54 |
55 | }
56 |
57 | #endregion
58 |
59 | private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
60 | private System.ServiceProcess.ServiceInstaller serviceInstaller1;
61 | }
62 | }
--------------------------------------------------------------------------------
/DnsProxy.Service/ProjectInstaller.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 |
3 | namespace DnsProxy
4 | {
5 | [RunInstaller(true)]
6 | public partial class ProjectInstaller : System.Configuration.Install.Installer
7 | {
8 | public ProjectInstaller()
9 | {
10 | InitializeComponent();
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/DnsProxy.Service/ProjectInstaller.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | 17, 17
122 |
123 |
124 | 229, 17
125 |
126 |
127 | False
128 |
129 |
--------------------------------------------------------------------------------
/DnsProxy.Service/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("DnsProxy Service")]
8 | [assembly: AssemblyDescription("Windows service to respond to DNS requests from Hyper-V guests by using Host DNS resolver")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("Roman Tumaykin")]
11 | [assembly: AssemblyProduct("DnsProxy Service For Hyper-V")]
12 | [assembly: AssemblyCopyright("Copyright © Roman Tumaykin 2016")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("89d75cfc-27e7-4d7a-badf-dc4874bc5474")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.3.0.0")]
35 | [assembly: AssemblyFileVersion("1.3.0.0")]
36 |
--------------------------------------------------------------------------------
/DnsProxy.Service/Service.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace DnsProxy
2 | {
3 | partial class Service
4 | {
5 | ///
6 | /// Required designer variable.
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// Clean up any resources being used.
12 | ///
13 | /// true if managed resources should be disposed; otherwise, false.
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Component Designer generated code
24 |
25 | ///
26 | /// Required method for Designer support - do not modify
27 | /// the contents of this method with the code editor.
28 | ///
29 | private void InitializeComponent()
30 | {
31 | //
32 | // DnsProxy
33 | //
34 | this.ServiceName = "DnsProxy";
35 |
36 | }
37 |
38 | #endregion
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/DnsProxy.Service/Service.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Net;
3 | using System.ServiceProcess;
4 | using System.Threading.Tasks;
5 | using ARSoft.Tools.Net.Dns;
6 |
7 | namespace DnsProxy
8 | {
9 | public partial class Service : ServiceBase
10 | {
11 | public Service()
12 | {
13 | InitializeComponent();
14 | }
15 |
16 | #if DEBUG
17 | public void DebugRun(string[] args)
18 | {
19 | OnStart(args);
20 | }
21 | #endif
22 |
23 | protected override void OnStart(string[] args)
24 | {
25 | ServiceManager.Start();
26 | }
27 |
28 | protected override void OnPause()
29 | {
30 | ServiceManager.Stop();
31 | }
32 |
33 | protected override void OnContinue()
34 | {
35 | ServiceManager.Start();
36 | }
37 |
38 | protected override void OnStop()
39 | {
40 | ServiceManager.Stop();
41 | }
42 |
43 | protected override void OnShutdown()
44 | {
45 | ServiceManager.Stop();
46 | base.OnShutdown();
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/DnsProxy.Service/Service.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | False
122 |
123 |
--------------------------------------------------------------------------------
/DnsProxy.Service/ServiceManager.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Management;
5 | using System.Net;
6 | using System.Text.RegularExpressions;
7 | using System.Threading;
8 | using System.Threading.Tasks;
9 | using ARSoft.Tools.Net.Dns;
10 |
11 | namespace DnsProxy
12 | {
13 | public static class ServiceManager
14 | {
15 | #region Private variables
16 |
17 | private static readonly Dictionary Servers = new Dictionary();
18 |
19 | private static Timer _scheduler;
20 | private static readonly object Lock = new object();
21 |
22 | #endregion // Private variables
23 |
24 | #region WMI data retrievers
25 |
26 | private static IEnumerable GetNetworkInterfaceIpAddresses(uint[] virtualAdaptersInterfaceIds)
27 | {
28 | if (virtualAdaptersInterfaceIds == null || virtualAdaptersInterfaceIds.Length == 0)
29 | yield break;
30 |
31 | var scope = new ManagementScope(@"root\StandardCimv2");
32 | var queryString = "SELECT * FROM MSFT_NetIPAddress WHERE " +
33 | string.Join(" OR ", virtualAdaptersInterfaceIds.Select(i => $"InterfaceIndex = {i}"));
34 |
35 | var query = new ObjectQuery(queryString);
36 | using (var searcher = new ManagementObjectSearcher(scope, query))
37 | {
38 | using (var ipAddresses = searcher.Get())
39 | {
40 | foreach (var ipAddress in ipAddresses)
41 | {
42 | yield return $"{ipAddress["IPAddress"]}/{ipAddress["PrefixLength"]}";
43 | }
44 | }
45 | }
46 | }
47 |
48 |
49 | private static IEnumerable GetVirtualAdaptersInterfaceIds(string [] internalEthernetDeviceIds)
50 | {
51 | if (internalEthernetDeviceIds == null || internalEthernetDeviceIds.Length == 0)
52 | yield break;
53 |
54 | var scope = new ManagementScope(@"root\StandardCimv2");
55 | var queryString = "SELECT * FROM MSFT_NetAdapter WHERE " +
56 | string.Join(" OR ", internalEthernetDeviceIds.Select(d => $"DeviceID = \"{{{d}}}\""));
57 |
58 | var query = new ObjectQuery(queryString);
59 | using (var searcher = new ManagementObjectSearcher(scope, query))
60 | {
61 | using (var virtualAdapters = searcher.Get())
62 | {
63 | foreach (var virtualAdapter in virtualAdapters)
64 | {
65 | yield return (uint) virtualAdapter["InterfaceIndex"];
66 | }
67 | }
68 | }
69 | }
70 |
71 | private static IEnumerable GetInternalEthernetDeviceIds()
72 | {
73 | var scope = new ManagementScope(@"root\virtualization\v2");
74 | var query = new ObjectQuery("select * from Msvm_InternalEthernetPort");
75 | using (var results = new ManagementObjectSearcher(scope, query))
76 | {
77 | using (var internalEthernetPorts = results.Get())
78 | {
79 | foreach (var internalEthernetPort in internalEthernetPorts)
80 | {
81 | var fullDeviceId = (string) internalEthernetPort["DeviceID"];
82 | var foundMatches = Regex.Matches(fullDeviceId,
83 | @"[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}");
84 | if (foundMatches.Count > 0)
85 | yield return foundMatches[0].Value;
86 | }
87 | }
88 | }
89 | }
90 |
91 |
92 | private static IEnumerable GetNatSubnets()
93 | {
94 | var scope = new ManagementScope(@"root\StandardCimv2");
95 | var query = new ObjectQuery("SELECT * FROM MSFT_NetNat");
96 | using (var searcher = new ManagementObjectSearcher(scope, query))
97 | {
98 | using (var natObjects = searcher.Get())
99 | {
100 | foreach (var natObject in natObjects)
101 | {
102 | if ((byte) natObject["Active"] == 1)
103 | {
104 | var subnet = (string) natObject["InternalIPInterfaceAddressPrefix"];
105 | if (!string.IsNullOrWhiteSpace(subnet))
106 | {
107 | yield return subnet;
108 | }
109 | }
110 | }
111 | }
112 | }
113 | }
114 |
115 | #endregion // WMI data retrievers
116 |
117 |
118 | #region Service Management Methods
119 | public static void Start()
120 | {
121 |
122 | _scheduler = new Timer(Cycle, null, 0, 15000);
123 | }
124 |
125 |
126 | private static void Cycle(object o)
127 | {
128 |
129 | lock (Lock)
130 | {
131 | var natSubnets = GetNatSubnets().ToArray();
132 | var internalEthernetDeviceIds = GetInternalEthernetDeviceIds().ToArray();
133 | var virtualAdaptersInterfaceIds = GetVirtualAdaptersInterfaceIds(internalEthernetDeviceIds).ToArray();
134 | var networkInterfaceIpAddresses = GetNetworkInterfaceIpAddresses(virtualAdaptersInterfaceIds).ToArray();
135 | var ipAddressesForBinding = GetIpAddressesForBinding(networkInterfaceIpAddresses, natSubnets).ToArray();
136 |
137 | var currentlyBoundAddresses = Servers.Keys.ToArray();
138 |
139 | foreach (
140 | var ipAddressForBinding in
141 | ipAddressesForBinding.Where(a => !currentlyBoundAddresses.Contains(a)))
142 | {
143 | BindListener(ipAddressForBinding);
144 | }
145 |
146 | foreach (
147 | var ipAddressForBinding in
148 | currentlyBoundAddresses.Where(a => !ipAddressesForBinding.Contains(a)))
149 | {
150 | UnBindListener(ipAddressForBinding);
151 | }
152 | }
153 |
154 | }
155 |
156 |
157 | private static void BindListener(string ipAddressForBinding)
158 | {
159 | IPAddress ip;
160 |
161 | if (!IPAddress.TryParse(ipAddressForBinding, out ip))
162 | return;
163 |
164 | if (Servers.ContainsKey(ipAddressForBinding))
165 | return;
166 |
167 | var dnsServer = new DnsServer(ip, 10, 10);
168 | dnsServer.QueryReceived += OnQueryReceived;
169 | Servers.Add(ipAddressForBinding, dnsServer);
170 | dnsServer.Start();
171 |
172 | var appLog = new System.Diagnostics.EventLog {Source = "Hyper-V Dns Proxy"};
173 | appLog.WriteEntry($"Started DNS Service on {ipAddressForBinding}");
174 | }
175 |
176 | private static async Task OnQueryReceived(object sender, QueryReceivedEventArgs e)
177 | {
178 | var message = e.Query as DnsMessage;
179 |
180 | var response = message?.CreateResponseInstance();
181 |
182 | if (message?.Questions.Count == 1)
183 | {
184 | // send query to upstream _servers
185 | var question = message.Questions[0];
186 |
187 | var upstreamResponse =
188 | await DnsClient.Default.ResolveAsync(question.Name, question.RecordType, question.RecordClass);
189 |
190 | // if got an answer, copy it to the message sent to the client
191 | if (upstreamResponse != null)
192 | {
193 | foreach (var record in (upstreamResponse.AnswerRecords))
194 | {
195 | response.AnswerRecords.Add(record);
196 | }
197 | foreach (var record in (upstreamResponse.AdditionalRecords))
198 | {
199 | response.AdditionalRecords.Add(record);
200 | }
201 |
202 | response.ReturnCode = ReturnCode.NoError;
203 |
204 | // set the response
205 | e.Response = response;
206 | }
207 | }
208 | }
209 |
210 | private static void UnBindListener(string ipAddressForBinding)
211 | {
212 | DnsServer server;
213 | if (!Servers.TryGetValue(ipAddressForBinding, out server))
214 | return;
215 |
216 | server.Stop();
217 | Servers.Remove(ipAddressForBinding);
218 | var appLog = new System.Diagnostics.EventLog { Source = "Hyper-V Dns Proxy" };
219 | appLog.WriteEntry($"Stopped DNS Service on {ipAddressForBinding}");
220 | }
221 |
222 |
223 | private static IEnumerable GetIpAddressesForBinding(string[] networkInterfaceIpAddresses, string[] natSubnets)
224 | {
225 | if (networkInterfaceIpAddresses == null || natSubnets == null)
226 | yield break;
227 |
228 | foreach (var networkInterfaceIpAddress in networkInterfaceIpAddresses)
229 | {
230 | var ipParts = networkInterfaceIpAddress.Split('/');
231 | var interfaceIp = BitConverter.ToInt32(IPAddress.Parse(ipParts[0]).GetAddressBytes(), 0);
232 | var interfaceMask = IPAddress.HostToNetworkOrder(-1 << (32 - int.Parse(ipParts[1])));
233 | foreach (var natSubnet in natSubnets)
234 | {
235 | var subnetParts = natSubnet.Split('/');
236 | var subnetIp = BitConverter.ToInt32(IPAddress.Parse(subnetParts[0]).GetAddressBytes(), 0);
237 | var subnetMask = IPAddress.HostToNetworkOrder(-1 << (32 - int.Parse(subnetParts[1])));
238 |
239 | if ((interfaceIp & interfaceMask) == (subnetIp & subnetMask))
240 | {
241 | yield return ipParts[0];
242 | }
243 |
244 | }
245 | }
246 | }
247 |
248 | public static void Stop()
249 | {
250 | _scheduler.Dispose();
251 | _scheduler = null;
252 | UnbindListeners();
253 | }
254 |
255 | private static void UnbindListeners()
256 | {
257 | lock (Lock)
258 | {
259 | var ipAddressesForUnBinding = Servers.Keys.ToArray();
260 |
261 | foreach (var ipAddressForUnbinding in ipAddressesForUnBinding)
262 | {
263 | UnBindListener(ipAddressForUnbinding);
264 | }
265 | }
266 | }
267 |
268 | #endregion // Service Management Methods
269 | }
270 | }
271 |
--------------------------------------------------------------------------------
/DnsProxy.Service/dns.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rtumaykin/hyperv-dnsproxy/075b416bb3e881939f098e30db27f02f294e5c75/DnsProxy.Service/dns.ico
--------------------------------------------------------------------------------
/DnsProxy.Service/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/DnsProxy.SetupPackage/DnsProxy.SetupPackage.wixproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | x86
7 | 3.10
8 | 7de5a53a-646c-4cc7-9b04-caded8350296
9 | 2.0
10 | DnsProxy
11 | Package
12 | $(MSBuildExtensionsPath32)\Microsoft\WiX\v3.x\Wix.targets
13 | $(MSBuildExtensionsPath)\Microsoft\WiX\v3.x\Wix.targets
14 |
15 |
16 |
17 |
18 | bin\$(Configuration)\
19 | obj\$(Configuration)\
20 | Debug
21 |
22 |
23 | bin\$(Configuration)\
24 | obj\$(Configuration)\
25 |
26 |
27 |
28 |
29 |
30 |
31 | DnsProxy.Service
32 | {89d75cfc-27e7-4d7a-badf-dc4874bc5474}
33 | True
34 | True
35 | Binaries;Content;Satellites
36 | INSTALLFOLDER
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 | ..\packages\WiX.3.10.3\tools\WixUIExtension.dll
45 | WixUIExtension
46 |
47 |
48 | ..\packages\WiX.3.10.3\tools\WixNetFxExtension.dll
49 | WixNetFxExtension
50 |
51 |
52 |
53 |
54 |
55 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.
56 |
57 |
58 |
59 |
67 |
--------------------------------------------------------------------------------
/DnsProxy.SetupPackage/Product.wxs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | 1
59 | "1"]]>
60 |
61 | 1
62 |
63 | NOT Installed
64 | Installed AND PATCH
65 |
66 | 1
67 | 1
68 | NOT WIXUI_DONTVALIDATEPATH
69 | "1"]]>
70 | WIXUI_DONTVALIDATEPATH OR WIXUI_INSTALLDIR_VALID="1"
71 | 1
72 | 1
73 |
74 | NOT Installed
75 | Installed AND NOT PATCH
76 | Installed AND PATCH
77 |
78 | 1
79 |
80 | 1
81 | 1
82 | 1
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
108 |
109 |
110 |
111 |
117 |
118 |
119 |
120 |
--------------------------------------------------------------------------------
/DnsProxy.SetupPackage/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # hyperv-dnsproxy
2 | This DNS service listens to the client requests and uses Host's resolver to return responses. Used in conjunction with the NAT virtual switch for Hyper-V which does not provide DNS resolution.
3 |
--------------------------------------------------------------------------------
/hyperv-dnsproxy.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.24720.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DnsProxy.Service", "DnsProxy.Service\DnsProxy.Service.csproj", "{89D75CFC-27E7-4D7A-BADF-DC4874BC5474}"
7 | EndProject
8 | Project("{930C7802-8A8C-48F9-8165-68863BCCD9DD}") = "DnsProxy.SetupPackage", "DnsProxy.SetupPackage\DnsProxy.SetupPackage.wixproj", "{7DE5A53A-646C-4CC7-9B04-CADED8350296}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Debug|x86 = Debug|x86
14 | Release|Any CPU = Release|Any CPU
15 | Release|x86 = Release|x86
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {89D75CFC-27E7-4D7A-BADF-DC4874BC5474}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {89D75CFC-27E7-4D7A-BADF-DC4874BC5474}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {89D75CFC-27E7-4D7A-BADF-DC4874BC5474}.Debug|x86.ActiveCfg = Debug|Any CPU
21 | {89D75CFC-27E7-4D7A-BADF-DC4874BC5474}.Debug|x86.Build.0 = Debug|Any CPU
22 | {89D75CFC-27E7-4D7A-BADF-DC4874BC5474}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {89D75CFC-27E7-4D7A-BADF-DC4874BC5474}.Release|Any CPU.Build.0 = Release|Any CPU
24 | {89D75CFC-27E7-4D7A-BADF-DC4874BC5474}.Release|x86.ActiveCfg = Release|Any CPU
25 | {89D75CFC-27E7-4D7A-BADF-DC4874BC5474}.Release|x86.Build.0 = Release|Any CPU
26 | {7DE5A53A-646C-4CC7-9B04-CADED8350296}.Debug|Any CPU.ActiveCfg = Debug|x86
27 | {7DE5A53A-646C-4CC7-9B04-CADED8350296}.Debug|x86.ActiveCfg = Debug|x86
28 | {7DE5A53A-646C-4CC7-9B04-CADED8350296}.Debug|x86.Build.0 = Debug|x86
29 | {7DE5A53A-646C-4CC7-9B04-CADED8350296}.Release|Any CPU.ActiveCfg = Release|x86
30 | {7DE5A53A-646C-4CC7-9B04-CADED8350296}.Release|x86.ActiveCfg = Release|x86
31 | {7DE5A53A-646C-4CC7-9B04-CADED8350296}.Release|x86.Build.0 = Release|x86
32 | EndGlobalSection
33 | GlobalSection(SolutionProperties) = preSolution
34 | HideSolutionNode = FALSE
35 | EndGlobalSection
36 | EndGlobal
37 |
--------------------------------------------------------------------------------