App.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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.Collections.Generic;
  17. using System.IO;
  18. using System.Net;
  19. using System.Text.Json;
  20. using System.Threading.Tasks;
  21. using TechnitiumLibrary;
  22. using TechnitiumLibrary.Net;
  23. using TechnitiumLibrary.Net.Dns;
  24. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  25. namespace DnsRebindingProtection
  26. {
  27. public sealed class App : IDnsApplication, IDnsPostProcessor
  28. {
  29. #region variables
  30. bool _enableProtection;
  31. NetworkAddress[] _bypassNetworks;
  32. HashSet<NetworkAddress> _privateNetworks;
  33. HashSet<string> _privateDomains;
  34. #endregion
  35. #region IDisposable
  36. public void Dispose()
  37. {
  38. // Nothing to dispose of.
  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[(i + 1)..];
  47. //dont return root zone
  48. return null;
  49. }
  50. private bool IsPrivateDomain(string domain)
  51. {
  52. domain = domain.ToLowerInvariant();
  53. do
  54. {
  55. if (_privateDomains.Contains(domain))
  56. return true;
  57. domain = GetParentZone(domain);
  58. }
  59. while (domain is not null);
  60. return false;
  61. }
  62. private bool IsRebindingAttempt(DnsResourceRecord record)
  63. {
  64. IPAddress address;
  65. switch (record.Type)
  66. {
  67. case DnsResourceRecordType.A:
  68. if (IsPrivateDomain(record.Name))
  69. return false;
  70. address = (record.RDATA as DnsARecordData).Address;
  71. break;
  72. case DnsResourceRecordType.AAAA:
  73. if (IsPrivateDomain(record.Name))
  74. return false;
  75. address = (record.RDATA as DnsAAAARecordData).Address;
  76. break;
  77. default:
  78. return false;
  79. }
  80. foreach (NetworkAddress networkAddress in _privateNetworks)
  81. {
  82. if (networkAddress.Contains(address))
  83. return true;
  84. }
  85. return false;
  86. }
  87. private bool TryDetectRebinding(IReadOnlyList<DnsResourceRecord> answer, out List<DnsResourceRecord> protectedAnswer)
  88. {
  89. for (int i = 0; i < answer.Count; i++)
  90. {
  91. DnsResourceRecord record = answer[i];
  92. if (IsRebindingAttempt(record))
  93. {
  94. //rebinding attempt detected!
  95. //prepare protected answer
  96. protectedAnswer = new List<DnsResourceRecord>(answer.Count);
  97. //copy passed records
  98. for (int j = 0; j < i; j++)
  99. protectedAnswer.Add(answer[j]);
  100. //copy remaining records with check
  101. for (int j = i + 1; j < answer.Count; j++)
  102. {
  103. record = answer[j];
  104. if (!IsRebindingAttempt(record))
  105. protectedAnswer.Add(record);
  106. }
  107. return true;
  108. }
  109. }
  110. protectedAnswer = null;
  111. return false;
  112. }
  113. #endregion
  114. #region public
  115. public async Task InitializeAsync(IDnsServer dnsServer, string config)
  116. {
  117. using JsonDocument jsonDocument = JsonDocument.Parse(config);
  118. JsonElement jsonConfig = jsonDocument.RootElement;
  119. _enableProtection = jsonConfig.GetPropertyValue("enableProtection", true);
  120. _privateNetworks = new HashSet<NetworkAddress>(jsonConfig.ReadArray("privateNetworks", NetworkAddress.Parse));
  121. _privateDomains = new HashSet<string>(jsonConfig.ReadArray("privateDomains"));
  122. if (jsonConfig.TryReadArray("bypassNetworks", NetworkAddress.Parse, out NetworkAddress[] bypassNetworks))
  123. {
  124. _bypassNetworks = bypassNetworks;
  125. }
  126. else
  127. {
  128. _bypassNetworks = [];
  129. //update config for new feature
  130. config = config.Replace("\"privateNetworks\"", "\"bypassNetworks\": [\r\n ],\r\n \"privateNetworks\"");
  131. await File.WriteAllTextAsync(Path.Combine(dnsServer.ApplicationFolder, "dnsApp.config"), config);
  132. }
  133. }
  134. public Task<DnsDatagram> PostProcessAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, DnsDatagram response)
  135. {
  136. // Do not filter authoritative responses. Because in this case any rebinding is intentional.
  137. if (!_enableProtection || response.AuthoritativeAnswer)
  138. return Task.FromResult(response);
  139. IPAddress remoteIP = remoteEP.Address;
  140. foreach (NetworkAddress network in _bypassNetworks)
  141. {
  142. if (network.Contains(remoteIP))
  143. return Task.FromResult(response);
  144. }
  145. if (TryDetectRebinding(response.Answer, out List<DnsResourceRecord> protectedAnswer))
  146. return Task.FromResult(response.Clone(protectedAnswer));
  147. return Task.FromResult(response);
  148. }
  149. #endregion
  150. #region properties
  151. public string Description
  152. { get { return "Protects from DNS rebinding attacks using configured private domains and networks."; } }
  153. #endregion
  154. }
  155. }