App.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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.Text;
  21. using System.Text.Json;
  22. using System.Threading.Tasks;
  23. using TechnitiumLibrary;
  24. using TechnitiumLibrary.Net.Dns;
  25. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  26. namespace DefaultRecords
  27. {
  28. public sealed class App : IDnsApplication, IDnsPostProcessor
  29. {
  30. #region variables
  31. IDnsServer _dnsServer;
  32. bool _enableDefaultRecords;
  33. uint _defaultTtl;
  34. Dictionary<string, string[]> _zoneSetMap;
  35. Dictionary<string, Set> _sets;
  36. #endregion
  37. #region IDisposable
  38. public void Dispose()
  39. {
  40. //do nothing
  41. }
  42. #endregion
  43. #region private
  44. private static string GetParentZone(string domain)
  45. {
  46. int i = domain.IndexOf('.');
  47. if (i > -1)
  48. return domain.Substring(i + 1);
  49. //dont return root zone
  50. return null;
  51. }
  52. private bool TryGetMappedSets(string domain, out string zone, out string[] setNames)
  53. {
  54. domain = domain.ToLowerInvariant();
  55. string parent;
  56. do
  57. {
  58. if (_zoneSetMap.TryGetValue(domain, out setNames))
  59. {
  60. zone = domain;
  61. return true;
  62. }
  63. parent = GetParentZone(domain);
  64. if (parent is null)
  65. {
  66. if (_zoneSetMap.TryGetValue("*", out setNames))
  67. {
  68. zone = "*";
  69. return true;
  70. }
  71. break;
  72. }
  73. domain = "*." + parent;
  74. if (_zoneSetMap.TryGetValue(domain, out setNames))
  75. {
  76. zone = domain;
  77. return true;
  78. }
  79. domain = parent;
  80. }
  81. while (true);
  82. zone = null;
  83. return false;
  84. }
  85. #endregion
  86. #region public
  87. public Task InitializeAsync(IDnsServer dnsServer, string config)
  88. {
  89. _dnsServer = dnsServer;
  90. using JsonDocument jsonDocument = JsonDocument.Parse(config);
  91. JsonElement jsonConfig = jsonDocument.RootElement;
  92. _enableDefaultRecords = jsonConfig.GetProperty("enableDefaultRecords").GetBoolean();
  93. _defaultTtl = jsonConfig.GetPropertyValue("defaultTtl", 3600u);
  94. _zoneSetMap = jsonConfig.ReadObjectAsMap("zoneSetMap", delegate (string zone, JsonElement jsonSets)
  95. {
  96. string[] sets = jsonSets.GetArray();
  97. return new Tuple<string, string[]>(zone.ToLowerInvariant(), sets);
  98. });
  99. _sets = jsonConfig.ReadArrayAsMap("sets", delegate (JsonElement jsonSet)
  100. {
  101. Set set = new Set(jsonSet);
  102. return new Tuple<string, Set>(set.Name, set);
  103. });
  104. return Task.CompletedTask;
  105. }
  106. public async Task<DnsDatagram> PostProcessAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, DnsDatagram response)
  107. {
  108. if (!_enableDefaultRecords)
  109. return response;
  110. if (!response.AuthoritativeAnswer || (response.OPCODE != DnsOpcode.StandardQuery))
  111. return response;
  112. switch (response.RCODE)
  113. {
  114. case DnsResponseCode.NoError:
  115. case DnsResponseCode.NxDomain:
  116. break;
  117. default:
  118. return response;
  119. }
  120. DnsQuestionRecord question = request.Question[0];
  121. if (!TryGetMappedSets(question.Name, out string zone, out string[] setNames))
  122. return response;
  123. if (zone.StartsWith('*'))
  124. {
  125. DnsDatagram soaResponse = await _dnsServer.DirectQueryAsync(new DnsQuestionRecord(question.Name, DnsResourceRecordType.SOA, DnsClass.IN));
  126. if (soaResponse is null)
  127. return response;
  128. if ((soaResponse.Answer.Count > 0) && (soaResponse.Answer[soaResponse.Answer.Count - 1].Type == DnsResourceRecordType.SOA))
  129. zone = soaResponse.Answer[soaResponse.Answer.Count - 1].Name;
  130. else if ((soaResponse.Authority.Count > 0) && (soaResponse.Authority[0].Type == DnsResourceRecordType.SOA))
  131. zone = soaResponse.Authority[0].Name;
  132. else
  133. return response;
  134. }
  135. StringBuilder sb = new StringBuilder();
  136. foreach (string setName in setNames)
  137. {
  138. if (_sets.TryGetValue(setName, out Set set) && set.Enable)
  139. {
  140. foreach (string record in set.Records)
  141. sb.AppendLine(record);
  142. }
  143. }
  144. if (sb.Length == 0)
  145. return response;
  146. StringReader sR = new StringReader(sb.ToString());
  147. List<DnsResourceRecord> records = ZoneFile.ReadZoneFileFromAsync(sR, zone, _defaultTtl).Sync();
  148. List<DnsResourceRecord> newAnswer = new List<DnsResourceRecord>(response.Answer.Count + records.Count);
  149. string qname = question.Name;
  150. if (response.Answer.Count > 0)
  151. {
  152. newAnswer.AddRange(response.Answer);
  153. DnsResourceRecord lastRR = response.Answer[response.Answer.Count - 1];
  154. if (lastRR.Type == DnsResourceRecordType.CNAME)
  155. qname = (lastRR.RDATA as DnsCNAMERecordData).Domain;
  156. }
  157. foreach (DnsResourceRecord record in records)
  158. {
  159. if (record.Class != question.Class)
  160. continue;
  161. if ((record.Type != question.Type) && (record.Type != DnsResourceRecordType.CNAME))
  162. continue;
  163. if (!record.Name.Equals(qname, StringComparison.OrdinalIgnoreCase))
  164. continue;
  165. newAnswer.Add(record);
  166. if (record.Type == DnsResourceRecordType.CNAME)
  167. qname = (record.RDATA as DnsCNAMERecordData).Domain;
  168. }
  169. if (newAnswer.Count == response.Answer.Count)
  170. return response;
  171. return 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 };
  172. }
  173. #endregion
  174. #region properties
  175. public string Description
  176. { get { return "Enables default records for configured local zones."; } }
  177. #endregion
  178. class Set
  179. {
  180. #region variables
  181. readonly string _name;
  182. readonly bool _enable;
  183. readonly string[] _records;
  184. #endregion
  185. #region constructor
  186. public Set(JsonElement jsonSet)
  187. {
  188. _name = jsonSet.GetProperty("name").GetString();
  189. _enable = jsonSet.GetProperty("enable").GetBoolean();
  190. _records = jsonSet.ReadArray("records");
  191. }
  192. #endregion
  193. #region properties
  194. public string Name
  195. { get { return _name; } }
  196. public bool Enable
  197. { get { return _enable; } }
  198. public string[] Records
  199. { get { return _records; } }
  200. #endregion
  201. }
  202. }
  203. }