Address.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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 MaxMind.GeoIP2.Responses;
  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.EDnsOptions;
  25. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  26. namespace GeoCountry
  27. {
  28. public sealed class Address : IDnsApplication, IDnsAppRecordRequestHandler
  29. {
  30. #region variables
  31. IDnsServer _dnsServer;
  32. MaxMind _maxMind;
  33. #endregion
  34. #region IDisposable
  35. bool _disposed;
  36. private void Dispose(bool disposing)
  37. {
  38. if (_disposed)
  39. return;
  40. if (disposing)
  41. {
  42. if (_maxMind is not null)
  43. _maxMind.Dispose();
  44. }
  45. _disposed = true;
  46. }
  47. public void Dispose()
  48. {
  49. Dispose(true);
  50. }
  51. #endregion
  52. #region public
  53. public Task InitializeAsync(IDnsServer dnsServer, string config)
  54. {
  55. _dnsServer = dnsServer;
  56. _maxMind = MaxMind.Create(dnsServer);
  57. return Task.CompletedTask;
  58. }
  59. public Task<DnsDatagram> ProcessRequestAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, string zoneName, string appRecordName, uint appRecordTtl, string appRecordData)
  60. {
  61. DnsQuestionRecord question = request.Question[0];
  62. switch (question.Type)
  63. {
  64. case DnsResourceRecordType.A:
  65. case DnsResourceRecordType.AAAA:
  66. using (JsonDocument jsonDocument = JsonDocument.Parse(appRecordData))
  67. {
  68. JsonElement jsonAppRecordData = jsonDocument.RootElement;
  69. JsonElement jsonCountry = default;
  70. bool ecsUsed = false;
  71. EDnsClientSubnetOptionData requestECS = request.GetEDnsClientSubnetOption();
  72. if (requestECS is not null)
  73. {
  74. if (_maxMind.DatabaseReader.TryCountry(requestECS.Address, out CountryResponse csResponse))
  75. {
  76. ecsUsed = true;
  77. if (!jsonAppRecordData.TryGetProperty(csResponse.Country.IsoCode, out jsonCountry))
  78. jsonAppRecordData.TryGetProperty("default", out jsonCountry);
  79. }
  80. }
  81. if (jsonCountry.ValueKind == JsonValueKind.Undefined)
  82. {
  83. if (_maxMind.DatabaseReader.TryCountry(remoteEP.Address, out CountryResponse response))
  84. {
  85. if (!jsonAppRecordData.TryGetProperty(response.Country.IsoCode, out jsonCountry))
  86. jsonAppRecordData.TryGetProperty("default", out jsonCountry);
  87. }
  88. else
  89. {
  90. jsonAppRecordData.TryGetProperty("default", out jsonCountry);
  91. }
  92. if (jsonCountry.ValueKind == JsonValueKind.Undefined)
  93. return Task.FromResult<DnsDatagram>(null);
  94. }
  95. List<DnsResourceRecord> answers = new List<DnsResourceRecord>();
  96. switch (question.Type)
  97. {
  98. case DnsResourceRecordType.A:
  99. foreach (JsonElement jsonAddress in jsonCountry.EnumerateArray())
  100. {
  101. IPAddress address = IPAddress.Parse(jsonAddress.GetString());
  102. if (address.AddressFamily == AddressFamily.InterNetwork)
  103. answers.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.A, DnsClass.IN, appRecordTtl, new DnsARecordData(address)));
  104. }
  105. break;
  106. case DnsResourceRecordType.AAAA:
  107. foreach (JsonElement jsonAddress in jsonCountry.EnumerateArray())
  108. {
  109. IPAddress address = IPAddress.Parse(jsonAddress.GetString());
  110. if (address.AddressFamily == AddressFamily.InterNetworkV6)
  111. answers.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.AAAA, DnsClass.IN, appRecordTtl, new DnsAAAARecordData(address)));
  112. }
  113. break;
  114. }
  115. if (answers.Count == 0)
  116. return Task.FromResult<DnsDatagram>(null);
  117. if (answers.Count > 1)
  118. answers.Shuffle();
  119. EDnsOption[] options;
  120. if (requestECS is null)
  121. {
  122. options = null;
  123. }
  124. else
  125. {
  126. if (ecsUsed)
  127. options = EDnsClientSubnetOptionData.GetEDnsClientSubnetOption(requestECS.SourcePrefixLength, requestECS.SourcePrefixLength, requestECS.Address);
  128. else
  129. options = EDnsClientSubnetOptionData.GetEDnsClientSubnetOption(requestECS.SourcePrefixLength, 0, requestECS.Address);
  130. }
  131. return Task.FromResult(new DnsDatagram(request.Identifier, true, request.OPCODE, true, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.NoError, request.Question, answers, null, null, _dnsServer.UdpPayloadSize, EDnsHeaderFlags.None, options));
  132. }
  133. default:
  134. return Task.FromResult<DnsDatagram>(null);
  135. }
  136. }
  137. #endregion
  138. #region properties
  139. public string Description
  140. { get { return "Returns A or AAAA records based on the country the client queries from using MaxMind GeoIP2 Country database. Use the two-character ISO 3166-1 alpha code for the country."; } }
  141. public string ApplicationRecordDataTemplate
  142. {
  143. get
  144. {
  145. return @"{
  146. ""IN"": [
  147. ""1.1.1.1"",
  148. ""2.2.2.2""
  149. ],
  150. ""default"": [
  151. ""3.3.3.3""
  152. ]
  153. }";
  154. }
  155. }
  156. #endregion
  157. }
  158. }