App.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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.Text.Json;
  20. using System.Threading.Tasks;
  21. using TechnitiumLibrary;
  22. using TechnitiumLibrary.Net.Dns;
  23. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  24. namespace ZoneAlias
  25. {
  26. public sealed class App : IDnsApplication, IDnsAuthoritativeRequestHandler
  27. {
  28. #region variables
  29. IDnsServer _dnsServer;
  30. bool _enableAliasing;
  31. Dictionary<string, string> _aliases;
  32. #endregion
  33. #region IDisposable
  34. public void Dispose()
  35. {
  36. //do nothing
  37. }
  38. #endregion
  39. #region private
  40. private static string GetParentZone(string domain)
  41. {
  42. int i = domain.IndexOf('.');
  43. if (i > -1)
  44. return domain.Substring(i + 1);
  45. //dont return root zone
  46. return null;
  47. }
  48. private bool IsZoneAlias(string domain, out string zone, out string alias)
  49. {
  50. domain = domain.ToLowerInvariant();
  51. do
  52. {
  53. if (_aliases.TryGetValue(domain, out zone))
  54. {
  55. //found alias
  56. alias = domain;
  57. return true;
  58. }
  59. domain = GetParentZone(domain);
  60. }
  61. while (domain is not null);
  62. alias = null;
  63. return false;
  64. }
  65. private static IReadOnlyList<DnsResourceRecord> ConvertRecords(IReadOnlyList<DnsResourceRecord> records, string zone, string alias)
  66. {
  67. if (records.Count == 0)
  68. return records;
  69. DnsResourceRecord[] newRecords = new DnsResourceRecord[records.Count];
  70. int j;
  71. for (int i = 0; i < records.Count; i++)
  72. {
  73. DnsResourceRecord record = records[i];
  74. j = record.Name.LastIndexOf(zone, StringComparison.OrdinalIgnoreCase);
  75. if (j == 0)
  76. newRecords[i] = new DnsResourceRecord(alias, record.Type, record.Class, record.TTL, record.RDATA);
  77. else if (j > 0)
  78. newRecords[i] = new DnsResourceRecord(string.Concat(record.Name.AsSpan(0, j), alias), record.Type, record.Class, record.TTL, record.RDATA);
  79. else
  80. newRecords[i] = record;
  81. }
  82. return newRecords;
  83. }
  84. #endregion
  85. #region public
  86. public Task InitializeAsync(IDnsServer dnsServer, string config)
  87. {
  88. _dnsServer = dnsServer;
  89. using JsonDocument jsonDocument = JsonDocument.Parse(config);
  90. JsonElement jsonConfig = jsonDocument.RootElement;
  91. _enableAliasing = jsonConfig.GetPropertyValue("enableAliasing", true);
  92. if (jsonConfig.TryGetProperty("zoneAliases", out JsonElement jsonZoneAliases))
  93. {
  94. Dictionary<string, string> aliases = new Dictionary<string, string>();
  95. foreach (JsonProperty jsonZoneAlias in jsonZoneAliases.EnumerateObject())
  96. {
  97. string zone = jsonZoneAlias.Name.ToLowerInvariant();
  98. foreach (JsonElement jsonAlias in jsonZoneAlias.Value.EnumerateArray())
  99. aliases.Add(jsonAlias.GetString().ToLowerInvariant(), zone);
  100. }
  101. aliases.TrimExcess();
  102. _aliases = aliases;
  103. }
  104. else
  105. {
  106. _aliases = null;
  107. }
  108. return Task.CompletedTask;
  109. }
  110. public async Task<DnsDatagram> ProcessRequestAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed)
  111. {
  112. if (!_enableAliasing || (_aliases is null))
  113. return null;
  114. DnsQuestionRecord question = request.Question[0];
  115. string qname = question.Name;
  116. if (!IsZoneAlias(qname, out string zone, out string alias))
  117. return null;
  118. string newQname;
  119. int i = qname.LastIndexOf(alias, StringComparison.OrdinalIgnoreCase);
  120. if (i == 0)
  121. newQname = zone;
  122. else if (i > 0)
  123. newQname = string.Concat(qname.AsSpan(0, i), zone);
  124. else
  125. return null;
  126. DnsQuestionRecord newQuestion = new DnsQuestionRecord(newQname, question.Type, question.Class);
  127. try
  128. {
  129. DnsDatagram response = await _dnsServer.DirectQueryAsync(newQuestion);
  130. IReadOnlyList<DnsResourceRecord> newAnswer = ConvertRecords(response.Answer, zone, alias);
  131. IReadOnlyList<DnsResourceRecord> newAuthority = ConvertRecords(response.Authority, zone, alias);
  132. IReadOnlyList<DnsResourceRecord> newAdditional = ConvertRecords(response.Additional, zone, alias);
  133. return new DnsDatagram(request.Identifier, true, request.OPCODE, response.AuthoritativeAnswer, response.Truncation, request.RecursionDesired, isRecursionAllowed, false, false, response.RCODE, request.Question, newAnswer, newAuthority, newAdditional) { Tag = response.Tag };
  134. }
  135. catch (TimeoutException)
  136. { }
  137. catch (Exception ex)
  138. {
  139. _dnsServer.WriteLog(ex);
  140. }
  141. return new DnsDatagram(request.Identifier, true, request.OPCODE, false, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.ServerFailure, request.Question);
  142. }
  143. #endregion
  144. #region properties
  145. public string Description
  146. { get { return "Allows configuring aliases for any zone (internal or external) such that they all return the same set of records."; } }
  147. #endregion
  148. }
  149. }