BlockedZoneManager.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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.Dns.Zones;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Text;
  20. using System.Threading;
  21. using TechnitiumLibrary.IO;
  22. using TechnitiumLibrary.Net.Dns;
  23. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  24. namespace DnsServerCore.Dns.ZoneManagers
  25. {
  26. public sealed class BlockedZoneManager
  27. {
  28. #region variables
  29. readonly DnsServer _dnsServer;
  30. readonly AuthZoneManager _zoneManager;
  31. DnsSOARecordData _soaRecord;
  32. DnsNSRecordData _nsRecord;
  33. readonly object _saveLock = new object();
  34. bool _pendingSave;
  35. readonly Timer _saveTimer;
  36. const int SAVE_TIMER_INITIAL_INTERVAL = 10000;
  37. #endregion
  38. #region constructor
  39. public BlockedZoneManager(DnsServer dnsServer)
  40. {
  41. _dnsServer = dnsServer;
  42. _zoneManager = new AuthZoneManager(_dnsServer);
  43. UpdateServerDomain();
  44. _saveTimer = new Timer(delegate (object state)
  45. {
  46. lock (_saveLock)
  47. {
  48. if (_pendingSave)
  49. {
  50. try
  51. {
  52. SaveZoneFileInternal();
  53. _pendingSave = false;
  54. }
  55. catch (Exception ex)
  56. {
  57. _dnsServer.LogManager.Write(ex);
  58. //set timer to retry again
  59. _saveTimer.Change(SAVE_TIMER_INITIAL_INTERVAL, Timeout.Infinite);
  60. }
  61. }
  62. }
  63. });
  64. }
  65. #endregion
  66. #region IDisposable
  67. bool _disposed;
  68. public void Dispose()
  69. {
  70. if (_disposed)
  71. return;
  72. lock (_saveLock)
  73. {
  74. _saveTimer?.Dispose();
  75. if (_pendingSave)
  76. {
  77. try
  78. {
  79. SaveZoneFileInternal();
  80. }
  81. catch (Exception ex)
  82. {
  83. _dnsServer.LogManager.Write(ex);
  84. }
  85. finally
  86. {
  87. _pendingSave = false;
  88. }
  89. }
  90. }
  91. _disposed = true;
  92. }
  93. #endregion
  94. #region private
  95. internal void UpdateServerDomain()
  96. {
  97. _soaRecord = new DnsSOARecordData(_dnsServer.ServerDomain, _dnsServer.ResponsiblePerson.Address, 1, 14400, 3600, 604800, _dnsServer.BlockingAnswerTtl);
  98. _nsRecord = new DnsNSRecordData(_dnsServer.ServerDomain);
  99. _zoneManager.UpdateServerDomain(true);
  100. }
  101. private void SaveZoneFileInternal()
  102. {
  103. IReadOnlyList<AuthZoneInfo> blockedZones = _dnsServer.BlockedZoneManager.GetAllZones();
  104. string blockedZoneFile = Path.Combine(_dnsServer.ConfigFolder, "blocked.config");
  105. using (FileStream fS = new FileStream(blockedZoneFile, FileMode.Create, FileAccess.Write))
  106. {
  107. BinaryWriter bW = new BinaryWriter(fS);
  108. bW.Write(Encoding.ASCII.GetBytes("BZ")); //format
  109. bW.Write((byte)1); //version
  110. bW.Write(blockedZones.Count);
  111. foreach (AuthZoneInfo zone in blockedZones)
  112. bW.WriteShortString(zone.Name);
  113. }
  114. _dnsServer.LogManager?.Write("DNS Server blocked zone file was saved: " + blockedZoneFile);
  115. }
  116. #endregion
  117. #region public
  118. public void LoadBlockedZoneFile()
  119. {
  120. _zoneManager.Flush();
  121. string blockedZoneFile = Path.Combine(_dnsServer.ConfigFolder, "blocked.config");
  122. try
  123. {
  124. string oldCustomBlockedZoneFile = Path.Combine(_dnsServer.ConfigFolder, "custom-blocked.config");
  125. if (File.Exists(oldCustomBlockedZoneFile))
  126. {
  127. if (File.Exists(blockedZoneFile))
  128. File.Delete(blockedZoneFile);
  129. File.Move(oldCustomBlockedZoneFile, blockedZoneFile);
  130. }
  131. }
  132. catch (Exception ex)
  133. {
  134. _dnsServer.LogManager?.Write(ex);
  135. }
  136. try
  137. {
  138. _dnsServer.LogManager?.Write("DNS Server is loading blocked zone file: " + blockedZoneFile);
  139. using (FileStream fS = new FileStream(blockedZoneFile, FileMode.Open, FileAccess.Read))
  140. {
  141. BinaryReader bR = new BinaryReader(fS);
  142. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "BZ") //format
  143. throw new InvalidDataException("DnsServer blocked zone file format is invalid.");
  144. byte version = bR.ReadByte();
  145. switch (version)
  146. {
  147. case 1:
  148. int length = bR.ReadInt32();
  149. int i = 0;
  150. _zoneManager.LoadSpecialPrimaryZones(delegate ()
  151. {
  152. if (i++ < length)
  153. return bR.ReadShortString();
  154. return null;
  155. }, _soaRecord, _nsRecord);
  156. break;
  157. default:
  158. throw new InvalidDataException("DnsServer blocked zone file version not supported.");
  159. }
  160. }
  161. _dnsServer.LogManager?.Write("DNS Server blocked zone file was loaded: " + blockedZoneFile);
  162. }
  163. catch (FileNotFoundException)
  164. { }
  165. catch (Exception ex)
  166. {
  167. _dnsServer.LogManager?.Write("DNS Server encountered an error while loading blocked zone file: " + blockedZoneFile + "\r\n" + ex.ToString());
  168. }
  169. }
  170. public void ImportZones(string[] domains)
  171. {
  172. _zoneManager.LoadSpecialPrimaryZones(domains, _soaRecord, _nsRecord);
  173. }
  174. public bool BlockZone(string domain)
  175. {
  176. if (_zoneManager.CreateSpecialPrimaryZone(domain, _soaRecord, _nsRecord) != null)
  177. return true;
  178. return false;
  179. }
  180. public bool DeleteZone(string domain)
  181. {
  182. if (_zoneManager.DeleteZone(domain))
  183. return true;
  184. return false;
  185. }
  186. public void Flush()
  187. {
  188. _zoneManager.Flush();
  189. }
  190. public IReadOnlyList<AuthZoneInfo> GetAllZones()
  191. {
  192. return _zoneManager.GetAllZones();
  193. }
  194. public void ListAllRecords(string domain, List<DnsResourceRecord> records)
  195. {
  196. _zoneManager.ListAllRecords(domain, domain, records);
  197. }
  198. public void ListSubDomains(string domain, List<string> subDomains)
  199. {
  200. _zoneManager.ListSubDomains(domain, subDomains);
  201. }
  202. public void SaveZoneFile()
  203. {
  204. lock (_saveLock)
  205. {
  206. if (_pendingSave)
  207. return;
  208. _pendingSave = true;
  209. _saveTimer.Change(SAVE_TIMER_INITIAL_INTERVAL, Timeout.Infinite);
  210. }
  211. }
  212. public DnsDatagram Query(DnsDatagram request)
  213. {
  214. if (_zoneManager.TotalZones < 1)
  215. return null;
  216. return _zoneManager.Query(request, false);
  217. }
  218. #endregion
  219. #region properties
  220. internal DnsSOARecordData DnsSOARecord
  221. { get { return _soaRecord; } }
  222. public int TotalZonesBlocked
  223. { get { return _zoneManager.TotalZones; } }
  224. #endregion
  225. }
  226. }