App.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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.Dns;
  24. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  25. namespace NxDomainOverride
  26. {
  27. public sealed class App : IDnsApplication, IDnsPostProcessor
  28. {
  29. #region variables
  30. bool _enableOverride;
  31. uint _defaultTtl;
  32. Dictionary<string, string[]> _domainSetMap;
  33. Dictionary<string, Set> _sets;
  34. #endregion
  35. #region IDisposable
  36. public void Dispose()
  37. {
  38. //do nothing
  39. }
  40. #endregion
  41. #region private
  42. private static string GetParentZone(string domain)
  43. {
  44. int i = domain.IndexOf('.');
  45. if (i > -1)
  46. return domain.Substring(i + 1);
  47. //dont return root zone
  48. return null;
  49. }
  50. private bool TryGetMappedSets(string domain, out string[] setNames)
  51. {
  52. domain = domain.ToLowerInvariant();
  53. string parent;
  54. do
  55. {
  56. if (_domainSetMap.TryGetValue(domain, out setNames))
  57. return true;
  58. parent = GetParentZone(domain);
  59. if (parent is null)
  60. {
  61. if (_domainSetMap.TryGetValue("*", out setNames))
  62. return true;
  63. break;
  64. }
  65. domain = "*." + parent;
  66. if (_domainSetMap.TryGetValue(domain, out setNames))
  67. return true;
  68. domain = parent;
  69. }
  70. while (true);
  71. return false;
  72. }
  73. #endregion
  74. #region public
  75. public Task InitializeAsync(IDnsServer dnsServer, string config)
  76. {
  77. using JsonDocument jsonDocument = JsonDocument.Parse(config);
  78. JsonElement jsonConfig = jsonDocument.RootElement;
  79. _enableOverride = jsonConfig.GetPropertyValue("enableOverride", true);
  80. _defaultTtl = jsonConfig.GetPropertyValue("defaultTtl", 300u);
  81. _domainSetMap = jsonConfig.ReadObjectAsMap("domainSetMap", delegate (string domain, JsonElement jsonSets)
  82. {
  83. string[] sets = jsonSets.GetArray();
  84. return new Tuple<string, string[]>(domain.ToLowerInvariant(), sets);
  85. });
  86. _sets = jsonConfig.ReadArrayAsMap("sets", delegate (JsonElement jsonSet)
  87. {
  88. Set set = new Set(jsonSet);
  89. return new Tuple<string, Set>(set.Name, set);
  90. });
  91. return Task.CompletedTask;
  92. }
  93. public Task<DnsDatagram> PostProcessAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, DnsDatagram response)
  94. {
  95. if (!_enableOverride)
  96. return Task.FromResult(response);
  97. if (response.DnssecOk)
  98. return Task.FromResult(response);
  99. if (response.OPCODE != DnsOpcode.StandardQuery)
  100. return Task.FromResult(response);
  101. if (response.RCODE != DnsResponseCode.NxDomain)
  102. return Task.FromResult(response);
  103. DnsQuestionRecord question = request.Question[0];
  104. switch (question.Type)
  105. {
  106. case DnsResourceRecordType.A:
  107. case DnsResourceRecordType.AAAA:
  108. break;
  109. default:
  110. //NO DATA response
  111. return Task.FromResult(new DnsDatagram(response.Identifier, true, response.OPCODE, response.AuthoritativeAnswer, response.Truncation, response.RecursionDesired, response.RecursionAvailable, response.AuthenticData, response.CheckingDisabled, DnsResponseCode.NoError, response.Question, response.Answer, response.Authority, response.Additional) { Tag = response.Tag });
  112. }
  113. string nxDomain = question.Name;
  114. foreach (DnsResourceRecord record in response.Answer)
  115. {
  116. if (record.Type == DnsResourceRecordType.CNAME)
  117. nxDomain = (record.RDATA as DnsCNAMERecordData).Domain;
  118. }
  119. if (!TryGetMappedSets(nxDomain, out string[] setNames))
  120. return Task.FromResult(response);
  121. List<DnsResourceRecord> newAnswer = new List<DnsResourceRecord>();
  122. newAnswer.AddRange(response.Answer);
  123. foreach (string setName in setNames)
  124. {
  125. if (_sets.TryGetValue(setName, out Set set))
  126. {
  127. switch (question.Type)
  128. {
  129. case DnsResourceRecordType.A:
  130. foreach (DnsResourceRecordData rdata in set.RecordDataAddresses)
  131. {
  132. if (rdata is DnsARecordData)
  133. newAnswer.Add(new DnsResourceRecord(nxDomain, DnsResourceRecordType.A, DnsClass.IN, _defaultTtl, rdata));
  134. }
  135. break;
  136. case DnsResourceRecordType.AAAA:
  137. foreach (DnsResourceRecordData rdata in set.RecordDataAddresses)
  138. {
  139. if (rdata is DnsAAAARecordData)
  140. newAnswer.Add(new DnsResourceRecord(nxDomain, DnsResourceRecordType.AAAA, DnsClass.IN, _defaultTtl, rdata));
  141. }
  142. break;
  143. default:
  144. throw new InvalidOperationException();
  145. }
  146. }
  147. }
  148. return Task.FromResult(new DnsDatagram(response.Identifier, true, response.OPCODE, response.AuthoritativeAnswer, response.Truncation, response.RecursionDesired, response.RecursionAvailable, response.AuthenticData, response.CheckingDisabled, DnsResponseCode.NoError, response.Question, newAnswer) { Tag = response.Tag });
  149. }
  150. #endregion
  151. #region properties
  152. public string Description
  153. { get { return "Overrides NX Domain response with custom A/AAAA record response for configured domain names."; } }
  154. #endregion
  155. class Set
  156. {
  157. #region variables
  158. readonly string _name;
  159. readonly DnsResourceRecordData[] _rdataAddresses;
  160. #endregion
  161. #region constructor
  162. public Set(JsonElement jsonSet)
  163. {
  164. _name = jsonSet.GetProperty("name").GetString();
  165. _rdataAddresses = jsonSet.ReadArray<DnsResourceRecordData>("addresses", delegate (string item)
  166. {
  167. IPAddress address = IPAddress.Parse(item);
  168. switch (address.AddressFamily)
  169. {
  170. case AddressFamily.InterNetwork:
  171. return new DnsARecordData(address);
  172. case AddressFamily.InterNetworkV6:
  173. return new DnsAAAARecordData(address);
  174. default:
  175. throw new NotSupportedException("Address family not supported: " + address.AddressFamily.ToString());
  176. }
  177. });
  178. }
  179. #endregion
  180. #region properties
  181. public string Name
  182. { get { return _name; } }
  183. public DnsResourceRecordData[] RecordDataAddresses
  184. { get { return _rdataAddresses; } }
  185. #endregion
  186. }
  187. }
  188. }