WebServiceSettingsApi.cs 85 KB

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