Address.cs 7.8 KB

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