AddressTranslation.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2024 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerCore.ApplicationCommon;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Net;
  20. using System.Net.Sockets;
  21. using System.Text.Json;
  22. using System.Threading.Tasks;
  23. using TechnitiumLibrary;
  24. using TechnitiumLibrary.Net;
  25. using TechnitiumLibrary.Net.Dns;
  26. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  27. namespace SplitHorizon
  28. {
  29. public sealed class AddressTranslation : IDnsApplication, IDnsPostProcessor, IDnsAuthoritativeRequestHandler
  30. {
  31. #region variables
  32. bool _enableAddressTranslation;
  33. Dictionary<NetworkAddress, string> _networkGroupMap;
  34. Dictionary<string, Group> _groups;
  35. #endregion
  36. #region IDisposable
  37. public void Dispose()
  38. {
  39. //do nothing
  40. }
  41. #endregion
  42. #region public
  43. public async Task InitializeAsync(IDnsServer dnsServer, string config)
  44. {
  45. if (string.IsNullOrEmpty(config) || config.StartsWith('#'))
  46. {
  47. //replace old config with default config
  48. config = """
  49. {
  50. "networks": {
  51. "custom-networks": [
  52. "172.16.1.0/24",
  53. "172.16.10.0/24",
  54. "172.16.2.1"
  55. ]
  56. },
  57. "enableAddressTranslation": false,
  58. "networkGroupMap": {
  59. "10.0.0.0/8": "local1",
  60. "172.16.0.0/12": "local2",
  61. "192.168.0.0/16": "local3"
  62. },
  63. "groups": [
  64. {
  65. "name": "local1",
  66. "enabled": true,
  67. "translateReverseLookups": true,
  68. "externalToInternalTranslation": {
  69. "1.2.3.0/24": "10.0.0.0/24",
  70. "5.6.7.8": "10.0.0.5"
  71. }
  72. },
  73. {
  74. "name": "local2",
  75. "enabled": true,
  76. "translateReverseLookups": true,
  77. "externalToInternalTranslation": {
  78. "1.2.3.4": "172.16.0.4",
  79. "5.6.7.8": "172.16.0.5"
  80. }
  81. },
  82. {
  83. "name": "local3",
  84. "enabled": true,
  85. "translateReverseLookups": true,
  86. "externalToInternalTranslation": {
  87. "1.2.3.4": "192.168.0.4",
  88. "5.6.7.8": "192.168.0.5"
  89. }
  90. }
  91. ]
  92. }
  93. """;
  94. await File.WriteAllTextAsync(Path.Combine(dnsServer.ApplicationFolder, "dnsApp.config"), config);
  95. }
  96. do
  97. {
  98. using JsonDocument jsonDocument = JsonDocument.Parse(config);
  99. JsonElement jsonConfig = jsonDocument.RootElement;
  100. if (!jsonConfig.TryGetProperty("enableAddressTranslation", out _))
  101. {
  102. //update old config with default config
  103. config = config.TrimEnd(' ', '\t', '\r', '\n');
  104. config = config.Substring(0, config.Length - 1);
  105. config = config.TrimEnd(' ', '\t', '\r', '\n');
  106. config += """
  107. ,
  108. "enableAddressTranslation": false,
  109. "networkGroupMap": {
  110. "10.0.0.0/8": "local1",
  111. "172.16.0.0/12": "local2",
  112. "192.168.0.0/16": "local3"
  113. },
  114. "groups": [
  115. {
  116. "name": "local1",
  117. "enabled": true,
  118. "translateReverseLookups": true,
  119. "externalToInternalTranslation": {
  120. "1.2.3.0/24": "10.0.0.0/24",
  121. "5.6.7.8": "10.0.0.5"
  122. }
  123. },
  124. {
  125. "name": "local2",
  126. "enabled": true,
  127. "translateReverseLookups": true,
  128. "externalToInternalTranslation": {
  129. "1.2.3.4": "172.16.0.4",
  130. "5.6.7.8": "172.16.0.5"
  131. }
  132. },
  133. {
  134. "name": "local3",
  135. "enabled": true,
  136. "translateReverseLookups": true,
  137. "externalToInternalTranslation": {
  138. "1.2.3.4": "192.168.0.4",
  139. "5.6.7.8": "192.168.0.5"
  140. }
  141. }
  142. ]
  143. }
  144. """;
  145. await File.WriteAllTextAsync(Path.Combine(dnsServer.ApplicationFolder, "dnsApp.config"), config);
  146. //reparse config
  147. continue;
  148. }
  149. _enableAddressTranslation = jsonConfig.GetProperty("enableAddressTranslation").GetBoolean();
  150. _networkGroupMap = jsonConfig.ReadObjectAsMap("networkGroupMap", delegate (string strNetworkAddress, JsonElement jsonGroupName)
  151. {
  152. if (!NetworkAddress.TryParse(strNetworkAddress, out NetworkAddress networkAddress))
  153. throw new InvalidOperationException("Network group map contains an invalid network address: " + strNetworkAddress);
  154. return new Tuple<NetworkAddress, string>(networkAddress, jsonGroupName.GetString());
  155. });
  156. _groups = jsonConfig.ReadArrayAsMap("groups", delegate (JsonElement jsonGroup)
  157. {
  158. Group group = new Group(jsonGroup);
  159. return new Tuple<string, Group>(group.Name, group);
  160. });
  161. break;
  162. }
  163. while (true);
  164. }
  165. public Task<DnsDatagram> PostProcessAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, DnsDatagram response)
  166. {
  167. if (!_enableAddressTranslation)
  168. return Task.FromResult(response);
  169. if (response.RCODE != DnsResponseCode.NoError)
  170. return Task.FromResult(response);
  171. DnsQuestionRecord question = request.Question[0];
  172. switch (question.Type)
  173. {
  174. case DnsResourceRecordType.A:
  175. case DnsResourceRecordType.AAAA:
  176. break;
  177. default:
  178. return Task.FromResult(response);
  179. }
  180. if (response.Answer.Count == 0)
  181. return Task.FromResult(response);
  182. IPAddress remoteIP = remoteEP.Address;
  183. NetworkAddress network = null;
  184. string groupName = null;
  185. foreach (KeyValuePair<NetworkAddress, string> entry in _networkGroupMap)
  186. {
  187. if (entry.Key.Contains(remoteIP) && ((network is null) || (entry.Key.PrefixLength > network.PrefixLength)))
  188. {
  189. network = entry.Key;
  190. groupName = entry.Value;
  191. }
  192. }
  193. if ((groupName is null) || !_groups.TryGetValue(groupName, out Group group) || !group.Enabled)
  194. return Task.FromResult(response);
  195. List<DnsResourceRecord> newAnswer = new List<DnsResourceRecord>(response.Answer.Count);
  196. foreach (DnsResourceRecord answer in response.Answer)
  197. {
  198. switch (answer.Type)
  199. {
  200. case DnsResourceRecordType.A:
  201. {
  202. IPAddress externalIp = (answer.RDATA as DnsARecordData).Address;
  203. if (group.TryExternalToInternalTranslation(externalIp, out IPAddress internalIp))
  204. newAnswer.Add(new DnsResourceRecord(answer.Name, answer.Type, answer.Class, answer.TTL, new DnsARecordData(internalIp)));
  205. else
  206. newAnswer.Add(answer);
  207. }
  208. break;
  209. case DnsResourceRecordType.AAAA:
  210. {
  211. IPAddress externalIp = (answer.RDATA as DnsAAAARecordData).Address;
  212. if (group.TryExternalToInternalTranslation(externalIp, out IPAddress internalIp))
  213. newAnswer.Add(new DnsResourceRecord(answer.Name, answer.Type, answer.Class, answer.TTL, new DnsAAAARecordData(internalIp)));
  214. else
  215. newAnswer.Add(answer);
  216. }
  217. break;
  218. default:
  219. newAnswer.Add(answer);
  220. break;
  221. }
  222. }
  223. return Task.FromResult(response.Clone(newAnswer));
  224. }
  225. public Task<DnsDatagram> ProcessRequestAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed)
  226. {
  227. if (!_enableAddressTranslation)
  228. return Task.FromResult<DnsDatagram>(null);
  229. DnsQuestionRecord question = request.Question[0];
  230. if (question.Type != DnsResourceRecordType.PTR)
  231. return Task.FromResult<DnsDatagram>(null);
  232. IPAddress remoteIP = remoteEP.Address;
  233. NetworkAddress network = null;
  234. string groupName = null;
  235. foreach (KeyValuePair<NetworkAddress, string> entry in _networkGroupMap)
  236. {
  237. if (entry.Key.Contains(remoteIP) && ((network is null) || (entry.Key.PrefixLength > network.PrefixLength)))
  238. {
  239. network = entry.Key;
  240. groupName = entry.Value;
  241. }
  242. }
  243. if ((groupName is null) || !_groups.TryGetValue(groupName, out Group group) || !group.Enabled || !group.TranslateReverseLookups)
  244. return Task.FromResult<DnsDatagram>(null);
  245. IPAddress ptrIpAddress = IPAddressExtensions.ParseReverseDomain(question.Name);
  246. if (!group.TryInternalToExternalTranslation(ptrIpAddress, out IPAddress externalIp))
  247. return Task.FromResult<DnsDatagram>(null);
  248. IReadOnlyList<DnsResourceRecord> answer = new DnsResourceRecord[] { new DnsResourceRecord(question.Name, DnsResourceRecordType.CNAME, question.Class, 600, new DnsCNAMERecordData(externalIp.GetReverseDomain())) };
  249. return Task.FromResult(new DnsDatagram(request.Identifier, true, request.OPCODE, true, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.NoError, request.Question, answer));
  250. }
  251. #endregion
  252. #region properties
  253. public string Description
  254. { get { return "Translates IP addresses in DNS response for A & AAAA type request based on the client's network address and the configured 1:1 translation. Also supports reverse (PTR) queries for translated addresses."; } }
  255. #endregion
  256. class Group
  257. {
  258. #region variables
  259. readonly string _name;
  260. readonly bool _enabled;
  261. readonly bool _translateReverseLookups;
  262. readonly Dictionary<IPAddress, IPAddress> _externalToInternalTranslation;
  263. readonly Dictionary<IPAddress, IPAddress> _internalToExternalTranslation;
  264. readonly List<KeyValuePair<NetworkAddress, NetworkAddress>> _externalToInternalNetworkTranslation;
  265. #endregion
  266. #region constructor
  267. public Group(JsonElement jsonGroup)
  268. {
  269. _name = jsonGroup.GetProperty("name").GetString();
  270. _enabled = jsonGroup.GetProperty("enabled").GetBoolean();
  271. _translateReverseLookups = jsonGroup.GetProperty("translateReverseLookups").GetBoolean();
  272. JsonElement jsonExternalToInternalTranslation = jsonGroup.GetProperty("externalToInternalTranslation");
  273. Dictionary<IPAddress, IPAddress> externalToInternalIpTranslation = new Dictionary<IPAddress, IPAddress>();
  274. Dictionary<IPAddress, IPAddress> internalToExternalIpTranslation = new Dictionary<IPAddress, IPAddress>();
  275. List<KeyValuePair<NetworkAddress, NetworkAddress>> externalToInternalNetworkTranslation = new List<KeyValuePair<NetworkAddress, NetworkAddress>>();
  276. foreach (JsonProperty jsonProperty in jsonExternalToInternalTranslation.EnumerateObject())
  277. {
  278. string strExternal = jsonProperty.Name;
  279. string strInternal = jsonProperty.Value.GetString();
  280. NetworkAddress external = NetworkAddress.Parse(strExternal);
  281. NetworkAddress @internal = NetworkAddress.Parse(strInternal);
  282. if (external.AddressFamily != @internal.AddressFamily)
  283. throw new InvalidDataException("External to internal translation entries must have same address family: " + strExternal + " - " + strInternal);
  284. if (external.PrefixLength != @internal.PrefixLength)
  285. throw new InvalidDataException("External to internal translation entries must have same prefix length: " + strExternal + " - " + strInternal);
  286. if (
  287. ((external.AddressFamily == AddressFamily.InterNetwork) && (external.PrefixLength == 32)) ||
  288. ((external.AddressFamily == AddressFamily.InterNetworkV6) && (external.PrefixLength == 128))
  289. )
  290. {
  291. externalToInternalIpTranslation.TryAdd(external.Address, @internal.Address);
  292. if (_translateReverseLookups)
  293. internalToExternalIpTranslation.TryAdd(@internal.Address, external.Address);
  294. }
  295. else
  296. {
  297. externalToInternalNetworkTranslation.Add(new KeyValuePair<NetworkAddress, NetworkAddress>(external, @internal));
  298. }
  299. }
  300. _externalToInternalTranslation = externalToInternalIpTranslation;
  301. if (_translateReverseLookups)
  302. _internalToExternalTranslation = internalToExternalIpTranslation;
  303. _externalToInternalNetworkTranslation = externalToInternalNetworkTranslation;
  304. }
  305. #endregion
  306. #region public
  307. public bool TryExternalToInternalTranslation(IPAddress externalIp, out IPAddress internalIp)
  308. {
  309. if (_externalToInternalTranslation.TryGetValue(externalIp, out internalIp))
  310. return true;
  311. foreach (KeyValuePair<NetworkAddress, NetworkAddress> networkEntry in _externalToInternalNetworkTranslation)
  312. {
  313. NetworkAddress external = networkEntry.Key;
  314. if (external.AddressFamily != externalIp.AddressFamily)
  315. continue;
  316. if (external.Contains(externalIp))
  317. {
  318. NetworkAddress @internal = networkEntry.Value;
  319. switch (external.AddressFamily)
  320. {
  321. case AddressFamily.InterNetwork:
  322. {
  323. uint hostMask = ~(0xFFFFFFFFu << (32 - external.PrefixLength));
  324. uint host = externalIp.ConvertIpToNumber() & hostMask;
  325. uint addr = @internal.Address.ConvertIpToNumber();
  326. uint internalAddr = addr | host;
  327. internalIp = IPAddressExtensions.ConvertNumberToIp(internalAddr);
  328. return true;
  329. }
  330. case AddressFamily.InterNetworkV6:
  331. {
  332. byte[] externalIpBytes = externalIp.GetAddressBytes();
  333. byte[] internalIpBytes = @internal.Address.GetAddressBytes();
  334. int copyBytes = external.PrefixLength / 8;
  335. int balanceBits = external.PrefixLength - (copyBytes * 8);
  336. Buffer.BlockCopy(externalIpBytes, copyBytes + 1, internalIpBytes, copyBytes + 1, 16 - copyBytes - 1);
  337. if (balanceBits > 0)
  338. {
  339. int mask = 0xFF << (8 - balanceBits);
  340. internalIpBytes[copyBytes] = (byte)((internalIpBytes[copyBytes] & mask) | (externalIpBytes[copyBytes] & ~mask));
  341. }
  342. internalIp = new IPAddress(internalIpBytes);
  343. return true;
  344. }
  345. default:
  346. throw new InvalidOperationException();
  347. }
  348. }
  349. }
  350. internalIp = null;
  351. return false;
  352. }
  353. public bool TryInternalToExternalTranslation(IPAddress internalIp, out IPAddress externalIp)
  354. {
  355. if (_internalToExternalTranslation.TryGetValue(internalIp, out externalIp))
  356. return true;
  357. foreach (KeyValuePair<NetworkAddress, NetworkAddress> networkEntry in _externalToInternalNetworkTranslation)
  358. {
  359. NetworkAddress @internal = networkEntry.Value;
  360. if (@internal.AddressFamily != internalIp.AddressFamily)
  361. continue;
  362. if (@internal.Contains(internalIp))
  363. {
  364. NetworkAddress external = networkEntry.Key;
  365. switch (@internal.AddressFamily)
  366. {
  367. case AddressFamily.InterNetwork:
  368. {
  369. uint hostMask = ~(0xFFFFFFFFu << (32 - @internal.PrefixLength));
  370. uint host = internalIp.ConvertIpToNumber() & hostMask;
  371. uint addr = external.Address.ConvertIpToNumber();
  372. uint externalAddr = addr | host;
  373. externalIp = IPAddressExtensions.ConvertNumberToIp(externalAddr);
  374. return true;
  375. }
  376. case AddressFamily.InterNetworkV6:
  377. {
  378. byte[] internalIpBytes = internalIp.GetAddressBytes();
  379. byte[] externalIpBytes = external.Address.GetAddressBytes();
  380. int copyBytes = @internal.PrefixLength / 8;
  381. int balanceBits = @internal.PrefixLength - (copyBytes * 8);
  382. Buffer.BlockCopy(internalIpBytes, copyBytes + 1, externalIpBytes, copyBytes + 1, 16 - copyBytes - 1);
  383. if (balanceBits > 0)
  384. {
  385. int mask = 0xFF << (8 - balanceBits);
  386. externalIpBytes[copyBytes] = (byte)((externalIpBytes[copyBytes] & mask) | (internalIpBytes[copyBytes] & ~mask));
  387. }
  388. externalIp = new IPAddress(externalIpBytes);
  389. return true;
  390. }
  391. default:
  392. throw new InvalidOperationException();
  393. }
  394. }
  395. }
  396. externalIp = null;
  397. return false;
  398. }
  399. #endregion
  400. #region properties
  401. public string Name
  402. { get { return _name; } }
  403. public bool Enabled
  404. { get { return _enabled; } }
  405. public bool TranslateReverseLookups
  406. { get { return _translateReverseLookups; } }
  407. #endregion
  408. }
  409. }
  410. }