App.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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.Net;
  19. using System.Net.Sockets;
  20. using System.Text.Json;
  21. using System.Threading.Tasks;
  22. using TechnitiumLibrary;
  23. using TechnitiumLibrary.Net;
  24. using TechnitiumLibrary.Net.Dns;
  25. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  26. namespace Dns64
  27. {
  28. // DNS64: DNS Extensions for Network Address Translation from IPv6 Clients to IPv4 Servers
  29. // https://www.rfc-editor.org/rfc/rfc6147
  30. public sealed class App : IDnsApplication, IDnsPostProcessor, IDnsAuthoritativeRequestHandler
  31. {
  32. #region variables
  33. IDnsServer _dnsServer;
  34. bool _enableDns64;
  35. Dictionary<NetworkAddress, string> _networkGroupMap;
  36. Dictionary<string, Group> _groups;
  37. #endregion
  38. #region IDisposable
  39. public void Dispose()
  40. {
  41. //do nothing
  42. }
  43. #endregion
  44. #region public
  45. public Task InitializeAsync(IDnsServer dnsServer, string config)
  46. {
  47. _dnsServer = dnsServer;
  48. using JsonDocument jsonDocument = JsonDocument.Parse(config);
  49. JsonElement jsonConfig = jsonDocument.RootElement;
  50. _enableDns64 = jsonConfig.GetProperty("enableDns64").GetBoolean();
  51. _networkGroupMap = jsonConfig.ReadObjectAsMap("networkGroupMap", delegate (string network, JsonElement group)
  52. {
  53. if (!NetworkAddress.TryParse(network, out NetworkAddress networkAddress))
  54. throw new InvalidOperationException("Network group map contains an invalid network address: " + network);
  55. if (networkAddress.Address.AddressFamily == AddressFamily.InterNetwork)
  56. throw new InvalidOperationException("Network group map can only have IPv6 network addresses: " + network);
  57. return new Tuple<NetworkAddress, string>(networkAddress, group.GetString());
  58. });
  59. _groups = jsonConfig.ReadArrayAsMap("groups", delegate (JsonElement jsonGroup)
  60. {
  61. Group group = new Group(jsonGroup);
  62. return new Tuple<string, Group>(group.Name, group);
  63. });
  64. return Task.CompletedTask;
  65. }
  66. public async Task<DnsDatagram> PostProcessAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, DnsDatagram response)
  67. {
  68. if (!_enableDns64)
  69. return response;
  70. if (request.DnssecOk)
  71. return response;
  72. switch (response.RCODE)
  73. {
  74. case DnsResponseCode.NxDomain:
  75. return response;
  76. }
  77. DnsQuestionRecord question = request.Question[0];
  78. if (question.Type != DnsResourceRecordType.AAAA)
  79. return response;
  80. IPAddress remoteIP = remoteEP.Address;
  81. NetworkAddress network = null;
  82. string groupName = null;
  83. foreach (KeyValuePair<NetworkAddress, string> entry in _networkGroupMap)
  84. {
  85. if (entry.Key.Contains(remoteIP) && ((network is null) || (entry.Key.PrefixLength > network.PrefixLength)))
  86. {
  87. network = entry.Key;
  88. groupName = entry.Value;
  89. }
  90. }
  91. if ((groupName is null) || !_groups.TryGetValue(groupName, out Group group) || !group.EnableDns64)
  92. return response;
  93. List<DnsResourceRecord> newAnswer = new List<DnsResourceRecord>(response.Answer.Count);
  94. bool synthesizeAAAA = true;
  95. if (group.ExcludedIpv6.Length == 0)
  96. {
  97. //no exclusions configured
  98. foreach (DnsResourceRecord answer in response.Answer)
  99. {
  100. newAnswer.Add(answer);
  101. if (answer.Type == DnsResourceRecordType.AAAA)
  102. synthesizeAAAA = false; //found an AAAA record so no need to synthesize AAAA
  103. }
  104. }
  105. else
  106. {
  107. //check for exclusions
  108. foreach (DnsResourceRecord answer in response.Answer)
  109. {
  110. if (answer.Type != DnsResourceRecordType.AAAA)
  111. {
  112. //keep non-AAAA record, most probably a CNAME record, in answer list
  113. newAnswer.Add(answer);
  114. continue;
  115. }
  116. IPAddress ipv6Address = (answer.RDATA as DnsAAAARecordData).Address;
  117. foreach (NetworkAddress excludedIpv6 in group.ExcludedIpv6)
  118. {
  119. if (!excludedIpv6.Contains(ipv6Address))
  120. {
  121. //found non-excluded AAAA record so no need to synthesize AAAA
  122. newAnswer.Add(answer);
  123. synthesizeAAAA = false;
  124. }
  125. }
  126. }
  127. }
  128. if (!synthesizeAAAA)
  129. return new DnsDatagram(response.Identifier, true, response.OPCODE, response.AuthoritativeAnswer, response.Truncation, response.RecursionDesired, response.RecursionAvailable, response.AuthenticData, response.CheckingDisabled, response.RCODE, response.Question, newAnswer, response.Authority, response.Additional) { Tag = response.Tag };
  130. DnsDatagram newResponse = await _dnsServer.DirectQueryAsync(new DnsQuestionRecord(question.Name, DnsResourceRecordType.A, DnsClass.IN), 2000);
  131. uint soaTtl;
  132. {
  133. DnsResourceRecord soa = response.FindFirstAuthorityRecord();
  134. if ((soa is not null) && (soa.Type == DnsResourceRecordType.SOA))
  135. soaTtl = soa.TTL;
  136. else
  137. soaTtl = 600;
  138. }
  139. foreach (DnsResourceRecord answer in newResponse.Answer)
  140. {
  141. if (answer.Type != DnsResourceRecordType.A)
  142. continue;
  143. IPAddress ipv4Address = (answer.RDATA as DnsARecordData).Address;
  144. NetworkAddress ipv4Network = null;
  145. NetworkAddress dns64Prefix = null;
  146. foreach (KeyValuePair<NetworkAddress, NetworkAddress> dns64PrefixEntry in group.Dns64PrefixMap)
  147. {
  148. if (dns64PrefixEntry.Key.Contains(ipv4Address) && ((ipv4Network is null) || (dns64PrefixEntry.Key.PrefixLength > ipv4Network.PrefixLength)))
  149. {
  150. ipv4Network = dns64PrefixEntry.Key;
  151. dns64Prefix = dns64PrefixEntry.Value;
  152. }
  153. }
  154. if (dns64Prefix is null)
  155. continue;
  156. IPAddress ipv6Address = ipv4Address.MapToIPv6(dns64Prefix);
  157. newAnswer.Add(new DnsResourceRecord(answer.Name, DnsResourceRecordType.AAAA, answer.Class, Math.Min(answer.TTL, soaTtl), new DnsAAAARecordData(ipv6Address)));
  158. }
  159. return new DnsDatagram(response.Identifier, true, response.OPCODE, response.AuthoritativeAnswer, response.Truncation, response.RecursionDesired, response.RecursionAvailable, response.AuthenticData, response.CheckingDisabled, newResponse.RCODE, response.Question, newAnswer, newResponse.Authority, newResponse.Additional) { Tag = response.Tag };
  160. }
  161. public Task<DnsDatagram> ProcessRequestAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed)
  162. {
  163. if (!_enableDns64)
  164. return Task.FromResult<DnsDatagram>(null);
  165. if (request.DnssecOk)
  166. return Task.FromResult<DnsDatagram>(null);
  167. DnsQuestionRecord question = request.Question[0];
  168. if ((question.Type != DnsResourceRecordType.PTR) || !question.Name.EndsWith(".ip6.arpa", StringComparison.OrdinalIgnoreCase))
  169. return Task.FromResult<DnsDatagram>(null);
  170. IPAddress remoteIP = remoteEP.Address;
  171. NetworkAddress network = null;
  172. string groupName = null;
  173. foreach (KeyValuePair<NetworkAddress, string> entry in _networkGroupMap)
  174. {
  175. if (entry.Key.Contains(remoteIP) && ((network is null) || (entry.Key.PrefixLength > network.PrefixLength)))
  176. {
  177. network = entry.Key;
  178. groupName = entry.Value;
  179. }
  180. }
  181. if ((groupName is null) || !_groups.TryGetValue(groupName, out Group group) || !group.EnableDns64)
  182. return Task.FromResult<DnsDatagram>(null);
  183. IPAddress ipv6Address = IPAddressExtensions.ParseReverseDomain(question.Name);
  184. if (ipv6Address.AddressFamily != AddressFamily.InterNetworkV6)
  185. return Task.FromResult<DnsDatagram>(null);
  186. NetworkAddress dns64Prefix = null;
  187. foreach (KeyValuePair<NetworkAddress, NetworkAddress> dns64PrefixEntry in group.Dns64PrefixMap)
  188. {
  189. if ((dns64PrefixEntry.Value is not null) && dns64PrefixEntry.Value.Contains(ipv6Address))
  190. {
  191. dns64Prefix = dns64PrefixEntry.Value;
  192. break;
  193. }
  194. }
  195. if (dns64Prefix is null)
  196. return Task.FromResult<DnsDatagram>(null);
  197. IPAddress ipv4Address = ipv6Address.MapToIPv4(dns64Prefix.PrefixLength);
  198. IReadOnlyList<DnsResourceRecord> answer = new DnsResourceRecord[] { new DnsResourceRecord(question.Name, DnsResourceRecordType.CNAME, question.Class, 600, new DnsCNAMERecordData(ipv4Address.GetReverseDomain())) };
  199. return Task.FromResult(new DnsDatagram(request.Identifier, true, request.OPCODE, true, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.NoError, request.Question, answer));
  200. }
  201. #endregion
  202. #region properties
  203. public string Description
  204. { get { return "Enables DNS64 function for both authoritative and recursive resolver responses for use by IPv6 only clients."; } }
  205. #endregion
  206. class Group
  207. {
  208. #region variables
  209. readonly string _name;
  210. readonly bool _enableDns64;
  211. readonly Dictionary<NetworkAddress, NetworkAddress> _dns64PrefixMap;
  212. readonly NetworkAddress[] _excludedIpv6;
  213. #endregion
  214. #region constructor
  215. public Group(JsonElement jsonGroup)
  216. {
  217. _name = jsonGroup.GetProperty("name").GetString();
  218. _enableDns64 = jsonGroup.GetProperty("enableDns64").GetBoolean();
  219. _dns64PrefixMap = jsonGroup.ReadObjectAsMap("dns64PrefixMap", delegate (string strNetwork, JsonElement jsonDns64Prefix)
  220. {
  221. string strDns64Prefix = jsonDns64Prefix.GetString();
  222. NetworkAddress network = NetworkAddress.Parse(strNetwork);
  223. NetworkAddress dns64Prefix = null;
  224. if (strDns64Prefix is not null)
  225. {
  226. dns64Prefix = NetworkAddress.Parse(strDns64Prefix);
  227. switch (dns64Prefix.PrefixLength)
  228. {
  229. case 32:
  230. case 40:
  231. case 48:
  232. case 56:
  233. case 64:
  234. case 96:
  235. break;
  236. default:
  237. throw new NotSupportedException("DNS64 prefix can have only the following prefixes: 32, 40, 48, 56, 64, or 96.");
  238. }
  239. }
  240. return new Tuple<NetworkAddress, NetworkAddress>(network, dns64Prefix);
  241. });
  242. _excludedIpv6 = jsonGroup.ReadArray("excludedIpv6", delegate (string strNetworkAddress)
  243. {
  244. NetworkAddress networkAddress = NetworkAddress.Parse(strNetworkAddress);
  245. if (networkAddress.Address.AddressFamily != AddressFamily.InterNetworkV6)
  246. throw new InvalidOperationException("An IPv6 network address is expected for 'excludedIpv6' array.");
  247. return networkAddress;
  248. });
  249. }
  250. #endregion
  251. #region properties
  252. public string Name
  253. { get { return _name; } }
  254. public bool EnableDns64
  255. { get { return _enableDns64; } }
  256. public Dictionary<NetworkAddress, NetworkAddress> Dns64PrefixMap
  257. { get { return _dns64PrefixMap; } }
  258. public NetworkAddress[] ExcludedIpv6
  259. { get { return _excludedIpv6; } }
  260. #endregion
  261. }
  262. }
  263. }