WebServiceSettingsApi.cs 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922
  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.Auth;
  16. using DnsServerCore.Dns;
  17. using Microsoft.AspNetCore.Http;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.IO;
  21. using System.IO.Compression;
  22. using System.Linq;
  23. using System.Net;
  24. using System.Net.Sockets;
  25. using System.Security.Cryptography;
  26. using System.Text;
  27. using System.Text.Json;
  28. using System.Threading;
  29. using System.Threading.Tasks;
  30. using TechnitiumLibrary;
  31. using TechnitiumLibrary.Net;
  32. using TechnitiumLibrary.Net.Dns;
  33. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  34. using TechnitiumLibrary.Net.Proxy;
  35. namespace DnsServerCore
  36. {
  37. sealed class WebServiceSettingsApi : IDisposable
  38. {
  39. #region variables
  40. readonly static RandomNumberGenerator _rng = RandomNumberGenerator.Create();
  41. readonly DnsWebService _dnsWebService;
  42. Timer _blockListUpdateTimer;
  43. DateTime _blockListLastUpdatedOn;
  44. int _blockListUpdateIntervalHours = 24;
  45. const int BLOCK_LIST_UPDATE_TIMER_INITIAL_INTERVAL = 5000;
  46. const int BLOCK_LIST_UPDATE_TIMER_PERIODIC_INTERVAL = 900000;
  47. Timer _temporaryDisableBlockingTimer;
  48. DateTime _temporaryDisableBlockingTill;
  49. #endregion
  50. #region constructor
  51. public WebServiceSettingsApi(DnsWebService dnsWebService)
  52. {
  53. _dnsWebService = dnsWebService;
  54. }
  55. #endregion
  56. #region IDisposable
  57. bool _disposed;
  58. public void Dispose()
  59. {
  60. if (_disposed)
  61. return;
  62. if (_blockListUpdateTimer is not null)
  63. _blockListUpdateTimer.Dispose();
  64. if (_temporaryDisableBlockingTimer is not null)
  65. _temporaryDisableBlockingTimer.Dispose();
  66. _disposed = true;
  67. }
  68. #endregion
  69. #region block list
  70. private void ForceUpdateBlockLists()
  71. {
  72. Task.Run(async delegate ()
  73. {
  74. if (await _dnsWebService.DnsServer.BlockListZoneManager.UpdateBlockListsAsync())
  75. {
  76. //block lists were updated
  77. //save last updated on time
  78. _blockListLastUpdatedOn = DateTime.UtcNow;
  79. _dnsWebService.SaveConfigFile();
  80. }
  81. });
  82. }
  83. public void StartBlockListUpdateTimer()
  84. {
  85. if (_blockListUpdateTimer is null)
  86. {
  87. _blockListUpdateTimer = new Timer(async delegate (object state)
  88. {
  89. try
  90. {
  91. if (DateTime.UtcNow > _blockListLastUpdatedOn.AddHours(_blockListUpdateIntervalHours))
  92. {
  93. if (await _dnsWebService.DnsServer.BlockListZoneManager.UpdateBlockListsAsync())
  94. {
  95. //block lists were updated
  96. //save last updated on time
  97. _blockListLastUpdatedOn = DateTime.UtcNow;
  98. _dnsWebService.SaveConfigFile();
  99. }
  100. }
  101. }
  102. catch (Exception ex)
  103. {
  104. _dnsWebService._log.Write("DNS Server encountered an error while updating block lists.\r\n" + ex.ToString());
  105. }
  106. }, null, BLOCK_LIST_UPDATE_TIMER_INITIAL_INTERVAL, BLOCK_LIST_UPDATE_TIMER_PERIODIC_INTERVAL);
  107. }
  108. }
  109. public void StopBlockListUpdateTimer()
  110. {
  111. if (_blockListUpdateTimer is not null)
  112. {
  113. _blockListUpdateTimer.Dispose();
  114. _blockListUpdateTimer = null;
  115. }
  116. }
  117. public void StopTemporaryDisableBlockingTimer()
  118. {
  119. Timer temporaryDisableBlockingTimer = _temporaryDisableBlockingTimer;
  120. if (temporaryDisableBlockingTimer is not null)
  121. temporaryDisableBlockingTimer.Dispose();
  122. }
  123. #endregion
  124. #region private
  125. private void RestartService(bool restartDnsService, bool restartWebService)
  126. {
  127. if (restartDnsService)
  128. {
  129. _ = Task.Run(async delegate ()
  130. {
  131. _dnsWebService._log.Write("Attempting to restart DNS service.");
  132. try
  133. {
  134. await _dnsWebService.DnsServer.StopAsync();
  135. await _dnsWebService.DnsServer.StartAsync();
  136. _dnsWebService._log.Write("DNS service was restarted successfully.");
  137. }
  138. catch (Exception ex)
  139. {
  140. _dnsWebService._log.Write("Failed to restart DNS service.\r\n" + ex.ToString());
  141. }
  142. });
  143. }
  144. if (restartWebService)
  145. {
  146. _ = Task.Run(async delegate ()
  147. {
  148. await Task.Delay(2000); //wait for this HTTP response to be delivered before stopping web server
  149. _dnsWebService._log.Write("Attempting to restart web service.");
  150. try
  151. {
  152. await _dnsWebService.StopWebServiceAsync();
  153. await _dnsWebService.TryStartWebServiceAsync();
  154. _dnsWebService._log.Write("Web service was restarted successfully.");
  155. }
  156. catch (Exception ex)
  157. {
  158. _dnsWebService._log.Write("Failed to restart web service.\r\n" + ex.ToString());
  159. }
  160. });
  161. }
  162. }
  163. private static async Task CreateBackupEntryFromFileAsync(ZipArchive backupZip, string sourceFileName, string entryName)
  164. {
  165. using (FileStream fS = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  166. {
  167. ZipArchiveEntry entry = backupZip.CreateEntry(entryName);
  168. DateTime lastWrite = File.GetLastWriteTime(sourceFileName);
  169. // If file to be archived has an invalid last modified time, use the first datetime representable in the Zip timestamp format
  170. // (midnight on January 1, 1980):
  171. if (lastWrite.Year < 1980 || lastWrite.Year > 2107)
  172. lastWrite = new DateTime(1980, 1, 1, 0, 0, 0);
  173. entry.LastWriteTime = lastWrite;
  174. using (Stream sE = entry.Open())
  175. {
  176. await fS.CopyToAsync(sE);
  177. }
  178. }
  179. }
  180. private void WriteDnsSettings(Utf8JsonWriter jsonWriter)
  181. {
  182. //general
  183. jsonWriter.WriteString("version", _dnsWebService.GetServerVersion());
  184. jsonWriter.WriteString("uptimestamp", _dnsWebService._uptimestamp);
  185. jsonWriter.WriteString("dnsServerDomain", _dnsWebService.DnsServer.ServerDomain);
  186. jsonWriter.WritePropertyName("dnsServerLocalEndPoints");
  187. jsonWriter.WriteStartArray();
  188. foreach (IPEndPoint localEP in _dnsWebService.DnsServer.LocalEndPoints)
  189. jsonWriter.WriteStringValue(localEP.ToString());
  190. jsonWriter.WriteEndArray();
  191. jsonWriter.WriteNumber("defaultRecordTtl", _dnsWebService._zonesApi.DefaultRecordTtl);
  192. jsonWriter.WriteBoolean("dnsAppsEnableAutomaticUpdate", _dnsWebService._appsApi.EnableAutomaticUpdate);
  193. jsonWriter.WriteBoolean("preferIPv6", _dnsWebService.DnsServer.PreferIPv6);
  194. jsonWriter.WriteNumber("udpPayloadSize", _dnsWebService.DnsServer.UdpPayloadSize);
  195. jsonWriter.WriteBoolean("dnssecValidation", _dnsWebService.DnsServer.DnssecValidation);
  196. jsonWriter.WriteBoolean("eDnsClientSubnet", _dnsWebService.DnsServer.EDnsClientSubnet);
  197. jsonWriter.WriteNumber("eDnsClientSubnetIPv4PrefixLength", _dnsWebService.DnsServer.EDnsClientSubnetIPv4PrefixLength);
  198. jsonWriter.WriteNumber("eDnsClientSubnetIPv6PrefixLength", _dnsWebService.DnsServer.EDnsClientSubnetIPv6PrefixLength);
  199. jsonWriter.WriteNumber("qpmLimitRequests", _dnsWebService.DnsServer.QpmLimitRequests);
  200. jsonWriter.WriteNumber("qpmLimitErrors", _dnsWebService.DnsServer.QpmLimitErrors);
  201. jsonWriter.WriteNumber("qpmLimitSampleMinutes", _dnsWebService.DnsServer.QpmLimitSampleMinutes);
  202. jsonWriter.WriteNumber("qpmLimitIPv4PrefixLength", _dnsWebService.DnsServer.QpmLimitIPv4PrefixLength);
  203. jsonWriter.WriteNumber("qpmLimitIPv6PrefixLength", _dnsWebService.DnsServer.QpmLimitIPv6PrefixLength);
  204. jsonWriter.WriteNumber("clientTimeout", _dnsWebService.DnsServer.ClientTimeout);
  205. jsonWriter.WriteNumber("tcpSendTimeout", _dnsWebService.DnsServer.TcpSendTimeout);
  206. jsonWriter.WriteNumber("tcpReceiveTimeout", _dnsWebService.DnsServer.TcpReceiveTimeout);
  207. jsonWriter.WriteNumber("quicIdleTimeout", _dnsWebService.DnsServer.QuicIdleTimeout);
  208. jsonWriter.WriteNumber("quicMaxInboundStreams", _dnsWebService.DnsServer.QuicMaxInboundStreams);
  209. jsonWriter.WriteNumber("listenBacklog", _dnsWebService.DnsServer.ListenBacklog);
  210. //web service
  211. jsonWriter.WritePropertyName("webServiceLocalAddresses");
  212. jsonWriter.WriteStartArray();
  213. foreach (IPAddress localAddress in _dnsWebService._webServiceLocalAddresses)
  214. {
  215. if (localAddress.AddressFamily == AddressFamily.InterNetworkV6)
  216. jsonWriter.WriteStringValue("[" + localAddress.ToString() + "]");
  217. else
  218. jsonWriter.WriteStringValue(localAddress.ToString());
  219. }
  220. jsonWriter.WriteEndArray();
  221. jsonWriter.WriteNumber("webServiceHttpPort", _dnsWebService._webServiceHttpPort);
  222. jsonWriter.WriteBoolean("webServiceEnableTls", _dnsWebService._webServiceEnableTls);
  223. jsonWriter.WriteBoolean("webServiceHttpToTlsRedirect", _dnsWebService._webServiceHttpToTlsRedirect);
  224. jsonWriter.WriteBoolean("webServiceUseSelfSignedTlsCertificate", _dnsWebService._webServiceUseSelfSignedTlsCertificate);
  225. jsonWriter.WriteNumber("webServiceTlsPort", _dnsWebService._webServiceTlsPort);
  226. jsonWriter.WriteString("webServiceTlsCertificatePath", _dnsWebService._webServiceTlsCertificatePath);
  227. jsonWriter.WriteString("webServiceTlsCertificatePassword", "************");
  228. //optional protocols
  229. jsonWriter.WriteBoolean("enableDnsOverUdpProxy", _dnsWebService.DnsServer.EnableDnsOverUdpProxy);
  230. jsonWriter.WriteBoolean("enableDnsOverTcpProxy", _dnsWebService.DnsServer.EnableDnsOverTcpProxy);
  231. jsonWriter.WriteBoolean("enableDnsOverHttp", _dnsWebService.DnsServer.EnableDnsOverHttp);
  232. jsonWriter.WriteBoolean("enableDnsOverTls", _dnsWebService.DnsServer.EnableDnsOverTls);
  233. jsonWriter.WriteBoolean("enableDnsOverHttps", _dnsWebService.DnsServer.EnableDnsOverHttps);
  234. jsonWriter.WriteBoolean("enableDnsOverQuic", _dnsWebService.DnsServer.EnableDnsOverQuic);
  235. jsonWriter.WriteNumber("dnsOverUdpProxyPort", _dnsWebService.DnsServer.DnsOverUdpProxyPort);
  236. jsonWriter.WriteNumber("dnsOverTcpProxyPort", _dnsWebService.DnsServer.DnsOverTcpProxyPort);
  237. jsonWriter.WriteNumber("dnsOverHttpPort", _dnsWebService.DnsServer.DnsOverHttpPort);
  238. jsonWriter.WriteNumber("dnsOverTlsPort", _dnsWebService.DnsServer.DnsOverTlsPort);
  239. jsonWriter.WriteNumber("dnsOverHttpsPort", _dnsWebService.DnsServer.DnsOverHttpsPort);
  240. jsonWriter.WriteNumber("dnsOverQuicPort", _dnsWebService.DnsServer.DnsOverQuicPort);
  241. jsonWriter.WriteString("dnsTlsCertificatePath", _dnsWebService._dnsTlsCertificatePath);
  242. jsonWriter.WriteString("dnsTlsCertificatePassword", "************");
  243. //tsig
  244. jsonWriter.WritePropertyName("tsigKeys");
  245. {
  246. jsonWriter.WriteStartArray();
  247. if (_dnsWebService.DnsServer.TsigKeys is not null)
  248. {
  249. foreach (KeyValuePair<string, TsigKey> tsigKey in _dnsWebService.DnsServer.TsigKeys)
  250. {
  251. jsonWriter.WriteStartObject();
  252. jsonWriter.WriteString("keyName", tsigKey.Key);
  253. jsonWriter.WriteString("sharedSecret", tsigKey.Value.SharedSecret);
  254. jsonWriter.WriteString("algorithmName", tsigKey.Value.AlgorithmName);
  255. jsonWriter.WriteEndObject();
  256. }
  257. }
  258. jsonWriter.WriteEndArray();
  259. }
  260. //recursion
  261. jsonWriter.WriteString("recursion", _dnsWebService.DnsServer.Recursion.ToString());
  262. jsonWriter.WritePropertyName("recursionDeniedNetworks");
  263. {
  264. jsonWriter.WriteStartArray();
  265. if (_dnsWebService.DnsServer.RecursionDeniedNetworks is not null)
  266. {
  267. foreach (NetworkAddress networkAddress in _dnsWebService.DnsServer.RecursionDeniedNetworks)
  268. jsonWriter.WriteStringValue(networkAddress.ToString());
  269. }
  270. jsonWriter.WriteEndArray();
  271. }
  272. jsonWriter.WritePropertyName("recursionAllowedNetworks");
  273. {
  274. jsonWriter.WriteStartArray();
  275. if (_dnsWebService.DnsServer.RecursionAllowedNetworks is not null)
  276. {
  277. foreach (NetworkAddress networkAddress in _dnsWebService.DnsServer.RecursionAllowedNetworks)
  278. jsonWriter.WriteStringValue(networkAddress.ToString());
  279. }
  280. jsonWriter.WriteEndArray();
  281. }
  282. jsonWriter.WriteBoolean("randomizeName", _dnsWebService.DnsServer.RandomizeName);
  283. jsonWriter.WriteBoolean("qnameMinimization", _dnsWebService.DnsServer.QnameMinimization);
  284. jsonWriter.WriteBoolean("nsRevalidation", _dnsWebService.DnsServer.NsRevalidation);
  285. jsonWriter.WriteNumber("resolverRetries", _dnsWebService.DnsServer.ResolverRetries);
  286. jsonWriter.WriteNumber("resolverTimeout", _dnsWebService.DnsServer.ResolverTimeout);
  287. jsonWriter.WriteNumber("resolverMaxStackCount", _dnsWebService.DnsServer.ResolverMaxStackCount);
  288. //cache
  289. jsonWriter.WriteBoolean("saveCache", _dnsWebService._saveCache);
  290. jsonWriter.WriteBoolean("serveStale", _dnsWebService.DnsServer.ServeStale);
  291. jsonWriter.WriteNumber("serveStaleTtl", _dnsWebService.DnsServer.CacheZoneManager.ServeStaleTtl);
  292. jsonWriter.WriteNumber("cacheMaximumEntries", _dnsWebService.DnsServer.CacheZoneManager.MaximumEntries);
  293. jsonWriter.WriteNumber("cacheMinimumRecordTtl", _dnsWebService.DnsServer.CacheZoneManager.MinimumRecordTtl);
  294. jsonWriter.WriteNumber("cacheMaximumRecordTtl", _dnsWebService.DnsServer.CacheZoneManager.MaximumRecordTtl);
  295. jsonWriter.WriteNumber("cacheNegativeRecordTtl", _dnsWebService.DnsServer.CacheZoneManager.NegativeRecordTtl);
  296. jsonWriter.WriteNumber("cacheFailureRecordTtl", _dnsWebService.DnsServer.CacheZoneManager.FailureRecordTtl);
  297. jsonWriter.WriteNumber("cachePrefetchEligibility", _dnsWebService.DnsServer.CachePrefetchEligibility);
  298. jsonWriter.WriteNumber("cachePrefetchTrigger", _dnsWebService.DnsServer.CachePrefetchTrigger);
  299. jsonWriter.WriteNumber("cachePrefetchSampleIntervalInMinutes", _dnsWebService.DnsServer.CachePrefetchSampleIntervalInMinutes);
  300. jsonWriter.WriteNumber("cachePrefetchSampleEligibilityHitsPerHour", _dnsWebService.DnsServer.CachePrefetchSampleEligibilityHitsPerHour);
  301. //blocking
  302. jsonWriter.WriteBoolean("enableBlocking", _dnsWebService.DnsServer.EnableBlocking);
  303. jsonWriter.WriteBoolean("allowTxtBlockingReport", _dnsWebService.DnsServer.AllowTxtBlockingReport);
  304. if (!_dnsWebService.DnsServer.EnableBlocking && (DateTime.UtcNow < _temporaryDisableBlockingTill))
  305. jsonWriter.WriteString("temporaryDisableBlockingTill", _temporaryDisableBlockingTill);
  306. jsonWriter.WriteString("blockingType", _dnsWebService.DnsServer.BlockingType.ToString());
  307. jsonWriter.WritePropertyName("customBlockingAddresses");
  308. jsonWriter.WriteStartArray();
  309. foreach (DnsARecordData record in _dnsWebService.DnsServer.CustomBlockingARecords)
  310. jsonWriter.WriteStringValue(record.Address.ToString());
  311. foreach (DnsAAAARecordData record in _dnsWebService.DnsServer.CustomBlockingAAAARecords)
  312. jsonWriter.WriteStringValue(record.Address.ToString());
  313. jsonWriter.WriteEndArray();
  314. jsonWriter.WritePropertyName("blockListUrls");
  315. if ((_dnsWebService.DnsServer.BlockListZoneManager.AllowListUrls.Count == 0) && (_dnsWebService.DnsServer.BlockListZoneManager.BlockListUrls.Count == 0))
  316. {
  317. jsonWriter.WriteNullValue();
  318. }
  319. else
  320. {
  321. jsonWriter.WriteStartArray();
  322. foreach (Uri allowListUrl in _dnsWebService.DnsServer.BlockListZoneManager.AllowListUrls)
  323. jsonWriter.WriteStringValue("!" + allowListUrl.AbsoluteUri);
  324. foreach (Uri blockListUrl in _dnsWebService.DnsServer.BlockListZoneManager.BlockListUrls)
  325. jsonWriter.WriteStringValue(blockListUrl.AbsoluteUri);
  326. jsonWriter.WriteEndArray();
  327. }
  328. jsonWriter.WriteNumber("blockListUpdateIntervalHours", _blockListUpdateIntervalHours);
  329. if (_blockListUpdateTimer is not null)
  330. {
  331. DateTime blockListNextUpdatedOn = _blockListLastUpdatedOn.AddHours(_blockListUpdateIntervalHours);
  332. jsonWriter.WriteString("blockListNextUpdatedOn", blockListNextUpdatedOn);
  333. }
  334. //proxy & forwarders
  335. jsonWriter.WritePropertyName("proxy");
  336. if (_dnsWebService.DnsServer.Proxy == null)
  337. {
  338. jsonWriter.WriteNullValue();
  339. }
  340. else
  341. {
  342. jsonWriter.WriteStartObject();
  343. NetProxy proxy = _dnsWebService.DnsServer.Proxy;
  344. jsonWriter.WriteString("type", proxy.Type.ToString());
  345. jsonWriter.WriteString("address", proxy.Address);
  346. jsonWriter.WriteNumber("port", proxy.Port);
  347. NetworkCredential credential = proxy.Credential;
  348. if (credential != null)
  349. {
  350. jsonWriter.WriteString("username", credential.UserName);
  351. jsonWriter.WriteString("password", credential.Password);
  352. }
  353. jsonWriter.WritePropertyName("bypass");
  354. jsonWriter.WriteStartArray();
  355. foreach (NetProxyBypassItem item in proxy.BypassList)
  356. jsonWriter.WriteStringValue(item.Value);
  357. jsonWriter.WriteEndArray();
  358. jsonWriter.WriteEndObject();
  359. }
  360. jsonWriter.WritePropertyName("forwarders");
  361. DnsTransportProtocol forwarderProtocol = DnsTransportProtocol.Udp;
  362. if (_dnsWebService.DnsServer.Forwarders == null)
  363. {
  364. jsonWriter.WriteNullValue();
  365. }
  366. else
  367. {
  368. forwarderProtocol = _dnsWebService.DnsServer.Forwarders[0].Protocol;
  369. jsonWriter.WriteStartArray();
  370. foreach (NameServerAddress forwarder in _dnsWebService.DnsServer.Forwarders)
  371. jsonWriter.WriteStringValue(forwarder.OriginalAddress);
  372. jsonWriter.WriteEndArray();
  373. }
  374. jsonWriter.WriteString("forwarderProtocol", forwarderProtocol.ToString());
  375. jsonWriter.WriteNumber("forwarderRetries", _dnsWebService.DnsServer.ForwarderRetries);
  376. jsonWriter.WriteNumber("forwarderTimeout", _dnsWebService.DnsServer.ForwarderTimeout);
  377. jsonWriter.WriteNumber("forwarderConcurrency", _dnsWebService.DnsServer.ForwarderConcurrency);
  378. //logging
  379. jsonWriter.WriteBoolean("enableLogging", _dnsWebService._log.EnableLogging);
  380. jsonWriter.WriteBoolean("logQueries", _dnsWebService.DnsServer.QueryLogManager != null);
  381. jsonWriter.WriteBoolean("useLocalTime", _dnsWebService._log.UseLocalTime);
  382. jsonWriter.WriteString("logFolder", _dnsWebService._log.LogFolder);
  383. jsonWriter.WriteNumber("maxLogFileDays", _dnsWebService._log.MaxLogFileDays);
  384. jsonWriter.WriteNumber("maxStatFileDays", _dnsWebService.DnsServer.StatsManager.MaxStatFileDays);
  385. }
  386. #endregion
  387. #region public
  388. public void GetDnsSettings(HttpContext context)
  389. {
  390. UserSession session = context.GetCurrentSession();
  391. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Settings, session.User, PermissionFlag.View))
  392. throw new DnsWebServiceException("Access was denied.");
  393. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  394. WriteDnsSettings(jsonWriter);
  395. }
  396. public void SetDnsSettings(HttpContext context)
  397. {
  398. UserSession session = context.GetCurrentSession();
  399. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Settings, session.User, PermissionFlag.Modify))
  400. throw new DnsWebServiceException("Access was denied.");
  401. bool serverDomainChanged = false;
  402. bool restartDnsService = false;
  403. bool restartWebService = false;
  404. bool blockListUrlsUpdated = false;
  405. int oldWebServiceHttpPort = _dnsWebService._webServiceHttpPort;
  406. HttpRequest request = context.Request;
  407. //general
  408. if (request.TryGetQueryOrForm("dnsServerDomain", out string dnsServerDomain))
  409. {
  410. if (!_dnsWebService.DnsServer.ServerDomain.Equals(dnsServerDomain, StringComparison.OrdinalIgnoreCase))
  411. {
  412. _dnsWebService.DnsServer.ServerDomain = dnsServerDomain;
  413. serverDomainChanged = true;
  414. }
  415. }
  416. string dnsServerLocalEndPoints = request.QueryOrForm("dnsServerLocalEndPoints");
  417. if (dnsServerLocalEndPoints is not null)
  418. {
  419. if (dnsServerLocalEndPoints.Length == 0)
  420. dnsServerLocalEndPoints = "0.0.0.0:53,[::]:53";
  421. IPEndPoint[] localEndPoints = dnsServerLocalEndPoints.Split(IPEndPoint.Parse, ',');
  422. if (localEndPoints.Length > 0)
  423. {
  424. foreach (IPEndPoint localEndPoint in localEndPoints)
  425. {
  426. if (localEndPoint.Port == 0)
  427. localEndPoint.Port = 53;
  428. }
  429. if (_dnsWebService.DnsServer.LocalEndPoints.Count != localEndPoints.Length)
  430. {
  431. restartDnsService = true;
  432. }
  433. else
  434. {
  435. foreach (IPEndPoint currentLocalEP in _dnsWebService.DnsServer.LocalEndPoints)
  436. {
  437. if (!localEndPoints.Contains(currentLocalEP))
  438. {
  439. restartDnsService = true;
  440. break;
  441. }
  442. }
  443. }
  444. _dnsWebService.DnsServer.LocalEndPoints = localEndPoints;
  445. }
  446. }
  447. if (request.TryGetQueryOrForm("defaultRecordTtl", uint.Parse, out uint defaultRecordTtl))
  448. _dnsWebService._zonesApi.DefaultRecordTtl = defaultRecordTtl;
  449. if (request.TryGetQueryOrForm("dnsAppsEnableAutomaticUpdate", bool.Parse, out bool dnsAppsEnableAutomaticUpdate))
  450. _dnsWebService._appsApi.EnableAutomaticUpdate = dnsAppsEnableAutomaticUpdate;
  451. if (request.TryGetQueryOrForm("preferIPv6", bool.Parse, out bool preferIPv6))
  452. _dnsWebService.DnsServer.PreferIPv6 = preferIPv6;
  453. if (request.TryGetQueryOrForm("udpPayloadSize", ushort.Parse, out ushort udpPayloadSize))
  454. _dnsWebService.DnsServer.UdpPayloadSize = udpPayloadSize;
  455. if (request.TryGetQueryOrForm("dnssecValidation", bool.Parse, out bool dnssecValidation))
  456. _dnsWebService.DnsServer.DnssecValidation = dnssecValidation;
  457. if (request.TryGetQueryOrForm("eDnsClientSubnet", bool.Parse, out bool eDnsClientSubnet))
  458. _dnsWebService.DnsServer.EDnsClientSubnet = eDnsClientSubnet;
  459. if (request.TryGetQueryOrForm("eDnsClientSubnetIPv4PrefixLength", byte.Parse, out byte eDnsClientSubnetIPv4PrefixLength))
  460. _dnsWebService.DnsServer.EDnsClientSubnetIPv4PrefixLength = eDnsClientSubnetIPv4PrefixLength;
  461. if (request.TryGetQueryOrForm("eDnsClientSubnetIPv6PrefixLength", byte.Parse, out byte eDnsClientSubnetIPv6PrefixLength))
  462. _dnsWebService.DnsServer.EDnsClientSubnetIPv6PrefixLength = eDnsClientSubnetIPv6PrefixLength;
  463. if (request.TryGetQueryOrForm("qpmLimitRequests", int.Parse, out int qpmLimitRequests))
  464. _dnsWebService.DnsServer.QpmLimitRequests = qpmLimitRequests;
  465. if (request.TryGetQueryOrForm("qpmLimitErrors", int.Parse, out int qpmLimitErrors))
  466. _dnsWebService.DnsServer.QpmLimitErrors = qpmLimitErrors;
  467. if (request.TryGetQueryOrForm("qpmLimitSampleMinutes", int.Parse, out int qpmLimitSampleMinutes))
  468. _dnsWebService.DnsServer.QpmLimitSampleMinutes = qpmLimitSampleMinutes;
  469. if (request.TryGetQueryOrForm("qpmLimitIPv4PrefixLength", int.Parse, out int qpmLimitIPv4PrefixLength))
  470. _dnsWebService.DnsServer.QpmLimitIPv4PrefixLength = qpmLimitIPv4PrefixLength;
  471. if (request.TryGetQueryOrForm("qpmLimitIPv6PrefixLength", int.Parse, out int qpmLimitIPv6PrefixLength))
  472. _dnsWebService.DnsServer.QpmLimitIPv6PrefixLength = qpmLimitIPv6PrefixLength;
  473. if (request.TryGetQueryOrForm("clientTimeout", int.Parse, out int clientTimeout))
  474. _dnsWebService.DnsServer.ClientTimeout = clientTimeout;
  475. if (request.TryGetQueryOrForm("tcpSendTimeout", int.Parse, out int tcpSendTimeout))
  476. _dnsWebService.DnsServer.TcpSendTimeout = tcpSendTimeout;
  477. if (request.TryGetQueryOrForm("tcpReceiveTimeout", int.Parse, out int tcpReceiveTimeout))
  478. _dnsWebService.DnsServer.TcpReceiveTimeout = tcpReceiveTimeout;
  479. if (request.TryGetQueryOrForm("quicIdleTimeout", int.Parse, out int quicIdleTimeout))
  480. _dnsWebService.DnsServer.QuicIdleTimeout = quicIdleTimeout;
  481. if (request.TryGetQueryOrForm("quicMaxInboundStreams", int.Parse, out int quicMaxInboundStreams))
  482. _dnsWebService.DnsServer.QuicMaxInboundStreams = quicMaxInboundStreams;
  483. if (request.TryGetQueryOrForm("listenBacklog", int.Parse, out int listenBacklog))
  484. _dnsWebService.DnsServer.ListenBacklog = listenBacklog;
  485. //web service
  486. string webServiceLocalAddresses = request.QueryOrForm("webServiceLocalAddresses");
  487. if (webServiceLocalAddresses is not null)
  488. {
  489. if (webServiceLocalAddresses.Length == 0)
  490. webServiceLocalAddresses = "0.0.0.0,[::]";
  491. IPAddress[] localAddresses = webServiceLocalAddresses.Split(IPAddress.Parse, ',');
  492. if (localAddresses.Length > 0)
  493. {
  494. if (_dnsWebService._webServiceLocalAddresses.Count != localAddresses.Length)
  495. {
  496. restartWebService = true;
  497. }
  498. else
  499. {
  500. foreach (IPAddress currentlocalAddress in _dnsWebService._webServiceLocalAddresses)
  501. {
  502. if (!localAddresses.Contains(currentlocalAddress))
  503. {
  504. restartWebService = true;
  505. break;
  506. }
  507. }
  508. }
  509. _dnsWebService._webServiceLocalAddresses = DnsServer.GetValidKestralLocalAddresses(localAddresses);
  510. }
  511. }
  512. if (request.TryGetQueryOrForm("webServiceHttpPort", int.Parse, out int webServiceHttpPort))
  513. {
  514. if (_dnsWebService._webServiceHttpPort != webServiceHttpPort)
  515. {
  516. _dnsWebService._webServiceHttpPort = webServiceHttpPort;
  517. restartWebService = true;
  518. }
  519. }
  520. if (request.TryGetQueryOrForm("webServiceEnableTls", bool.Parse, out bool webServiceEnableTls))
  521. {
  522. if (_dnsWebService._webServiceEnableTls != webServiceEnableTls)
  523. {
  524. _dnsWebService._webServiceEnableTls = webServiceEnableTls;
  525. restartWebService = true;
  526. }
  527. }
  528. if (request.TryGetQueryOrForm("webServiceHttpToTlsRedirect", bool.Parse, out bool webServiceHttpToTlsRedirect))
  529. {
  530. if (_dnsWebService._webServiceHttpToTlsRedirect != webServiceHttpToTlsRedirect)
  531. {
  532. _dnsWebService._webServiceHttpToTlsRedirect = webServiceHttpToTlsRedirect;
  533. restartWebService = true;
  534. }
  535. }
  536. if (request.TryGetQueryOrForm("webServiceUseSelfSignedTlsCertificate", bool.Parse, out bool webServiceUseSelfSignedTlsCertificate))
  537. _dnsWebService._webServiceUseSelfSignedTlsCertificate = webServiceUseSelfSignedTlsCertificate;
  538. if (request.TryGetQueryOrForm("webServiceTlsPort", int.Parse, out int webServiceTlsPort))
  539. {
  540. if (_dnsWebService._webServiceTlsPort != webServiceTlsPort)
  541. {
  542. _dnsWebService._webServiceTlsPort = webServiceTlsPort;
  543. restartWebService = true;
  544. }
  545. }
  546. string webServiceTlsCertificatePath = request.QueryOrForm("webServiceTlsCertificatePath");
  547. if (webServiceTlsCertificatePath is not null)
  548. {
  549. if (webServiceTlsCertificatePath.Length == 0)
  550. {
  551. _dnsWebService._webServiceTlsCertificatePath = null;
  552. _dnsWebService._webServiceTlsCertificatePassword = "";
  553. }
  554. else
  555. {
  556. string webServiceTlsCertificatePassword = request.QueryOrForm("webServiceTlsCertificatePassword");
  557. if ((webServiceTlsCertificatePassword is null) || (webServiceTlsCertificatePassword == "************"))
  558. webServiceTlsCertificatePassword = _dnsWebService._webServiceTlsCertificatePassword;
  559. if ((webServiceTlsCertificatePath != _dnsWebService._webServiceTlsCertificatePath) || (webServiceTlsCertificatePassword != _dnsWebService._webServiceTlsCertificatePassword))
  560. {
  561. _dnsWebService.LoadWebServiceTlsCertificate(_dnsWebService.ConvertToAbsolutePath(webServiceTlsCertificatePath), webServiceTlsCertificatePassword);
  562. _dnsWebService._webServiceTlsCertificatePath = _dnsWebService.ConvertToRelativePath(webServiceTlsCertificatePath);
  563. _dnsWebService._webServiceTlsCertificatePassword = webServiceTlsCertificatePassword;
  564. _dnsWebService.StartTlsCertificateUpdateTimer();
  565. }
  566. }
  567. }
  568. //optional protocols
  569. if (request.TryGetQueryOrForm("enableDnsOverUdpProxy", bool.Parse, out bool enableDnsOverUdpProxy))
  570. {
  571. if (_dnsWebService.DnsServer.EnableDnsOverUdpProxy != enableDnsOverUdpProxy)
  572. {
  573. _dnsWebService.DnsServer.EnableDnsOverUdpProxy = enableDnsOverUdpProxy;
  574. restartDnsService = true;
  575. }
  576. }
  577. if (request.TryGetQueryOrForm("enableDnsOverTcpProxy", bool.Parse, out bool enableDnsOverTcpProxy))
  578. {
  579. if (_dnsWebService.DnsServer.EnableDnsOverTcpProxy != enableDnsOverTcpProxy)
  580. {
  581. _dnsWebService.DnsServer.EnableDnsOverTcpProxy = enableDnsOverTcpProxy;
  582. restartDnsService = true;
  583. }
  584. }
  585. if (request.TryGetQueryOrForm("enableDnsOverHttp", bool.Parse, out bool enableDnsOverHttp))
  586. {
  587. if (_dnsWebService.DnsServer.EnableDnsOverHttp != enableDnsOverHttp)
  588. {
  589. _dnsWebService.DnsServer.EnableDnsOverHttp = enableDnsOverHttp;
  590. restartDnsService = true;
  591. }
  592. }
  593. if (request.TryGetQueryOrForm("enableDnsOverTls", bool.Parse, out bool enableDnsOverTls))
  594. {
  595. if (_dnsWebService.DnsServer.EnableDnsOverTls != enableDnsOverTls)
  596. {
  597. _dnsWebService.DnsServer.EnableDnsOverTls = enableDnsOverTls;
  598. restartDnsService = true;
  599. }
  600. }
  601. if (request.TryGetQueryOrForm("enableDnsOverHttps", bool.Parse, out bool enableDnsOverHttps))
  602. {
  603. if (_dnsWebService.DnsServer.EnableDnsOverHttps != enableDnsOverHttps)
  604. {
  605. _dnsWebService.DnsServer.EnableDnsOverHttps = enableDnsOverHttps;
  606. restartDnsService = true;
  607. }
  608. }
  609. if (request.TryGetQueryOrForm("enableDnsOverQuic", bool.Parse, out bool enableDnsOverQuic))
  610. {
  611. if (_dnsWebService.DnsServer.EnableDnsOverQuic != enableDnsOverQuic)
  612. {
  613. if (enableDnsOverQuic)
  614. DnsWebService.ValidateQuicSupport();
  615. _dnsWebService.DnsServer.EnableDnsOverQuic = enableDnsOverQuic;
  616. restartDnsService = true;
  617. }
  618. }
  619. if (request.TryGetQueryOrForm("dnsOverUdpProxyPort", int.Parse, out int dnsOverUdpProxyPort))
  620. {
  621. if (_dnsWebService.DnsServer.DnsOverUdpProxyPort != dnsOverUdpProxyPort)
  622. {
  623. _dnsWebService.DnsServer.DnsOverUdpProxyPort = dnsOverUdpProxyPort;
  624. restartDnsService = true;
  625. }
  626. }
  627. if (request.TryGetQueryOrForm("dnsOverTcpProxyPort", int.Parse, out int dnsOverTcpProxyPort))
  628. {
  629. if (_dnsWebService.DnsServer.DnsOverTcpProxyPort != dnsOverTcpProxyPort)
  630. {
  631. _dnsWebService.DnsServer.DnsOverTcpProxyPort = dnsOverTcpProxyPort;
  632. restartDnsService = true;
  633. }
  634. }
  635. if (request.TryGetQueryOrForm("dnsOverHttpPort", int.Parse, out int dnsOverHttpPort))
  636. {
  637. if (_dnsWebService.DnsServer.DnsOverHttpPort != dnsOverHttpPort)
  638. {
  639. _dnsWebService.DnsServer.DnsOverHttpPort = dnsOverHttpPort;
  640. restartDnsService = true;
  641. }
  642. }
  643. if (request.TryGetQueryOrForm("dnsOverTlsPort", int.Parse, out int dnsOverTlsPort))
  644. {
  645. if (_dnsWebService.DnsServer.DnsOverTlsPort != dnsOverTlsPort)
  646. {
  647. _dnsWebService.DnsServer.DnsOverTlsPort = dnsOverTlsPort;
  648. restartDnsService = true;
  649. }
  650. }
  651. if (request.TryGetQueryOrForm("dnsOverHttpsPort", int.Parse, out int dnsOverHttpsPort))
  652. {
  653. if (_dnsWebService.DnsServer.DnsOverHttpsPort != dnsOverHttpsPort)
  654. {
  655. _dnsWebService.DnsServer.DnsOverHttpsPort = dnsOverHttpsPort;
  656. restartDnsService = true;
  657. }
  658. }
  659. if (request.TryGetQueryOrForm("dnsOverQuicPort", int.Parse, out int dnsOverQuicPort))
  660. {
  661. if (_dnsWebService.DnsServer.DnsOverQuicPort != dnsOverQuicPort)
  662. {
  663. _dnsWebService.DnsServer.DnsOverQuicPort = dnsOverQuicPort;
  664. restartDnsService = true;
  665. }
  666. }
  667. string dnsTlsCertificatePath = request.QueryOrForm("dnsTlsCertificatePath");
  668. if (dnsTlsCertificatePath is not null)
  669. {
  670. if (dnsTlsCertificatePath.Length == 0)
  671. {
  672. if (!string.IsNullOrEmpty(_dnsWebService._dnsTlsCertificatePath) && (_dnsWebService.DnsServer.EnableDnsOverTls || _dnsWebService.DnsServer.EnableDnsOverHttps || _dnsWebService.DnsServer.EnableDnsOverQuic))
  673. restartDnsService = true;
  674. _dnsWebService.DnsServer.CertificateCollection = null;
  675. _dnsWebService._dnsTlsCertificatePath = null;
  676. _dnsWebService._dnsTlsCertificatePassword = "";
  677. }
  678. else
  679. {
  680. string strDnsTlsCertificatePassword = request.QueryOrForm("dnsTlsCertificatePassword");
  681. if ((strDnsTlsCertificatePassword is null) || (strDnsTlsCertificatePassword == "************"))
  682. strDnsTlsCertificatePassword = _dnsWebService._dnsTlsCertificatePassword;
  683. if ((dnsTlsCertificatePath != _dnsWebService._dnsTlsCertificatePath) || (strDnsTlsCertificatePassword != _dnsWebService._dnsTlsCertificatePassword))
  684. {
  685. _dnsWebService.LoadDnsTlsCertificate(_dnsWebService.ConvertToAbsolutePath(dnsTlsCertificatePath), strDnsTlsCertificatePassword);
  686. if (string.IsNullOrEmpty(_dnsWebService._dnsTlsCertificatePath) && (_dnsWebService.DnsServer.EnableDnsOverTls || _dnsWebService.DnsServer.EnableDnsOverHttps || _dnsWebService.DnsServer.EnableDnsOverQuic))
  687. restartDnsService = true;
  688. _dnsWebService._dnsTlsCertificatePath = _dnsWebService.ConvertToRelativePath(dnsTlsCertificatePath);
  689. _dnsWebService._dnsTlsCertificatePassword = strDnsTlsCertificatePassword;
  690. _dnsWebService.StartTlsCertificateUpdateTimer();
  691. }
  692. }
  693. }
  694. //tsig
  695. string strTsigKeys = request.QueryOrForm("tsigKeys");
  696. if (strTsigKeys is not null)
  697. {
  698. if ((strTsigKeys.Length == 0) || strTsigKeys.Equals("false", StringComparison.OrdinalIgnoreCase))
  699. {
  700. _dnsWebService.DnsServer.TsigKeys = null;
  701. }
  702. else
  703. {
  704. string[] strTsigKeyParts = strTsigKeys.Split('|');
  705. Dictionary<string, TsigKey> tsigKeys = new Dictionary<string, TsigKey>(strTsigKeyParts.Length);
  706. for (int i = 0; i < strTsigKeyParts.Length; i += 3)
  707. {
  708. string keyName = strTsigKeyParts[i + 0].ToLower();
  709. string sharedSecret = strTsigKeyParts[i + 1];
  710. string algorithmName = strTsigKeyParts[i + 2];
  711. if (sharedSecret.Length == 0)
  712. {
  713. byte[] key = new byte[32];
  714. _rng.GetBytes(key);
  715. tsigKeys.Add(keyName, new TsigKey(keyName, Convert.ToBase64String(key), algorithmName));
  716. }
  717. else
  718. {
  719. tsigKeys.Add(keyName, new TsigKey(keyName, sharedSecret, algorithmName));
  720. }
  721. }
  722. _dnsWebService.DnsServer.TsigKeys = tsigKeys;
  723. }
  724. }
  725. //recursion
  726. if (request.TryGetQueryOrFormEnum("recursion", out DnsServerRecursion recursion))
  727. _dnsWebService.DnsServer.Recursion = recursion;
  728. string recursionDeniedNetworks = request.QueryOrForm("recursionDeniedNetworks");
  729. if (recursionDeniedNetworks is not null)
  730. {
  731. if ((recursionDeniedNetworks.Length == 0) || recursionDeniedNetworks.Equals("false", StringComparison.OrdinalIgnoreCase))
  732. _dnsWebService.DnsServer.RecursionDeniedNetworks = null;
  733. else
  734. _dnsWebService.DnsServer.RecursionDeniedNetworks = recursionDeniedNetworks.Split(NetworkAddress.Parse, ',');
  735. }
  736. string recursionAllowedNetworks = request.QueryOrForm("recursionAllowedNetworks");
  737. if (recursionAllowedNetworks is not null)
  738. {
  739. if ((recursionAllowedNetworks.Length == 0) || recursionAllowedNetworks.Equals("false", StringComparison.OrdinalIgnoreCase))
  740. _dnsWebService.DnsServer.RecursionAllowedNetworks = null;
  741. else
  742. _dnsWebService.DnsServer.RecursionAllowedNetworks = recursionAllowedNetworks.Split(NetworkAddress.Parse, ',');
  743. }
  744. if (request.TryGetQueryOrForm("randomizeName", bool.Parse, out bool randomizeName))
  745. _dnsWebService.DnsServer.RandomizeName = randomizeName;
  746. if (request.TryGetQueryOrForm("qnameMinimization", bool.Parse, out bool qnameMinimization))
  747. _dnsWebService.DnsServer.QnameMinimization = qnameMinimization;
  748. if (request.TryGetQueryOrForm("nsRevalidation", bool.Parse, out bool nsRevalidation))
  749. _dnsWebService.DnsServer.NsRevalidation = nsRevalidation;
  750. if (request.TryGetQueryOrForm("resolverRetries", int.Parse, out int resolverRetries))
  751. _dnsWebService.DnsServer.ResolverRetries = resolverRetries;
  752. if (request.TryGetQueryOrForm("resolverTimeout", int.Parse, out int resolverTimeout))
  753. _dnsWebService.DnsServer.ResolverTimeout = resolverTimeout;
  754. if (request.TryGetQueryOrForm("resolverMaxStackCount", int.Parse, out int resolverMaxStackCount))
  755. _dnsWebService.DnsServer.ResolverMaxStackCount = resolverMaxStackCount;
  756. //cache
  757. if (request.TryGetQueryOrForm("saveCache", bool.Parse, out bool saveCache))
  758. {
  759. if (!saveCache)
  760. _dnsWebService.DnsServer.CacheZoneManager.DeleteCacheZoneFile();
  761. _dnsWebService._saveCache = saveCache;
  762. }
  763. if (request.TryGetQueryOrForm("serveStale", bool.Parse, out bool serveStale))
  764. _dnsWebService.DnsServer.ServeStale = serveStale;
  765. if (request.TryGetQueryOrForm("serveStaleTtl", uint.Parse, out uint serveStaleTtl))
  766. _dnsWebService.DnsServer.CacheZoneManager.ServeStaleTtl = serveStaleTtl;
  767. if (request.TryGetQueryOrForm("cacheMaximumEntries", long.Parse, out long cacheMaximumEntries))
  768. _dnsWebService.DnsServer.CacheZoneManager.MaximumEntries = cacheMaximumEntries;
  769. if (request.TryGetQueryOrForm("cacheMinimumRecordTtl", uint.Parse, out uint cacheMinimumRecordTtl))
  770. _dnsWebService.DnsServer.CacheZoneManager.MinimumRecordTtl = cacheMinimumRecordTtl;
  771. if (request.TryGetQueryOrForm("cacheMaximumRecordTtl", uint.Parse, out uint cacheMaximumRecordTtl))
  772. _dnsWebService.DnsServer.CacheZoneManager.MaximumRecordTtl = cacheMaximumRecordTtl;
  773. if (request.TryGetQueryOrForm("cacheNegativeRecordTtl", uint.Parse, out uint cacheNegativeRecordTtl))
  774. _dnsWebService.DnsServer.CacheZoneManager.NegativeRecordTtl = cacheNegativeRecordTtl;
  775. if (request.TryGetQueryOrForm("cacheFailureRecordTtl", uint.Parse, out uint cacheFailureRecordTtl))
  776. _dnsWebService.DnsServer.CacheZoneManager.FailureRecordTtl = cacheFailureRecordTtl;
  777. if (request.TryGetQueryOrForm("cachePrefetchEligibility", int.Parse, out int cachePrefetchEligibility))
  778. _dnsWebService.DnsServer.CachePrefetchEligibility = cachePrefetchEligibility;
  779. if (request.TryGetQueryOrForm("cachePrefetchTrigger", int.Parse, out int cachePrefetchTrigger))
  780. _dnsWebService.DnsServer.CachePrefetchTrigger = cachePrefetchTrigger;
  781. if (request.TryGetQueryOrForm("cachePrefetchSampleIntervalInMinutes", int.Parse, out int cachePrefetchSampleIntervalInMinutes))
  782. _dnsWebService.DnsServer.CachePrefetchSampleIntervalInMinutes = cachePrefetchSampleIntervalInMinutes;
  783. if (request.TryGetQueryOrForm("cachePrefetchSampleEligibilityHitsPerHour", int.Parse, out int cachePrefetchSampleEligibilityHitsPerHour))
  784. _dnsWebService.DnsServer.CachePrefetchSampleEligibilityHitsPerHour = cachePrefetchSampleEligibilityHitsPerHour;
  785. //blocking
  786. if (request.TryGetQueryOrForm("enableBlocking", bool.Parse, out bool enableBlocking))
  787. {
  788. _dnsWebService.DnsServer.EnableBlocking = enableBlocking;
  789. if (_dnsWebService.DnsServer.EnableBlocking)
  790. {
  791. if (_temporaryDisableBlockingTimer is not null)
  792. _temporaryDisableBlockingTimer.Dispose();
  793. }
  794. }
  795. if (request.TryGetQueryOrForm("allowTxtBlockingReport", bool.Parse, out bool allowTxtBlockingReport))
  796. _dnsWebService.DnsServer.AllowTxtBlockingReport = allowTxtBlockingReport;
  797. if (request.TryGetQueryOrFormEnum("blockingType", out DnsServerBlockingType blockingType))
  798. _dnsWebService.DnsServer.BlockingType = blockingType;
  799. string customBlockingAddresses = request.QueryOrForm("customBlockingAddresses");
  800. if (customBlockingAddresses is not null)
  801. {
  802. if ((customBlockingAddresses.Length == 0) || customBlockingAddresses.Equals("false", StringComparison.OrdinalIgnoreCase))
  803. {
  804. _dnsWebService.DnsServer.CustomBlockingARecords = null;
  805. _dnsWebService.DnsServer.CustomBlockingAAAARecords = null;
  806. }
  807. else
  808. {
  809. string[] strAddresses = customBlockingAddresses.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  810. List<DnsARecordData> dnsARecords = new List<DnsARecordData>();
  811. List<DnsAAAARecordData> dnsAAAARecords = new List<DnsAAAARecordData>();
  812. foreach (string strAddress in strAddresses)
  813. {
  814. if (IPAddress.TryParse(strAddress, out IPAddress customAddress))
  815. {
  816. switch (customAddress.AddressFamily)
  817. {
  818. case AddressFamily.InterNetwork:
  819. dnsARecords.Add(new DnsARecordData(customAddress));
  820. break;
  821. case AddressFamily.InterNetworkV6:
  822. dnsAAAARecords.Add(new DnsAAAARecordData(customAddress));
  823. break;
  824. }
  825. }
  826. }
  827. _dnsWebService.DnsServer.CustomBlockingARecords = dnsARecords;
  828. _dnsWebService.DnsServer.CustomBlockingAAAARecords = dnsAAAARecords;
  829. }
  830. }
  831. string blockListUrls = request.QueryOrForm("blockListUrls");
  832. if (blockListUrls is not null)
  833. {
  834. if ((blockListUrls.Length == 0) || blockListUrls.Equals("false", StringComparison.OrdinalIgnoreCase))
  835. {
  836. _dnsWebService.DnsServer.BlockListZoneManager.AllowListUrls.Clear();
  837. _dnsWebService.DnsServer.BlockListZoneManager.BlockListUrls.Clear();
  838. _dnsWebService.DnsServer.BlockListZoneManager.Flush();
  839. }
  840. else
  841. {
  842. string[] blockListUrlList = blockListUrls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  843. if (oldWebServiceHttpPort != _dnsWebService._webServiceHttpPort)
  844. {
  845. for (int i = 0; i < blockListUrlList.Length; i++)
  846. {
  847. if (blockListUrlList[i].Contains("http://localhost:" + oldWebServiceHttpPort + "/blocklist.txt"))
  848. {
  849. blockListUrlList[i] = "http://localhost:" + _dnsWebService._webServiceHttpPort + "/blocklist.txt";
  850. blockListUrlsUpdated = true;
  851. break;
  852. }
  853. }
  854. }
  855. if (!blockListUrlsUpdated)
  856. {
  857. if (blockListUrlList.Length != (_dnsWebService.DnsServer.BlockListZoneManager.AllowListUrls.Count + _dnsWebService.DnsServer.BlockListZoneManager.BlockListUrls.Count))
  858. {
  859. blockListUrlsUpdated = true;
  860. }
  861. else
  862. {
  863. foreach (string strBlockListUrl in blockListUrlList)
  864. {
  865. if (strBlockListUrl.StartsWith('!'))
  866. {
  867. string strAllowListUrl = strBlockListUrl.Substring(1);
  868. if (!_dnsWebService.DnsServer.BlockListZoneManager.AllowListUrls.Contains(new Uri(strAllowListUrl)))
  869. {
  870. blockListUrlsUpdated = true;
  871. break;
  872. }
  873. }
  874. else
  875. {
  876. if (!_dnsWebService.DnsServer.BlockListZoneManager.BlockListUrls.Contains(new Uri(strBlockListUrl)))
  877. {
  878. blockListUrlsUpdated = true;
  879. break;
  880. }
  881. }
  882. }
  883. }
  884. }
  885. if (blockListUrlsUpdated)
  886. {
  887. _dnsWebService.DnsServer.BlockListZoneManager.AllowListUrls.Clear();
  888. _dnsWebService.DnsServer.BlockListZoneManager.BlockListUrls.Clear();
  889. foreach (string strBlockListUrl in blockListUrlList)
  890. {
  891. if (strBlockListUrl.StartsWith('!'))
  892. {
  893. Uri allowListUrl = new Uri(strBlockListUrl.Substring(1));
  894. if (!_dnsWebService.DnsServer.BlockListZoneManager.AllowListUrls.Contains(allowListUrl))
  895. _dnsWebService.DnsServer.BlockListZoneManager.AllowListUrls.Add(allowListUrl);
  896. }
  897. else
  898. {
  899. Uri blockListUrl = new Uri(strBlockListUrl);
  900. if (!_dnsWebService.DnsServer.BlockListZoneManager.BlockListUrls.Contains(blockListUrl))
  901. _dnsWebService.DnsServer.BlockListZoneManager.BlockListUrls.Add(blockListUrl);
  902. }
  903. }
  904. }
  905. }
  906. }
  907. if (request.TryGetQueryOrForm("blockListUpdateIntervalHours", int.Parse, out int blockListUpdateIntervalHours))
  908. {
  909. if ((blockListUpdateIntervalHours < 0) || (blockListUpdateIntervalHours > 168))
  910. throw new DnsWebServiceException("Parameter `blockListUpdateIntervalHours` must be between 1 hour and 168 hours (7 days) or 0 to disable automatic update.");
  911. _blockListUpdateIntervalHours = blockListUpdateIntervalHours;
  912. }
  913. //proxy & forwarders
  914. if (request.TryGetQueryOrFormEnum("proxyType", out NetProxyType proxyType))
  915. {
  916. if (proxyType == NetProxyType.None)
  917. {
  918. _dnsWebService.DnsServer.Proxy = null;
  919. }
  920. else
  921. {
  922. NetworkCredential credential = null;
  923. if (request.TryGetQueryOrForm("proxyUsername", out string proxyUsername))
  924. credential = new NetworkCredential(proxyUsername, request.QueryOrForm("proxyPassword"));
  925. _dnsWebService.DnsServer.Proxy = NetProxy.CreateProxy(proxyType, request.QueryOrForm("proxyAddress"), int.Parse(request.QueryOrForm("proxyPort")), credential);
  926. if (request.TryGetQueryOrForm("proxyBypass", out string proxyBypass))
  927. _dnsWebService.DnsServer.Proxy.BypassList = proxyBypass.Split(delegate (string value) { return new NetProxyBypassItem(value); }, ',');
  928. }
  929. }
  930. string strForwarders = request.QueryOrForm("forwarders");
  931. if (strForwarders is not null)
  932. {
  933. if ((strForwarders.Length == 0) || strForwarders.Equals("false", StringComparison.OrdinalIgnoreCase))
  934. {
  935. _dnsWebService.DnsServer.Forwarders = null;
  936. }
  937. else
  938. {
  939. DnsTransportProtocol forwarderProtocol = request.GetQueryOrFormEnum("forwarderProtocol", DnsTransportProtocol.Udp);
  940. switch (forwarderProtocol)
  941. {
  942. case DnsTransportProtocol.Udp:
  943. if (proxyType == NetProxyType.Http)
  944. throw new DnsWebServiceException("HTTP proxy server can transport only DNS-over-TCP, DNS-over-TLS, or DNS-over-HTTPS forwarder protocols. Use SOCKS5 proxy server for DNS-over-UDP or DNS-over-QUIC forwarder protocols.");
  945. break;
  946. case DnsTransportProtocol.HttpsJson:
  947. forwarderProtocol = DnsTransportProtocol.Https;
  948. break;
  949. case DnsTransportProtocol.Quic:
  950. DnsWebService.ValidateQuicSupport();
  951. if (proxyType == NetProxyType.Http)
  952. throw new DnsWebServiceException("HTTP proxy server can transport only DNS-over-TCP, DNS-over-TLS, or DNS-over-HTTPS forwarder protocols. Use SOCKS5 proxy server for DNS-over-UDP or DNS-over-QUIC forwarder protocols.");
  953. break;
  954. }
  955. _dnsWebService.DnsServer.Forwarders = strForwarders.Split(delegate (string value)
  956. {
  957. NameServerAddress forwarder = NameServerAddress.Parse(value);
  958. if (forwarder.Protocol != forwarderProtocol)
  959. forwarder = forwarder.ChangeProtocol(forwarderProtocol);
  960. return forwarder;
  961. }, ',');
  962. }
  963. }
  964. if (request.TryGetQueryOrForm("forwarderRetries", int.Parse, out int forwarderRetries))
  965. _dnsWebService.DnsServer.ForwarderRetries = forwarderRetries;
  966. if (request.TryGetQueryOrForm("forwarderTimeout", int.Parse, out int forwarderTimeout))
  967. _dnsWebService.DnsServer.ForwarderTimeout = forwarderTimeout;
  968. if (request.TryGetQueryOrForm("forwarderConcurrency", int.Parse, out int forwarderConcurrency))
  969. _dnsWebService.DnsServer.ForwarderConcurrency = forwarderConcurrency;
  970. //logging
  971. if (request.TryGetQueryOrForm("enableLogging", bool.Parse, out bool enableLogging))
  972. _dnsWebService._log.EnableLogging = enableLogging;
  973. if (request.TryGetQueryOrForm("logQueries", bool.Parse, out bool logQueries))
  974. _dnsWebService.DnsServer.QueryLogManager = logQueries ? _dnsWebService._log : null;
  975. if (request.TryGetQueryOrForm("useLocalTime", bool.Parse, out bool useLocalTime))
  976. _dnsWebService._log.UseLocalTime = useLocalTime;
  977. if (request.TryGetQueryOrForm("logFolder", out string logFolder))
  978. _dnsWebService._log.LogFolder = logFolder;
  979. if (request.TryGetQueryOrForm("maxLogFileDays", int.Parse, out int maxLogFileDays))
  980. _dnsWebService._log.MaxLogFileDays = maxLogFileDays;
  981. if (request.TryGetQueryOrForm("maxStatFileDays", int.Parse, out int maxStatFileDays))
  982. _dnsWebService.DnsServer.StatsManager.MaxStatFileDays = maxStatFileDays;
  983. //TLS actions
  984. if ((_dnsWebService._webServiceTlsCertificatePath is null) && (_dnsWebService._dnsTlsCertificatePath is null))
  985. _dnsWebService.StopTlsCertificateUpdateTimer();
  986. _dnsWebService.SelfSignedCertCheck(serverDomainChanged, true);
  987. if (_dnsWebService._webServiceEnableTls && string.IsNullOrEmpty(_dnsWebService._webServiceTlsCertificatePath) && !_dnsWebService._webServiceUseSelfSignedTlsCertificate)
  988. {
  989. //disable TLS
  990. _dnsWebService._webServiceEnableTls = false;
  991. restartWebService = true;
  992. }
  993. //blocklist timers
  994. if ((_blockListUpdateIntervalHours > 0) && ((_dnsWebService.DnsServer.BlockListZoneManager.AllowListUrls.Count + _dnsWebService.DnsServer.BlockListZoneManager.BlockListUrls.Count) > 0))
  995. {
  996. if (_blockListUpdateTimer is null)
  997. StartBlockListUpdateTimer();
  998. else if (blockListUrlsUpdated)
  999. ForceUpdateBlockLists();
  1000. }
  1001. else
  1002. {
  1003. StopBlockListUpdateTimer();
  1004. }
  1005. //save config
  1006. _dnsWebService.SaveConfigFile();
  1007. _dnsWebService._log.Save();
  1008. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] DNS Settings were updated successfully.");
  1009. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  1010. WriteDnsSettings(jsonWriter);
  1011. RestartService(restartDnsService, restartWebService);
  1012. }
  1013. public void GetTsigKeyNames(HttpContext context)
  1014. {
  1015. UserSession session = context.GetCurrentSession();
  1016. if (
  1017. !_dnsWebService._authManager.IsPermitted(PermissionSection.Settings, session.User, PermissionFlag.View) &&
  1018. !_dnsWebService._authManager.IsPermitted(PermissionSection.Zones, session.User, PermissionFlag.Modify)
  1019. )
  1020. {
  1021. throw new DnsWebServiceException("Access was denied.");
  1022. }
  1023. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  1024. jsonWriter.WritePropertyName("tsigKeyNames");
  1025. {
  1026. jsonWriter.WriteStartArray();
  1027. if (_dnsWebService.DnsServer.TsigKeys is not null)
  1028. {
  1029. foreach (KeyValuePair<string, TsigKey> tsigKey in _dnsWebService.DnsServer.TsigKeys)
  1030. jsonWriter.WriteStringValue(tsigKey.Key);
  1031. }
  1032. jsonWriter.WriteEndArray();
  1033. }
  1034. }
  1035. public async Task BackupSettingsAsync(HttpContext context)
  1036. {
  1037. UserSession session = context.GetCurrentSession();
  1038. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Settings, session.User, PermissionFlag.Delete))
  1039. throw new DnsWebServiceException("Access was denied.");
  1040. HttpRequest request = context.Request;
  1041. bool blockLists = request.GetQueryOrForm("blockLists", bool.Parse, false);
  1042. bool logs = request.GetQueryOrForm("logs", bool.Parse, false);
  1043. bool scopes = request.GetQueryOrForm("scopes", bool.Parse, false);
  1044. bool apps = request.GetQueryOrForm("apps", bool.Parse, false);
  1045. bool stats = request.GetQueryOrForm("stats", bool.Parse, false);
  1046. bool zones = request.GetQueryOrForm("zones", bool.Parse, false);
  1047. bool allowedZones = request.GetQueryOrForm("allowedZones", bool.Parse, false);
  1048. bool blockedZones = request.GetQueryOrForm("blockedZones", bool.Parse, false);
  1049. bool dnsSettings = request.GetQueryOrForm("dnsSettings", bool.Parse, false);
  1050. bool authConfig = request.GetQueryOrForm("authConfig", bool.Parse, false);
  1051. bool logSettings = request.GetQueryOrForm("logSettings", bool.Parse, false);
  1052. string tmpFile = Path.GetTempFileName();
  1053. try
  1054. {
  1055. using (FileStream backupZipStream = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
  1056. {
  1057. //create backup zip
  1058. using (ZipArchive backupZip = new ZipArchive(backupZipStream, ZipArchiveMode.Create, true, Encoding.UTF8))
  1059. {
  1060. if (blockLists)
  1061. {
  1062. string[] blockListFiles = Directory.GetFiles(Path.Combine(_dnsWebService._configFolder, "blocklists"), "*", SearchOption.TopDirectoryOnly);
  1063. foreach (string blockListFile in blockListFiles)
  1064. {
  1065. string entryName = "blocklists/" + Path.GetFileName(blockListFile);
  1066. backupZip.CreateEntryFromFile(blockListFile, entryName);
  1067. }
  1068. }
  1069. if (logs)
  1070. {
  1071. string[] logFiles = Directory.GetFiles(_dnsWebService._log.LogFolderAbsolutePath, "*.log", SearchOption.TopDirectoryOnly);
  1072. foreach (string logFile in logFiles)
  1073. {
  1074. string entryName = "logs/" + Path.GetFileName(logFile);
  1075. if (logFile.Equals(_dnsWebService._log.CurrentLogFile, StringComparison.OrdinalIgnoreCase))
  1076. {
  1077. await CreateBackupEntryFromFileAsync(backupZip, logFile, entryName);
  1078. }
  1079. else
  1080. {
  1081. backupZip.CreateEntryFromFile(logFile, entryName);
  1082. }
  1083. }
  1084. }
  1085. if (scopes)
  1086. {
  1087. string[] scopeFiles = Directory.GetFiles(Path.Combine(_dnsWebService._configFolder, "scopes"), "*.scope", SearchOption.TopDirectoryOnly);
  1088. foreach (string scopeFile in scopeFiles)
  1089. {
  1090. string entryName = "scopes/" + Path.GetFileName(scopeFile);
  1091. backupZip.CreateEntryFromFile(scopeFile, entryName);
  1092. }
  1093. }
  1094. if (apps)
  1095. {
  1096. string[] appFiles = Directory.GetFiles(Path.Combine(_dnsWebService._configFolder, "apps"), "*", SearchOption.AllDirectories);
  1097. foreach (string appFile in appFiles)
  1098. {
  1099. string entryName = appFile.Substring(_dnsWebService._configFolder.Length);
  1100. if (Path.DirectorySeparatorChar != '/')
  1101. entryName = entryName.Replace(Path.DirectorySeparatorChar, '/');
  1102. entryName = entryName.TrimStart('/');
  1103. await CreateBackupEntryFromFileAsync(backupZip, appFile, entryName);
  1104. }
  1105. }
  1106. if (stats)
  1107. {
  1108. string[] hourlyStatsFiles = Directory.GetFiles(Path.Combine(_dnsWebService._configFolder, "stats"), "*.stat", SearchOption.TopDirectoryOnly);
  1109. foreach (string hourlyStatsFile in hourlyStatsFiles)
  1110. {
  1111. string entryName = "stats/" + Path.GetFileName(hourlyStatsFile);
  1112. backupZip.CreateEntryFromFile(hourlyStatsFile, entryName);
  1113. }
  1114. string[] dailyStatsFiles = Directory.GetFiles(Path.Combine(_dnsWebService._configFolder, "stats"), "*.dstat", SearchOption.TopDirectoryOnly);
  1115. foreach (string dailyStatsFile in dailyStatsFiles)
  1116. {
  1117. string entryName = "stats/" + Path.GetFileName(dailyStatsFile);
  1118. backupZip.CreateEntryFromFile(dailyStatsFile, entryName);
  1119. }
  1120. }
  1121. if (zones)
  1122. {
  1123. string[] zoneFiles = Directory.GetFiles(Path.Combine(_dnsWebService._configFolder, "zones"), "*.zone", SearchOption.TopDirectoryOnly);
  1124. foreach (string zoneFile in zoneFiles)
  1125. {
  1126. string entryName = "zones/" + Path.GetFileName(zoneFile);
  1127. backupZip.CreateEntryFromFile(zoneFile, entryName);
  1128. }
  1129. }
  1130. if (allowedZones)
  1131. {
  1132. string allowedZonesFile = Path.Combine(_dnsWebService._configFolder, "allowed.config");
  1133. if (File.Exists(allowedZonesFile))
  1134. backupZip.CreateEntryFromFile(allowedZonesFile, "allowed.config");
  1135. }
  1136. if (blockedZones)
  1137. {
  1138. string blockedZonesFile = Path.Combine(_dnsWebService._configFolder, "blocked.config");
  1139. if (File.Exists(blockedZonesFile))
  1140. backupZip.CreateEntryFromFile(blockedZonesFile, "blocked.config");
  1141. }
  1142. if (dnsSettings)
  1143. {
  1144. string dnsSettingsFile = Path.Combine(_dnsWebService._configFolder, "dns.config");
  1145. if (File.Exists(dnsSettingsFile))
  1146. backupZip.CreateEntryFromFile(dnsSettingsFile, "dns.config");
  1147. //backup web service cert
  1148. {
  1149. string webServiceTlsCertificatePath = _dnsWebService.ConvertToAbsolutePath(_dnsWebService._webServiceTlsCertificatePath);
  1150. if (File.Exists(webServiceTlsCertificatePath) && webServiceTlsCertificatePath.StartsWith(_dnsWebService._configFolder, Environment.OSVersion.Platform == PlatformID.Win32NT ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
  1151. {
  1152. string entryName = _dnsWebService.ConvertToRelativePath(webServiceTlsCertificatePath).Replace('\\', '/');
  1153. backupZip.CreateEntryFromFile(webServiceTlsCertificatePath, entryName);
  1154. }
  1155. }
  1156. //backup optional protocols cert
  1157. {
  1158. string dnsTlsCertificatePath = _dnsWebService.ConvertToAbsolutePath(_dnsWebService._dnsTlsCertificatePath);
  1159. if (File.Exists(dnsTlsCertificatePath) && dnsTlsCertificatePath.StartsWith(_dnsWebService._configFolder, Environment.OSVersion.Platform == PlatformID.Win32NT ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
  1160. {
  1161. string entryName = _dnsWebService.ConvertToRelativePath(dnsTlsCertificatePath).Replace('\\', '/');
  1162. backupZip.CreateEntryFromFile(dnsTlsCertificatePath, entryName);
  1163. }
  1164. }
  1165. }
  1166. if (authConfig)
  1167. {
  1168. string authSettingsFile = Path.Combine(_dnsWebService._configFolder, "auth.config");
  1169. if (File.Exists(authSettingsFile))
  1170. backupZip.CreateEntryFromFile(authSettingsFile, "auth.config");
  1171. }
  1172. if (logSettings)
  1173. {
  1174. string logSettingsFile = Path.Combine(_dnsWebService._configFolder, "log.config");
  1175. if (File.Exists(logSettingsFile))
  1176. backupZip.CreateEntryFromFile(logSettingsFile, "log.config");
  1177. }
  1178. }
  1179. //send zip file
  1180. backupZipStream.Position = 0;
  1181. HttpResponse response = context.Response;
  1182. response.ContentType = "application/zip";
  1183. response.ContentLength = backupZipStream.Length;
  1184. response.Headers.ContentDisposition = "attachment;filename=" + _dnsWebService.DnsServer.ServerDomain + DateTime.UtcNow.ToString("_yyyy-MM-dd_HH-mm-ss") + "_backup.zip";
  1185. using (Stream output = response.Body)
  1186. {
  1187. await backupZipStream.CopyToAsync(output);
  1188. }
  1189. }
  1190. }
  1191. catch (Exception ex)
  1192. {
  1193. _dnsWebService._log.Write(ex);
  1194. throw;
  1195. }
  1196. finally
  1197. {
  1198. try
  1199. {
  1200. File.Delete(tmpFile);
  1201. }
  1202. catch (Exception ex)
  1203. {
  1204. _dnsWebService._log.Write(ex);
  1205. }
  1206. }
  1207. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] Settings backup zip file was exported.");
  1208. }
  1209. public async Task RestoreSettingsAsync(HttpContext context)
  1210. {
  1211. UserSession session = context.GetCurrentSession();
  1212. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Settings, session.User, PermissionFlag.Delete))
  1213. throw new DnsWebServiceException("Access was denied.");
  1214. HttpRequest request = context.Request;
  1215. bool blockLists = request.GetQueryOrForm("blockLists", bool.Parse, false);
  1216. bool logs = request.GetQueryOrForm("logs", bool.Parse, false);
  1217. bool scopes = request.GetQueryOrForm("scopes", bool.Parse, false);
  1218. bool apps = request.GetQueryOrForm("apps", bool.Parse, false);
  1219. bool stats = request.GetQueryOrForm("stats", bool.Parse, false);
  1220. bool zones = request.GetQueryOrForm("zones", bool.Parse, false);
  1221. bool allowedZones = request.GetQueryOrForm("allowedZones", bool.Parse, false);
  1222. bool blockedZones = request.GetQueryOrForm("blockedZones", bool.Parse, false);
  1223. bool dnsSettings = request.GetQueryOrForm("dnsSettings", bool.Parse, false);
  1224. bool authConfig = request.GetQueryOrForm("authConfig", bool.Parse, false);
  1225. bool logSettings = request.GetQueryOrForm("logSettings", bool.Parse, false);
  1226. bool deleteExistingFiles = request.GetQueryOrForm("deleteExistingFiles", bool.Parse, false);
  1227. if (!request.HasFormContentType || (request.Form.Files.Count == 0))
  1228. throw new DnsWebServiceException("DNS backup zip file is missing.");
  1229. //write to temp file
  1230. string tmpFile = Path.GetTempFileName();
  1231. try
  1232. {
  1233. using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
  1234. {
  1235. await request.Form.Files[0].CopyToAsync(fS);
  1236. fS.Position = 0;
  1237. using (ZipArchive backupZip = new ZipArchive(fS, ZipArchiveMode.Read, false, Encoding.UTF8))
  1238. {
  1239. if (logSettings || logs)
  1240. {
  1241. //stop logging
  1242. _dnsWebService._log.StopLogging();
  1243. }
  1244. try
  1245. {
  1246. if (logSettings)
  1247. {
  1248. ZipArchiveEntry entry = backupZip.GetEntry("log.config");
  1249. if (entry is not null)
  1250. entry.ExtractToFile(Path.Combine(_dnsWebService._configFolder, entry.Name), true);
  1251. //reload config
  1252. _dnsWebService._log.LoadConfig();
  1253. }
  1254. if (logs)
  1255. {
  1256. if (deleteExistingFiles)
  1257. {
  1258. //delete existing log files
  1259. string[] logFiles = Directory.GetFiles(_dnsWebService._log.LogFolderAbsolutePath, "*.log", SearchOption.TopDirectoryOnly);
  1260. foreach (string logFile in logFiles)
  1261. {
  1262. File.Delete(logFile);
  1263. }
  1264. }
  1265. //extract log files from backup
  1266. foreach (ZipArchiveEntry entry in backupZip.Entries)
  1267. {
  1268. if (entry.FullName.StartsWith("logs/"))
  1269. entry.ExtractToFile(Path.Combine(_dnsWebService._log.LogFolderAbsolutePath, entry.Name), true);
  1270. }
  1271. }
  1272. }
  1273. finally
  1274. {
  1275. if (logSettings || logs)
  1276. {
  1277. //start logging
  1278. if (_dnsWebService._log.EnableLogging)
  1279. _dnsWebService._log.StartLogging();
  1280. }
  1281. }
  1282. if (authConfig)
  1283. {
  1284. ZipArchiveEntry entry = backupZip.GetEntry("auth.config");
  1285. if (entry is not null)
  1286. entry.ExtractToFile(Path.Combine(_dnsWebService._configFolder, entry.Name), true);
  1287. //reload auth config
  1288. _dnsWebService._authManager.LoadConfigFile(session);
  1289. }
  1290. if (blockLists)
  1291. {
  1292. if (deleteExistingFiles)
  1293. {
  1294. //delete existing block list files
  1295. string[] blockListFiles = Directory.GetFiles(Path.Combine(_dnsWebService._configFolder, "blocklists"), "*", SearchOption.TopDirectoryOnly);
  1296. foreach (string blockListFile in blockListFiles)
  1297. {
  1298. File.Delete(blockListFile);
  1299. }
  1300. }
  1301. //extract block list files from backup
  1302. foreach (ZipArchiveEntry entry in backupZip.Entries)
  1303. {
  1304. if (entry.FullName.StartsWith("blocklists/"))
  1305. entry.ExtractToFile(Path.Combine(_dnsWebService._configFolder, "blocklists", entry.Name), true);
  1306. }
  1307. }
  1308. if (dnsSettings)
  1309. {
  1310. ZipArchiveEntry entry = backupZip.GetEntry("dns.config");
  1311. if (entry is not null)
  1312. entry.ExtractToFile(Path.Combine(_dnsWebService._configFolder, entry.Name), true);
  1313. //extract any certs
  1314. foreach (ZipArchiveEntry certEntry in backupZip.Entries)
  1315. {
  1316. if (certEntry.FullName.StartsWith("apps/"))
  1317. continue;
  1318. if (certEntry.FullName.EndsWith(".pfx", StringComparison.OrdinalIgnoreCase))
  1319. {
  1320. string certFile = Path.Combine(_dnsWebService._configFolder, certEntry.FullName);
  1321. Directory.CreateDirectory(Path.GetDirectoryName(certFile));
  1322. certEntry.ExtractToFile(certFile, true);
  1323. }
  1324. }
  1325. //reload settings and block list zone
  1326. _dnsWebService.LoadConfigFile();
  1327. if ((_dnsWebService.DnsServer.BlockListZoneManager.AllowListUrls.Count + _dnsWebService.DnsServer.BlockListZoneManager.BlockListUrls.Count) > 0)
  1328. {
  1329. ThreadPool.QueueUserWorkItem(delegate (object state)
  1330. {
  1331. try
  1332. {
  1333. _dnsWebService.DnsServer.BlockListZoneManager.LoadBlockLists();
  1334. }
  1335. catch (Exception ex)
  1336. {
  1337. _dnsWebService._log.Write(ex);
  1338. }
  1339. });
  1340. if (_blockListUpdateIntervalHours > 0)
  1341. StartBlockListUpdateTimer();
  1342. else
  1343. StopBlockListUpdateTimer();
  1344. }
  1345. else
  1346. {
  1347. _dnsWebService.DnsServer.BlockListZoneManager.Flush();
  1348. StopBlockListUpdateTimer();
  1349. }
  1350. }
  1351. if (apps)
  1352. {
  1353. //unload apps
  1354. _dnsWebService.DnsServer.DnsApplicationManager.UnloadAllApplications();
  1355. if (deleteExistingFiles)
  1356. {
  1357. //delete existing apps
  1358. string appFolder = Path.Combine(_dnsWebService._configFolder, "apps");
  1359. if (Directory.Exists(appFolder))
  1360. Directory.Delete(appFolder, true);
  1361. //create apps folder
  1362. Directory.CreateDirectory(appFolder);
  1363. }
  1364. //extract apps files from backup
  1365. foreach (ZipArchiveEntry entry in backupZip.Entries)
  1366. {
  1367. if (entry.FullName.StartsWith("apps/"))
  1368. {
  1369. string entryPath = entry.FullName;
  1370. if (Path.DirectorySeparatorChar != '/')
  1371. entryPath = entryPath.Replace('/', '\\');
  1372. string filePath = Path.Combine(_dnsWebService._configFolder, entryPath);
  1373. Directory.CreateDirectory(Path.GetDirectoryName(filePath));
  1374. entry.ExtractToFile(filePath, true);
  1375. }
  1376. }
  1377. //reload apps
  1378. _dnsWebService.DnsServer.DnsApplicationManager.LoadAllApplications();
  1379. }
  1380. if (zones)
  1381. {
  1382. if (deleteExistingFiles)
  1383. {
  1384. //delete existing zone files
  1385. string[] zoneFiles = Directory.GetFiles(Path.Combine(_dnsWebService._configFolder, "zones"), "*.zone", SearchOption.TopDirectoryOnly);
  1386. foreach (string zoneFile in zoneFiles)
  1387. {
  1388. File.Delete(zoneFile);
  1389. }
  1390. }
  1391. //extract zone files from backup
  1392. foreach (ZipArchiveEntry entry in backupZip.Entries)
  1393. {
  1394. if (entry.FullName.StartsWith("zones/"))
  1395. entry.ExtractToFile(Path.Combine(_dnsWebService._configFolder, "zones", entry.Name), true);
  1396. }
  1397. //reload zones
  1398. _dnsWebService.DnsServer.AuthZoneManager.LoadAllZoneFiles();
  1399. _dnsWebService.InspectAndFixZonePermissions();
  1400. }
  1401. if (allowedZones)
  1402. {
  1403. ZipArchiveEntry entry = backupZip.GetEntry("allowed.config");
  1404. if (entry == null)
  1405. {
  1406. string fileName = Path.Combine(_dnsWebService._configFolder, "allowed.config");
  1407. if (File.Exists(fileName))
  1408. File.Delete(fileName);
  1409. }
  1410. else
  1411. {
  1412. entry.ExtractToFile(Path.Combine(_dnsWebService._configFolder, entry.Name), true);
  1413. }
  1414. //reload
  1415. _dnsWebService.DnsServer.AllowedZoneManager.LoadAllowedZoneFile();
  1416. }
  1417. if (blockedZones)
  1418. {
  1419. ZipArchiveEntry entry = backupZip.GetEntry("blocked.config");
  1420. if (entry == null)
  1421. {
  1422. string fileName = Path.Combine(_dnsWebService._configFolder, "allowed.config");
  1423. if (File.Exists(fileName))
  1424. File.Delete(fileName);
  1425. }
  1426. else
  1427. {
  1428. entry.ExtractToFile(Path.Combine(_dnsWebService._configFolder, entry.Name), true);
  1429. }
  1430. //reload
  1431. _dnsWebService.DnsServer.BlockedZoneManager.LoadBlockedZoneFile();
  1432. }
  1433. if (scopes)
  1434. {
  1435. //stop dhcp server
  1436. _dnsWebService.DhcpServer.Stop();
  1437. try
  1438. {
  1439. if (deleteExistingFiles)
  1440. {
  1441. //delete existing scope files
  1442. string[] scopeFiles = Directory.GetFiles(Path.Combine(_dnsWebService._configFolder, "scopes"), "*.scope", SearchOption.TopDirectoryOnly);
  1443. foreach (string scopeFile in scopeFiles)
  1444. {
  1445. File.Delete(scopeFile);
  1446. }
  1447. }
  1448. //extract scope files from backup
  1449. foreach (ZipArchiveEntry entry in backupZip.Entries)
  1450. {
  1451. if (entry.FullName.StartsWith("scopes/"))
  1452. entry.ExtractToFile(Path.Combine(_dnsWebService._configFolder, "scopes", entry.Name), true);
  1453. }
  1454. }
  1455. finally
  1456. {
  1457. //start dhcp server
  1458. _dnsWebService.DhcpServer.Start();
  1459. }
  1460. }
  1461. if (stats)
  1462. {
  1463. if (deleteExistingFiles)
  1464. {
  1465. //delete existing stats files
  1466. string[] hourlyStatsFiles = Directory.GetFiles(Path.Combine(_dnsWebService._configFolder, "stats"), "*.stat", SearchOption.TopDirectoryOnly);
  1467. foreach (string hourlyStatsFile in hourlyStatsFiles)
  1468. {
  1469. File.Delete(hourlyStatsFile);
  1470. }
  1471. string[] dailyStatsFiles = Directory.GetFiles(Path.Combine(_dnsWebService._configFolder, "stats"), "*.dstat", SearchOption.TopDirectoryOnly);
  1472. foreach (string dailyStatsFile in dailyStatsFiles)
  1473. {
  1474. File.Delete(dailyStatsFile);
  1475. }
  1476. }
  1477. //extract stats files from backup
  1478. foreach (ZipArchiveEntry entry in backupZip.Entries)
  1479. {
  1480. if (entry.FullName.StartsWith("stats/"))
  1481. entry.ExtractToFile(Path.Combine(_dnsWebService._configFolder, "stats", entry.Name), true);
  1482. }
  1483. //reload stats
  1484. _dnsWebService.DnsServer.StatsManager.ReloadStats();
  1485. }
  1486. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] Settings backup zip file was restored.");
  1487. }
  1488. }
  1489. }
  1490. catch (Exception ex)
  1491. {
  1492. _dnsWebService._log.Write(ex);
  1493. throw;
  1494. }
  1495. finally
  1496. {
  1497. try
  1498. {
  1499. File.Delete(tmpFile);
  1500. }
  1501. catch (Exception ex)
  1502. {
  1503. _dnsWebService._log.Write(ex);
  1504. }
  1505. }
  1506. if (dnsSettings)
  1507. RestartService(true, true);
  1508. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  1509. WriteDnsSettings(jsonWriter);
  1510. }
  1511. public void ForceUpdateBlockLists(HttpContext context)
  1512. {
  1513. UserSession session = context.GetCurrentSession();
  1514. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Settings, session.User, PermissionFlag.Modify))
  1515. throw new DnsWebServiceException("Access was denied.");
  1516. ForceUpdateBlockLists();
  1517. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] Block list update was triggered.");
  1518. }
  1519. public void TemporaryDisableBlocking(HttpContext context)
  1520. {
  1521. UserSession session = context.GetCurrentSession();
  1522. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Settings, session.User, PermissionFlag.Modify))
  1523. throw new DnsWebServiceException("Access was denied.");
  1524. int minutes = context.Request.GetQueryOrForm("minutes", int.Parse);
  1525. Timer temporaryDisableBlockingTimer = _temporaryDisableBlockingTimer;
  1526. if (temporaryDisableBlockingTimer is not null)
  1527. temporaryDisableBlockingTimer.Dispose();
  1528. Timer newTemporaryDisableBlockingTimer = new Timer(delegate (object state)
  1529. {
  1530. try
  1531. {
  1532. _dnsWebService.DnsServer.EnableBlocking = true;
  1533. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] Blocking was enabled after " + minutes + " minute(s) being temporarily disabled.");
  1534. }
  1535. catch (Exception ex)
  1536. {
  1537. _dnsWebService._log.Write(ex);
  1538. }
  1539. });
  1540. Timer originalTimer = Interlocked.CompareExchange(ref _temporaryDisableBlockingTimer, newTemporaryDisableBlockingTimer, temporaryDisableBlockingTimer);
  1541. if (ReferenceEquals(originalTimer, temporaryDisableBlockingTimer))
  1542. {
  1543. newTemporaryDisableBlockingTimer.Change(minutes * 60 * 1000, Timeout.Infinite);
  1544. _dnsWebService.DnsServer.EnableBlocking = false;
  1545. _temporaryDisableBlockingTill = DateTime.UtcNow.AddMinutes(minutes);
  1546. _dnsWebService._log.Write(context.GetRemoteEndPoint(), "[" + session.User.Username + "] Blocking was temporarily disabled for " + minutes + " minute(s).");
  1547. }
  1548. else
  1549. {
  1550. newTemporaryDisableBlockingTimer.Dispose();
  1551. }
  1552. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  1553. jsonWriter.WriteString("temporaryDisableBlockingTill", _temporaryDisableBlockingTill);
  1554. }
  1555. #endregion
  1556. #region properties
  1557. public DateTime BlockListLastUpdatedOn
  1558. {
  1559. get { return _blockListLastUpdatedOn; }
  1560. set { _blockListLastUpdatedOn = value; }
  1561. }
  1562. public int BlockListUpdateIntervalHours
  1563. {
  1564. get { return _blockListUpdateIntervalHours; }
  1565. set { _blockListUpdateIntervalHours = value; }
  1566. }
  1567. #endregion
  1568. }
  1569. }