App.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2023 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 class App : IDnsApplication, IDnsPostProcessor, IDnsAuthoritativeRequestHandler
  31. {
  32. #region variables
  33. IDnsServer _dnsServer;
  34. bool _enableDns64;
  35. IReadOnlyDictionary<NetworkAddress, string> _networkGroupMap;
  36. IReadOnlyDictionary<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. foreach (DnsResourceRecord answer in response.Answer)
  96. {
  97. if (answer.Type != DnsResourceRecordType.AAAA)
  98. {
  99. newAnswer.Add(answer);
  100. continue;
  101. }
  102. IPAddress ipv6Address = (answer.RDATA as DnsAAAARecordData).Address;
  103. foreach (NetworkAddress excludedIpv6 in group.ExcludedIpv6)
  104. {
  105. if (!excludedIpv6.Contains(ipv6Address))
  106. {
  107. //found non-excluded AAAA record so no need to synthesize AAAA
  108. newAnswer.Add(answer);
  109. synthesizeAAAA = false;
  110. }
  111. }
  112. }
  113. if (!synthesizeAAAA)
  114. 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 };
  115. DnsDatagram newResponse = await _dnsServer.DirectQueryAsync(new DnsQuestionRecord(question.Name, DnsResourceRecordType.A, DnsClass.IN), 2000);
  116. uint soaTtl;
  117. {
  118. DnsResourceRecord soa = response.FindFirstAuthorityRecord();
  119. if ((soa is not null) && (soa.Type == DnsResourceRecordType.SOA))
  120. soaTtl = soa.TTL;
  121. else
  122. soaTtl = 600;
  123. }
  124. foreach (DnsResourceRecord answer in newResponse.Answer)
  125. {
  126. if (answer.Type != DnsResourceRecordType.A)
  127. continue;
  128. IPAddress ipv4Address = (answer.RDATA as DnsARecordData).Address;
  129. NetworkAddress ipv4Network = null;
  130. NetworkAddress dns64Prefix = null;
  131. foreach (KeyValuePair<NetworkAddress, NetworkAddress> dns64PrefixEntry in group.Dns64PrefixMap)
  132. {
  133. if (dns64PrefixEntry.Key.Contains(ipv4Address) && ((ipv4Network is null) || (dns64PrefixEntry.Key.PrefixLength > ipv4Network.PrefixLength)))
  134. {
  135. ipv4Network = dns64PrefixEntry.Key;
  136. dns64Prefix = dns64PrefixEntry.Value;
  137. }
  138. }
  139. if (dns64Prefix is null)
  140. continue;
  141. IPAddress ipv6Address = ipv4Address.MapToIPv6(dns64Prefix);
  142. newAnswer.Add(new DnsResourceRecord(answer.Name, DnsResourceRecordType.AAAA, answer.Class, Math.Min(answer.TTL, soaTtl), new DnsAAAARecordData(ipv6Address)));
  143. }
  144. 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 };
  145. }
  146. public Task<DnsDatagram> ProcessRequestAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed)
  147. {
  148. if (!_enableDns64)
  149. return Task.FromResult<DnsDatagram>(null);
  150. if (request.DnssecOk)
  151. return Task.FromResult<DnsDatagram>(null);
  152. DnsQuestionRecord question = request.Question[0];
  153. if ((question.Type != DnsResourceRecordType.PTR) || !question.Name.EndsWith(".ip6.arpa", StringComparison.OrdinalIgnoreCase))
  154. return Task.FromResult<DnsDatagram>(null);
  155. IPAddress remoteIP = remoteEP.Address;
  156. NetworkAddress network = null;
  157. string groupName = null;
  158. foreach (KeyValuePair<NetworkAddress, string> entry in _networkGroupMap)
  159. {
  160. if (entry.Key.Contains(remoteIP) && ((network is null) || (entry.Key.PrefixLength > network.PrefixLength)))
  161. {
  162. network = entry.Key;
  163. groupName = entry.Value;
  164. }
  165. }
  166. if ((groupName is null) || !_groups.TryGetValue(groupName, out Group group) || !group.EnableDns64)
  167. return Task.FromResult<DnsDatagram>(null);
  168. IPAddress ipv6Address = IPAddressExtensions.ParseReverseDomain(question.Name);
  169. if (ipv6Address.AddressFamily != AddressFamily.InterNetworkV6)
  170. return Task.FromResult<DnsDatagram>(null);
  171. NetworkAddress dns64Prefix = null;
  172. foreach (KeyValuePair<NetworkAddress, NetworkAddress> dns64PrefixEntry in group.Dns64PrefixMap)
  173. {
  174. if ((dns64PrefixEntry.Value is not null) && dns64PrefixEntry.Value.Contains(ipv6Address))
  175. {
  176. dns64Prefix = dns64PrefixEntry.Value;
  177. break;
  178. }
  179. }
  180. if (dns64Prefix is null)
  181. return Task.FromResult<DnsDatagram>(null);
  182. IPAddress ipv4Address = ipv6Address.MapToIPv4(dns64Prefix.PrefixLength);
  183. IReadOnlyList<DnsResourceRecord> answer = new DnsResourceRecord[] { new DnsResourceRecord(question.Name, DnsResourceRecordType.CNAME, question.Class, 600, new DnsCNAMERecordData(ipv4Address.GetReverseDomain())) };
  184. return Task.FromResult(new DnsDatagram(request.Identifier, true, request.OPCODE, true, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.NoError, request.Question, answer));
  185. }
  186. #endregion
  187. #region properties
  188. public string Description
  189. { get { return "Enables DNS64 function for both authoritative and recursive resolver responses for use by IPv6 only clients."; } }
  190. #endregion
  191. class Group
  192. {
  193. #region variables
  194. readonly string _name;
  195. readonly bool _enableDns64;
  196. readonly IReadOnlyDictionary<NetworkAddress, NetworkAddress> _dns64PrefixMap;
  197. readonly IReadOnlyCollection<NetworkAddress> _excludedIpv6;
  198. #endregion
  199. #region constructor
  200. public Group(JsonElement jsonGroup)
  201. {
  202. _name = jsonGroup.GetProperty("name").GetString();
  203. _enableDns64 = jsonGroup.GetProperty("enableDns64").GetBoolean();
  204. _dns64PrefixMap = jsonGroup.ReadObjectAsMap("dns64PrefixMap", delegate (string strNetwork, JsonElement jsonDns64Prefix)
  205. {
  206. string strDns64Prefix = jsonDns64Prefix.GetString();
  207. NetworkAddress network = NetworkAddress.Parse(strNetwork);
  208. NetworkAddress dns64Prefix = null;
  209. if (strDns64Prefix is not null)
  210. {
  211. dns64Prefix = NetworkAddress.Parse(strDns64Prefix);
  212. switch (dns64Prefix.PrefixLength)
  213. {
  214. case 32:
  215. case 40:
  216. case 48:
  217. case 56:
  218. case 64:
  219. case 96:
  220. break;
  221. default:
  222. throw new NotSupportedException("DNS64 prefix can have only the following prefixes: 32, 40, 48, 56, 64, or 96.");
  223. }
  224. }
  225. return new Tuple<NetworkAddress, NetworkAddress>(network, dns64Prefix);
  226. });
  227. _excludedIpv6 = jsonGroup.ReadArray("excludedIpv6", delegate (string strNetworkAddress)
  228. {
  229. NetworkAddress networkAddress = NetworkAddress.Parse(strNetworkAddress);
  230. if (networkAddress.Address.AddressFamily != AddressFamily.InterNetworkV6)
  231. throw new InvalidOperationException("An IPv6 network address is expected for 'excludedIpv6' array.");
  232. return networkAddress;
  233. });
  234. }
  235. #endregion
  236. #region properties
  237. public string Name
  238. { get { return _name; } }
  239. public bool EnableDns64
  240. { get { return _enableDns64; } }
  241. public IReadOnlyDictionary<NetworkAddress, NetworkAddress> Dns64PrefixMap
  242. { get { return _dns64PrefixMap; } }
  243. public IReadOnlyCollection<NetworkAddress> ExcludedIpv6
  244. { get { return _excludedIpv6; } }
  245. #endregion
  246. }
  247. }
  248. }