DnsWebService.cs 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341
  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.Dhcp;
  17. using DnsServerCore.Dns;
  18. using DnsServerCore.Dns.ZoneManagers;
  19. using DnsServerCore.Dns.Zones;
  20. using Microsoft.AspNetCore.Builder;
  21. using Microsoft.AspNetCore.Connections;
  22. using Microsoft.AspNetCore.Diagnostics;
  23. using Microsoft.AspNetCore.Hosting;
  24. using Microsoft.AspNetCore.Http;
  25. using Microsoft.AspNetCore.Server.Kestrel.Core;
  26. using Microsoft.AspNetCore.Server.Kestrel.Https;
  27. using Microsoft.AspNetCore.StaticFiles;
  28. using Microsoft.Extensions.FileProviders;
  29. using Microsoft.Extensions.Logging;
  30. using System;
  31. using System.Collections.Generic;
  32. using System.IO;
  33. using System.Net;
  34. using System.Net.Quic;
  35. using System.Net.Sockets;
  36. using System.Reflection;
  37. using System.Security.Cryptography;
  38. using System.Security.Cryptography.X509Certificates;
  39. using System.Text;
  40. using System.Text.Json;
  41. using System.Threading;
  42. using System.Threading.Tasks;
  43. using TechnitiumLibrary;
  44. using TechnitiumLibrary.IO;
  45. using TechnitiumLibrary.Net;
  46. using TechnitiumLibrary.Net.Dns;
  47. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  48. using TechnitiumLibrary.Net.Proxy;
  49. namespace DnsServerCore
  50. {
  51. public sealed class DnsWebService : IAsyncDisposable, IDisposable
  52. {
  53. #region variables
  54. internal readonly Version _currentVersion;
  55. readonly string _appFolder;
  56. internal readonly string _configFolder;
  57. internal readonly LogManager _log;
  58. internal readonly AuthManager _authManager;
  59. readonly WebServiceApi _api;
  60. readonly WebServiceDashboardApi _dashboardApi;
  61. internal readonly WebServiceZonesApi _zonesApi;
  62. readonly WebServiceOtherZonesApi _otherZonesApi;
  63. internal readonly WebServiceAppsApi _appsApi;
  64. readonly WebServiceSettingsApi _settingsApi;
  65. readonly WebServiceDhcpApi _dhcpApi;
  66. readonly WebServiceAuthApi _authApi;
  67. readonly WebServiceLogsApi _logsApi;
  68. WebApplication _webService;
  69. X509Certificate2 _webServiceTlsCertificate;
  70. DnsServer _dnsServer;
  71. DhcpServer _dhcpServer;
  72. //web service
  73. internal IReadOnlyList<IPAddress> _webServiceLocalAddresses = new IPAddress[] { IPAddress.Any, IPAddress.IPv6Any };
  74. internal int _webServiceHttpPort = 5380;
  75. internal int _webServiceTlsPort = 53443;
  76. internal bool _webServiceEnableTls;
  77. internal bool _webServiceHttpToTlsRedirect;
  78. internal bool _webServiceUseSelfSignedTlsCertificate;
  79. internal string _webServiceTlsCertificatePath;
  80. internal string _webServiceTlsCertificatePassword;
  81. DateTime _webServiceTlsCertificateLastModifiedOn;
  82. //optional protocols
  83. internal string _dnsTlsCertificatePath;
  84. internal string _dnsTlsCertificatePassword;
  85. DateTime _dnsTlsCertificateLastModifiedOn;
  86. //cache
  87. internal bool _saveCache;
  88. Timer _tlsCertificateUpdateTimer;
  89. const int TLS_CERTIFICATE_UPDATE_TIMER_INITIAL_INTERVAL = 60000;
  90. const int TLS_CERTIFICATE_UPDATE_TIMER_INTERVAL = 60000;
  91. List<string> _configDisabledZones;
  92. #endregion
  93. #region constructor
  94. public DnsWebService(string configFolder = null, Uri updateCheckUri = null, Uri appStoreUri = null)
  95. {
  96. Assembly assembly = Assembly.GetExecutingAssembly();
  97. _currentVersion = assembly.GetName().Version;
  98. _appFolder = Path.GetDirectoryName(assembly.Location);
  99. if (configFolder is null)
  100. _configFolder = Path.Combine(_appFolder, "config");
  101. else
  102. _configFolder = configFolder;
  103. Directory.CreateDirectory(_configFolder);
  104. Directory.CreateDirectory(Path.Combine(_configFolder, "blocklists"));
  105. _log = new LogManager(_configFolder);
  106. _authManager = new AuthManager(_configFolder, _log);
  107. _api = new WebServiceApi(this, updateCheckUri);
  108. _dashboardApi = new WebServiceDashboardApi(this);
  109. _zonesApi = new WebServiceZonesApi(this);
  110. _otherZonesApi = new WebServiceOtherZonesApi(this);
  111. _appsApi = new WebServiceAppsApi(this, appStoreUri);
  112. _settingsApi = new WebServiceSettingsApi(this);
  113. _dhcpApi = new WebServiceDhcpApi(this);
  114. _authApi = new WebServiceAuthApi(this);
  115. _logsApi = new WebServiceLogsApi(this);
  116. }
  117. #endregion
  118. #region IDisposable
  119. bool _disposed;
  120. public async ValueTask DisposeAsync()
  121. {
  122. if (_disposed)
  123. return;
  124. await StopAsync();
  125. if (_appsApi is not null)
  126. _appsApi.Dispose();
  127. if (_settingsApi is not null)
  128. _settingsApi.Dispose();
  129. if (_authManager is not null)
  130. _authManager.Dispose();
  131. if (_log is not null)
  132. _log.Dispose();
  133. _disposed = true;
  134. }
  135. public void Dispose()
  136. {
  137. DisposeAsync().Sync();
  138. }
  139. #endregion
  140. #region server version
  141. internal string GetServerVersion()
  142. {
  143. return GetCleanVersion(_currentVersion);
  144. }
  145. internal static string GetCleanVersion(Version version)
  146. {
  147. string strVersion = version.Major + "." + version.Minor;
  148. if (version.Build > 0)
  149. strVersion += "." + version.Build;
  150. if (version.Revision > 0)
  151. strVersion += "." + version.Revision;
  152. return strVersion;
  153. }
  154. #endregion
  155. #region web service
  156. internal async Task TryStartWebServiceAsync()
  157. {
  158. try
  159. {
  160. _webServiceLocalAddresses = DnsServer.GetValidKestralLocalAddresses(_webServiceLocalAddresses);
  161. await StartWebServiceAsync(false);
  162. }
  163. catch (Exception ex)
  164. {
  165. _log.Write("Web Service failed to start: " + ex.ToString());
  166. _log.Write("Attempting to start Web Service on ANY (0.0.0.0) fallback address...");
  167. try
  168. {
  169. _webServiceLocalAddresses = new IPAddress[] { IPAddress.Any };
  170. await StartWebServiceAsync(false);
  171. }
  172. catch (Exception ex2)
  173. {
  174. _log.Write("Web Service failed to start: " + ex2.ToString());
  175. _log.Write("Attempting to start Web Service on loopback (127.0.0.1) fallback address...");
  176. _webServiceLocalAddresses = new IPAddress[] { IPAddress.Loopback };
  177. await StartWebServiceAsync(true);
  178. }
  179. }
  180. }
  181. private async Task StartWebServiceAsync(bool safeMode)
  182. {
  183. WebApplicationBuilder builder = WebApplication.CreateBuilder();
  184. builder.Environment.ContentRootFileProvider = new PhysicalFileProvider(_appFolder)
  185. {
  186. UseActivePolling = true,
  187. UsePollingFileWatcher = true
  188. };
  189. builder.Environment.WebRootFileProvider = new PhysicalFileProvider(Path.Combine(_appFolder, "www"))
  190. {
  191. UseActivePolling = true,
  192. UsePollingFileWatcher = true
  193. };
  194. builder.WebHost.ConfigureKestrel(delegate (WebHostBuilderContext context, KestrelServerOptions serverOptions)
  195. {
  196. //http
  197. foreach (IPAddress webServiceLocalAddress in _webServiceLocalAddresses)
  198. serverOptions.Listen(webServiceLocalAddress, _webServiceHttpPort);
  199. //https
  200. if (!safeMode && _webServiceEnableTls && (_webServiceTlsCertificate is not null))
  201. {
  202. serverOptions.ConfigureHttpsDefaults(delegate (HttpsConnectionAdapterOptions configureOptions)
  203. {
  204. configureOptions.ServerCertificateSelector = delegate (ConnectionContext context, string dnsName)
  205. {
  206. return _webServiceTlsCertificate;
  207. };
  208. });
  209. foreach (IPAddress webServiceLocalAddress in _webServiceLocalAddresses)
  210. {
  211. serverOptions.Listen(webServiceLocalAddress, _webServiceTlsPort, delegate (ListenOptions listenOptions)
  212. {
  213. listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
  214. listenOptions.UseHttps();
  215. });
  216. }
  217. }
  218. serverOptions.AddServerHeader = false;
  219. serverOptions.Limits.MaxRequestBodySize = null;
  220. });
  221. builder.Logging.ClearProviders();
  222. _webService = builder.Build();
  223. if (_webServiceHttpToTlsRedirect && !safeMode && _webServiceEnableTls && (_webServiceTlsCertificate is not null))
  224. _webService.UseHttpsRedirection();
  225. _webService.UseDefaultFiles();
  226. _webService.UseStaticFiles(new StaticFileOptions()
  227. {
  228. OnPrepareResponse = delegate (StaticFileResponseContext ctx)
  229. {
  230. ctx.Context.Response.Headers.Add("X-Robots-Tag", "noindex, nofollow");
  231. ctx.Context.Response.Headers.Add("Cache-Control", "private, max-age=300");
  232. }
  233. });
  234. ConfigureWebServiceRoutes();
  235. try
  236. {
  237. await _webService.StartAsync();
  238. foreach (IPAddress webServiceLocalAddress in _webServiceLocalAddresses)
  239. {
  240. _log?.Write(new IPEndPoint(webServiceLocalAddress, _webServiceHttpPort), "Http", "Web Service was bound successfully.");
  241. if (!safeMode && _webServiceEnableTls && (_webServiceTlsCertificate is not null))
  242. _log?.Write(new IPEndPoint(webServiceLocalAddress, _webServiceHttpPort), "Https", "Web Service was bound successfully.");
  243. }
  244. }
  245. catch
  246. {
  247. await StopWebServiceAsync();
  248. foreach (IPAddress webServiceLocalAddress in _webServiceLocalAddresses)
  249. {
  250. _log?.Write(new IPEndPoint(webServiceLocalAddress, _webServiceHttpPort), "Http", "Web Service failed to bind.");
  251. if (!safeMode && _webServiceEnableTls && (_webServiceTlsCertificate is not null))
  252. _log?.Write(new IPEndPoint(webServiceLocalAddress, _webServiceHttpPort), "Https", "Web Service failed to bind.");
  253. }
  254. throw;
  255. }
  256. }
  257. internal async Task StopWebServiceAsync()
  258. {
  259. if (_webService is not null)
  260. {
  261. await _webService.DisposeAsync();
  262. _webService = null;
  263. }
  264. }
  265. private void ConfigureWebServiceRoutes()
  266. {
  267. _webService.UseExceptionHandler(WebServiceExceptionHandler);
  268. _webService.Use(WebServiceApiMiddleware);
  269. _webService.UseRouting();
  270. //user auth
  271. _webService.MapGetAndPost("/api/user/login", delegate (HttpContext context) { return _authApi.LoginAsync(context, UserSessionType.Standard); });
  272. _webService.MapGetAndPost("/api/user/createToken", delegate (HttpContext context) { return _authApi.LoginAsync(context, UserSessionType.ApiToken); });
  273. _webService.MapGetAndPost("/api/user/logout", _authApi.Logout);
  274. //user
  275. _webService.MapGetAndPost("/api/user/session/get", _authApi.GetCurrentSessionDetails);
  276. _webService.MapGetAndPost("/api/user/session/delete", delegate (HttpContext context) { _authApi.DeleteSession(context, false); });
  277. _webService.MapGetAndPost("/api/user/changePassword", _authApi.ChangePassword);
  278. _webService.MapGetAndPost("/api/user/profile/get", _authApi.GetProfile);
  279. _webService.MapGetAndPost("/api/user/profile/set", _authApi.SetProfile);
  280. _webService.MapGetAndPost("/api/user/checkForUpdate", _api.CheckForUpdateAsync);
  281. //dashboard
  282. _webService.MapGetAndPost("/api/dashboard/stats/get", _dashboardApi.GetStats);
  283. _webService.MapGetAndPost("/api/dashboard/stats/getTop", _dashboardApi.GetTopStats);
  284. _webService.MapGetAndPost("/api/dashboard/stats/deleteAll", _logsApi.DeleteAllStats);
  285. //zones
  286. _webService.MapGetAndPost("/api/zones/list", _zonesApi.ListZones);
  287. _webService.MapGetAndPost("/api/zones/create", _zonesApi.CreateZoneAsync);
  288. _webService.MapGetAndPost("/api/zones/enable", _zonesApi.EnableZone);
  289. _webService.MapGetAndPost("/api/zones/disable", _zonesApi.DisableZone);
  290. _webService.MapGetAndPost("/api/zones/delete", _zonesApi.DeleteZone);
  291. _webService.MapGetAndPost("/api/zones/resync", _zonesApi.ResyncZone);
  292. _webService.MapGetAndPost("/api/zones/options/get", _zonesApi.GetZoneOptions);
  293. _webService.MapGetAndPost("/api/zones/options/set", _zonesApi.SetZoneOptions);
  294. _webService.MapGetAndPost("/api/zones/permissions/get", delegate (HttpContext context) { _authApi.GetPermissionDetails(context, PermissionSection.Zones); });
  295. _webService.MapGetAndPost("/api/zones/permissions/set", delegate (HttpContext context) { _authApi.SetPermissionsDetails(context, PermissionSection.Zones); });
  296. _webService.MapGetAndPost("/api/zones/dnssec/sign", _zonesApi.SignPrimaryZone);
  297. _webService.MapGetAndPost("/api/zones/dnssec/unsign", _zonesApi.UnsignPrimaryZone);
  298. _webService.MapGetAndPost("/api/zones/dnssec/properties/get", _zonesApi.GetPrimaryZoneDnssecProperties);
  299. _webService.MapGetAndPost("/api/zones/dnssec/properties/convertToNSEC", _zonesApi.ConvertPrimaryZoneToNSEC);
  300. _webService.MapGetAndPost("/api/zones/dnssec/properties/convertToNSEC3", _zonesApi.ConvertPrimaryZoneToNSEC3);
  301. _webService.MapGetAndPost("/api/zones/dnssec/properties/updateNSEC3Params", _zonesApi.UpdatePrimaryZoneNSEC3Parameters);
  302. _webService.MapGetAndPost("/api/zones/dnssec/properties/updateDnsKeyTtl", _zonesApi.UpdatePrimaryZoneDnssecDnsKeyTtl);
  303. _webService.MapGetAndPost("/api/zones/dnssec/properties/generatePrivateKey", _zonesApi.GenerateAndAddPrimaryZoneDnssecPrivateKey);
  304. _webService.MapGetAndPost("/api/zones/dnssec/properties/updatePrivateKey", _zonesApi.UpdatePrimaryZoneDnssecPrivateKey);
  305. _webService.MapGetAndPost("/api/zones/dnssec/properties/deletePrivateKey", _zonesApi.DeletePrimaryZoneDnssecPrivateKey);
  306. _webService.MapGetAndPost("/api/zones/dnssec/properties/publishAllPrivateKeys", _zonesApi.PublishAllGeneratedPrimaryZoneDnssecPrivateKeys);
  307. _webService.MapGetAndPost("/api/zones/dnssec/properties/rolloverDnsKey", _zonesApi.RolloverPrimaryZoneDnsKey);
  308. _webService.MapGetAndPost("/api/zones/dnssec/properties/retireDnsKey", _zonesApi.RetirePrimaryZoneDnsKey);
  309. _webService.MapGetAndPost("/api/zones/records/add", _zonesApi.AddRecord);
  310. _webService.MapGetAndPost("/api/zones/records/get", _zonesApi.GetRecords);
  311. _webService.MapGetAndPost("/api/zones/records/update", _zonesApi.UpdateRecord);
  312. _webService.MapGetAndPost("/api/zones/records/delete", _zonesApi.DeleteRecord);
  313. //cache
  314. _webService.MapGetAndPost("/api/cache/list", _otherZonesApi.ListCachedZones);
  315. _webService.MapGetAndPost("/api/cache/delete", _otherZonesApi.DeleteCachedZone);
  316. _webService.MapGetAndPost("/api/cache/flush", _otherZonesApi.FlushCache);
  317. //allowed
  318. _webService.MapGetAndPost("/api/allowed/list", _otherZonesApi.ListAllowedZones);
  319. _webService.MapGetAndPost("/api/allowed/add", _otherZonesApi.AllowZone);
  320. _webService.MapGetAndPost("/api/allowed/delete", _otherZonesApi.DeleteAllowedZone);
  321. _webService.MapGetAndPost("/api/allowed/flush", _otherZonesApi.FlushAllowedZone);
  322. _webService.MapGetAndPost("/api/allowed/import", _otherZonesApi.ImportAllowedZones);
  323. _webService.MapGetAndPost("/api/allowed/export", _otherZonesApi.ExportAllowedZonesAsync);
  324. //blocked
  325. _webService.MapGetAndPost("/api/blocked/list", _otherZonesApi.ListBlockedZones);
  326. _webService.MapGetAndPost("/api/blocked/add", _otherZonesApi.BlockZone);
  327. _webService.MapGetAndPost("/api/blocked/delete", _otherZonesApi.DeleteBlockedZone);
  328. _webService.MapGetAndPost("/api/blocked/flush", _otherZonesApi.FlushBlockedZone);
  329. _webService.MapGetAndPost("/api/blocked/import", _otherZonesApi.ImportBlockedZones);
  330. _webService.MapGetAndPost("/api/blocked/export", _otherZonesApi.ExportBlockedZonesAsync);
  331. //apps
  332. _webService.MapGetAndPost("/api/apps/list", _appsApi.ListInstalledAppsAsync);
  333. _webService.MapGetAndPost("/api/apps/listStoreApps", _appsApi.ListStoreApps);
  334. _webService.MapGetAndPost("/api/apps/downloadAndInstall", _appsApi.DownloadAndInstallAppAsync);
  335. _webService.MapGetAndPost("/api/apps/downloadAndUpdate", _appsApi.DownloadAndUpdateAppAsync);
  336. _webService.MapPost("/api/apps/install", _appsApi.InstallAppAsync);
  337. _webService.MapPost("/api/apps/update", _appsApi.UpdateAppAsync);
  338. _webService.MapGetAndPost("/api/apps/uninstall", _appsApi.UninstallApp);
  339. _webService.MapGetAndPost("/api/apps/config/get", _appsApi.GetAppConfigAsync);
  340. _webService.MapGetAndPost("/api/apps/config/set", _appsApi.SetAppConfigAsync);
  341. //dns client
  342. _webService.MapGetAndPost("/api/dnsClient/resolve", _api.ResolveQueryAsync);
  343. //settings
  344. _webService.MapGetAndPost("/api/settings/get", _settingsApi.GetDnsSettings);
  345. _webService.MapGetAndPost("/api/settings/set", _settingsApi.SetDnsSettings);
  346. _webService.MapGetAndPost("/api/settings/getTsigKeyNames", _settingsApi.GetTsigKeyNames);
  347. _webService.MapGetAndPost("/api/settings/forceUpdateBlockLists", _settingsApi.ForceUpdateBlockLists);
  348. _webService.MapGetAndPost("/api/settings/temporaryDisableBlocking", _settingsApi.TemporaryDisableBlocking);
  349. _webService.MapGetAndPost("/api/settings/backup", _settingsApi.BackupSettingsAsync);
  350. _webService.MapPost("/api/settings/restore", _settingsApi.RestoreSettingsAsync);
  351. //dhcp
  352. _webService.MapGetAndPost("/api/dhcp/leases/list", _dhcpApi.ListDhcpLeases);
  353. _webService.MapGetAndPost("/api/dhcp/leases/remove", _dhcpApi.RemoveDhcpLease);
  354. _webService.MapGetAndPost("/api/dhcp/leases/convertToReserved", _dhcpApi.ConvertToReservedLease);
  355. _webService.MapGetAndPost("/api/dhcp/leases/convertToDynamic", _dhcpApi.ConvertToDynamicLease);
  356. _webService.MapGetAndPost("/api/dhcp/scopes/list", _dhcpApi.ListDhcpScopes);
  357. _webService.MapGetAndPost("/api/dhcp/scopes/get", _dhcpApi.GetDhcpScope);
  358. _webService.MapGetAndPost("/api/dhcp/scopes/set", _dhcpApi.SetDhcpScopeAsync);
  359. _webService.MapGetAndPost("/api/dhcp/scopes/addReservedLease", _dhcpApi.AddReservedLease);
  360. _webService.MapGetAndPost("/api/dhcp/scopes/removeReservedLease", _dhcpApi.RemoveReservedLease);
  361. _webService.MapGetAndPost("/api/dhcp/scopes/enable", _dhcpApi.EnableDhcpScopeAsync);
  362. _webService.MapGetAndPost("/api/dhcp/scopes/disable", _dhcpApi.DisableDhcpScope);
  363. _webService.MapGetAndPost("/api/dhcp/scopes/delete", _dhcpApi.DeleteDhcpScope);
  364. //administration
  365. _webService.MapGetAndPost("/api/admin/sessions/list", _authApi.ListSessions);
  366. _webService.MapGetAndPost("/api/admin/sessions/createToken", _authApi.CreateApiToken);
  367. _webService.MapGetAndPost("/api/admin/sessions/delete", delegate (HttpContext context) { _authApi.DeleteSession(context, true); });
  368. _webService.MapGetAndPost("/api/admin/users/list", _authApi.ListUsers);
  369. _webService.MapGetAndPost("/api/admin/users/create", _authApi.CreateUser);
  370. _webService.MapGetAndPost("/api/admin/users/get", _authApi.GetUserDetails);
  371. _webService.MapGetAndPost("/api/admin/users/set", _authApi.SetUserDetails);
  372. _webService.MapGetAndPost("/api/admin/users/delete", _authApi.DeleteUser);
  373. _webService.MapGetAndPost("/api/admin/groups/list", _authApi.ListGroups);
  374. _webService.MapGetAndPost("/api/admin/groups/create", _authApi.CreateGroup);
  375. _webService.MapGetAndPost("/api/admin/groups/get", _authApi.GetGroupDetails);
  376. _webService.MapGetAndPost("/api/admin/groups/set", _authApi.SetGroupDetails);
  377. _webService.MapGetAndPost("/api/admin/groups/delete", _authApi.DeleteGroup);
  378. _webService.MapGetAndPost("/api/admin/permissions/list", _authApi.ListPermissions);
  379. _webService.MapGetAndPost("/api/admin/permissions/get", delegate (HttpContext context) { _authApi.GetPermissionDetails(context, PermissionSection.Unknown); });
  380. _webService.MapGetAndPost("/api/admin/permissions/set", delegate (HttpContext context) { _authApi.SetPermissionsDetails(context, PermissionSection.Unknown); });
  381. //logs
  382. _webService.MapGetAndPost("/api/logs/list", _logsApi.ListLogs);
  383. _webService.MapGetAndPost("/api/logs/download", _logsApi.DownloadLogAsync);
  384. _webService.MapGetAndPost("/api/logs/delete", _logsApi.DeleteLog);
  385. _webService.MapGetAndPost("/api/logs/deleteAll", _logsApi.DeleteAllLogs);
  386. _webService.MapGetAndPost("/api/logs/query", _logsApi.QueryLogsAsync);
  387. }
  388. private async Task WebServiceApiMiddleware(HttpContext context, RequestDelegate next)
  389. {
  390. bool needsJsonResponseObject;
  391. switch (context.Request.Path)
  392. {
  393. case "/api/user/login":
  394. case "/api/user/createToken":
  395. case "/api/user/logout":
  396. needsJsonResponseObject = false;
  397. break;
  398. case "/api/user/session/get":
  399. {
  400. if (!TryGetSession(context, out UserSession session))
  401. throw new InvalidTokenWebServiceException("Invalid token or session expired.");
  402. context.Items["session"] = session;
  403. needsJsonResponseObject = false;
  404. }
  405. break;
  406. case "/api/allowed/export":
  407. case "/api/blocked/export":
  408. case "/api/settings/backup":
  409. case "/api/logs/download":
  410. {
  411. if (!TryGetSession(context, out UserSession session))
  412. throw new InvalidTokenWebServiceException("Invalid token or session expired.");
  413. context.Items["session"] = session;
  414. await next(context);
  415. }
  416. return;
  417. default:
  418. {
  419. if (!TryGetSession(context, out UserSession session))
  420. throw new InvalidTokenWebServiceException("Invalid token or session expired.");
  421. context.Items["session"] = session;
  422. needsJsonResponseObject = true;
  423. }
  424. break;
  425. }
  426. using (MemoryStream mS = new MemoryStream())
  427. {
  428. Utf8JsonWriter jsonWriter = new Utf8JsonWriter(mS);
  429. context.Items["jsonWriter"] = jsonWriter;
  430. jsonWriter.WriteStartObject();
  431. if (needsJsonResponseObject)
  432. {
  433. jsonWriter.WritePropertyName("response");
  434. jsonWriter.WriteStartObject();
  435. await next(context);
  436. jsonWriter.WriteEndObject();
  437. }
  438. else
  439. {
  440. await next(context);
  441. }
  442. jsonWriter.WriteString("status", "ok");
  443. jsonWriter.WriteEndObject();
  444. jsonWriter.Flush();
  445. mS.Position = 0;
  446. HttpResponse response = context.Response;
  447. response.StatusCode = StatusCodes.Status200OK;
  448. response.ContentType = "application/json; charset=utf-8";
  449. response.ContentLength = mS.Length;
  450. await mS.CopyToAsync(response.Body);
  451. }
  452. }
  453. private static void WebServiceExceptionHandler(IApplicationBuilder exceptionHandlerApp)
  454. {
  455. exceptionHandlerApp.Run(async delegate (HttpContext context)
  456. {
  457. IExceptionHandlerPathFeature exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
  458. if (exceptionHandlerPathFeature.Path.StartsWith("/api/"))
  459. {
  460. Exception ex = exceptionHandlerPathFeature.Error;
  461. context.Response.StatusCode = StatusCodes.Status200OK;
  462. context.Response.ContentType = "application/json; charset=utf-8";
  463. await using (Utf8JsonWriter jsonWriter = new Utf8JsonWriter(context.Response.Body))
  464. {
  465. jsonWriter.WriteStartObject();
  466. if (ex is InvalidTokenWebServiceException)
  467. {
  468. jsonWriter.WriteString("status", "invalid-token");
  469. jsonWriter.WriteString("errorMessage", ex.Message);
  470. }
  471. else
  472. {
  473. jsonWriter.WriteString("status", "error");
  474. jsonWriter.WriteString("errorMessage", ex.Message);
  475. jsonWriter.WriteString("stackTrace", ex.StackTrace);
  476. if (ex.InnerException is not null)
  477. jsonWriter.WriteString("innerErrorMessage", ex.InnerException.Message);
  478. }
  479. jsonWriter.WriteEndObject();
  480. }
  481. }
  482. });
  483. }
  484. private bool TryGetSession(HttpContext context, out UserSession session)
  485. {
  486. string token = context.Request.GetQueryOrForm("token");
  487. session = _authManager.GetSession(token);
  488. if ((session is null) || session.User.Disabled)
  489. return false;
  490. if (session.HasExpired())
  491. {
  492. _authManager.DeleteSession(session.Token);
  493. _authManager.SaveConfigFile();
  494. return false;
  495. }
  496. IPEndPoint remoteEP = context.GetRemoteEndPoint();
  497. session.UpdateLastSeen(remoteEP.Address, context.Request.Headers.UserAgent);
  498. return true;
  499. }
  500. #endregion
  501. #region tls
  502. internal void StartTlsCertificateUpdateTimer()
  503. {
  504. if (_tlsCertificateUpdateTimer is null)
  505. {
  506. _tlsCertificateUpdateTimer = new Timer(delegate (object state)
  507. {
  508. if (!string.IsNullOrEmpty(_webServiceTlsCertificatePath))
  509. {
  510. try
  511. {
  512. FileInfo fileInfo = new FileInfo(_webServiceTlsCertificatePath);
  513. if (fileInfo.Exists && (fileInfo.LastWriteTimeUtc != _webServiceTlsCertificateLastModifiedOn))
  514. LoadWebServiceTlsCertificate(_webServiceTlsCertificatePath, _webServiceTlsCertificatePassword);
  515. }
  516. catch (Exception ex)
  517. {
  518. _log.Write("DNS Server encountered an error while updating Web Service TLS Certificate: " + _webServiceTlsCertificatePath + "\r\n" + ex.ToString());
  519. }
  520. }
  521. if (!string.IsNullOrEmpty(_dnsTlsCertificatePath))
  522. {
  523. try
  524. {
  525. FileInfo fileInfo = new FileInfo(_dnsTlsCertificatePath);
  526. if (fileInfo.Exists && (fileInfo.LastWriteTimeUtc != _dnsTlsCertificateLastModifiedOn))
  527. LoadDnsTlsCertificate(_dnsTlsCertificatePath, _dnsTlsCertificatePassword);
  528. }
  529. catch (Exception ex)
  530. {
  531. _log.Write("DNS Server encountered an error while updating DNS Server TLS Certificate: " + _dnsTlsCertificatePath + "\r\n" + ex.ToString());
  532. }
  533. }
  534. }, null, TLS_CERTIFICATE_UPDATE_TIMER_INITIAL_INTERVAL, TLS_CERTIFICATE_UPDATE_TIMER_INTERVAL);
  535. }
  536. }
  537. internal void StopTlsCertificateUpdateTimer()
  538. {
  539. if (_tlsCertificateUpdateTimer is not null)
  540. {
  541. _tlsCertificateUpdateTimer.Dispose();
  542. _tlsCertificateUpdateTimer = null;
  543. }
  544. }
  545. internal void LoadWebServiceTlsCertificate(string tlsCertificatePath, string tlsCertificatePassword)
  546. {
  547. FileInfo fileInfo = new FileInfo(tlsCertificatePath);
  548. if (!fileInfo.Exists)
  549. throw new ArgumentException("Web Service TLS certificate file does not exists: " + tlsCertificatePath);
  550. if (Path.GetExtension(tlsCertificatePath) != ".pfx")
  551. throw new ArgumentException("Web Service TLS certificate file must be PKCS #12 formatted with .pfx extension: " + tlsCertificatePath);
  552. _webServiceTlsCertificate = new X509Certificate2(tlsCertificatePath, tlsCertificatePassword);
  553. _webServiceTlsCertificateLastModifiedOn = fileInfo.LastWriteTimeUtc;
  554. _log.Write("Web Service TLS certificate was loaded: " + tlsCertificatePath);
  555. }
  556. internal void LoadDnsTlsCertificate(string tlsCertificatePath, string tlsCertificatePassword)
  557. {
  558. FileInfo fileInfo = new FileInfo(tlsCertificatePath);
  559. if (!fileInfo.Exists)
  560. throw new ArgumentException("DNS Server TLS certificate file does not exists: " + tlsCertificatePath);
  561. if (Path.GetExtension(tlsCertificatePath) != ".pfx")
  562. throw new ArgumentException("DNS Server TLS certificate file must be PKCS #12 formatted with .pfx extension: " + tlsCertificatePath);
  563. _dnsServer.Certificate = new X509Certificate2(tlsCertificatePath, tlsCertificatePassword);
  564. _dnsTlsCertificateLastModifiedOn = fileInfo.LastWriteTimeUtc;
  565. _log.Write("DNS Server TLS certificate was loaded: " + tlsCertificatePath);
  566. }
  567. internal void SelfSignedCertCheck(bool generateNew, bool throwException)
  568. {
  569. string selfSignedCertificateFilePath = Path.Combine(_configFolder, "cert.pfx");
  570. if (_webServiceUseSelfSignedTlsCertificate)
  571. {
  572. if (generateNew || !File.Exists(selfSignedCertificateFilePath))
  573. {
  574. RSA rsa = RSA.Create(2048);
  575. CertificateRequest req = new CertificateRequest("cn=" + _dnsServer.ServerDomain, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
  576. X509Certificate2 cert = req.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddYears(5));
  577. File.WriteAllBytes(selfSignedCertificateFilePath, cert.Export(X509ContentType.Pkcs12, null as string));
  578. }
  579. if (_webServiceEnableTls && string.IsNullOrEmpty(_webServiceTlsCertificatePath))
  580. {
  581. try
  582. {
  583. LoadWebServiceTlsCertificate(selfSignedCertificateFilePath, null);
  584. }
  585. catch (Exception ex)
  586. {
  587. _log.Write("DNS Server encountered an error while loading self signed Web Service TLS certificate: " + selfSignedCertificateFilePath + "\r\n" + ex.ToString());
  588. if (throwException)
  589. throw;
  590. }
  591. }
  592. }
  593. else
  594. {
  595. File.Delete(selfSignedCertificateFilePath);
  596. }
  597. }
  598. #endregion
  599. #region quic
  600. internal static void ValidateQuicSupport()
  601. {
  602. #pragma warning disable CA2252 // This API requires opting into preview features
  603. #pragma warning disable CA1416 // Validate platform compatibility
  604. if (!QuicConnection.IsSupported)
  605. throw new DnsWebServiceException("DNS-over-QUIC is supported only on Windows 11, Windows Server 2022, and Linux. On Linux, you must install 'libmsquic' and OpenSSL v1.1.1 manually.");
  606. #pragma warning restore CA1416 // Validate platform compatibility
  607. #pragma warning restore CA2252 // This API requires opting into preview features
  608. }
  609. #endregion
  610. #region config
  611. internal void LoadConfigFile()
  612. {
  613. string configFile = Path.Combine(_configFolder, "dns.config");
  614. try
  615. {
  616. int version;
  617. using (FileStream fS = new FileStream(configFile, FileMode.Open, FileAccess.Read))
  618. {
  619. version = ReadConfigFrom(new BinaryReader(fS));
  620. }
  621. _log.Write("DNS Server config file was loaded: " + configFile);
  622. if (version <= 27)
  623. SaveConfigFile(); //save as new config version to avoid loading old version next time
  624. }
  625. catch (FileNotFoundException)
  626. {
  627. _log.Write("DNS Server config file was not found: " + configFile);
  628. _log.Write("DNS Server is restoring default config file.");
  629. //general
  630. string serverDomain = Environment.GetEnvironmentVariable("DNS_SERVER_DOMAIN");
  631. if (!string.IsNullOrEmpty(serverDomain))
  632. _dnsServer.ServerDomain = serverDomain;
  633. _appsApi.EnableAutomaticUpdate = true;
  634. string strPreferIPv6 = Environment.GetEnvironmentVariable("DNS_SERVER_PREFER_IPV6");
  635. if (!string.IsNullOrEmpty(strPreferIPv6))
  636. _dnsServer.PreferIPv6 = bool.Parse(strPreferIPv6);
  637. _dnsServer.DnssecValidation = true;
  638. CreateForwarderZoneToDisableDnssecForNTP();
  639. //optional protocols
  640. string strDnsOverHttp = Environment.GetEnvironmentVariable("DNS_SERVER_OPTIONAL_PROTOCOL_DNS_OVER_HTTP");
  641. if (!string.IsNullOrEmpty(strDnsOverHttp))
  642. _dnsServer.EnableDnsOverHttp = bool.Parse(strDnsOverHttp);
  643. //recursion
  644. string strRecursion = Environment.GetEnvironmentVariable("DNS_SERVER_RECURSION");
  645. if (!string.IsNullOrEmpty(strRecursion))
  646. _dnsServer.Recursion = Enum.Parse<DnsServerRecursion>(strRecursion, true);
  647. else
  648. _dnsServer.Recursion = DnsServerRecursion.AllowOnlyForPrivateNetworks; //default for security reasons
  649. string strRecursionDeniedNetworks = Environment.GetEnvironmentVariable("DNS_SERVER_RECURSION_DENIED_NETWORKS");
  650. if (!string.IsNullOrEmpty(strRecursionDeniedNetworks))
  651. _dnsServer.RecursionDeniedNetworks = strRecursionDeniedNetworks.Split(NetworkAddress.Parse, ',');
  652. string strRecursionAllowedNetworks = Environment.GetEnvironmentVariable("DNS_SERVER_RECURSION_ALLOWED_NETWORKS");
  653. if (!string.IsNullOrEmpty(strRecursionAllowedNetworks))
  654. _dnsServer.RecursionAllowedNetworks = strRecursionAllowedNetworks.Split(NetworkAddress.Parse, ',');
  655. _dnsServer.RandomizeName = true; //default true to enable security feature
  656. _dnsServer.QnameMinimization = true; //default true to enable privacy feature
  657. _dnsServer.NsRevalidation = true; //default true for security reasons
  658. //cache
  659. _dnsServer.CacheZoneManager.MaximumEntries = 10000;
  660. //blocking
  661. string strEnableBlocking = Environment.GetEnvironmentVariable("DNS_SERVER_ENABLE_BLOCKING");
  662. if (!string.IsNullOrEmpty(strEnableBlocking))
  663. _dnsServer.EnableBlocking = bool.Parse(strEnableBlocking);
  664. string strAllowTxtBlockingReport = Environment.GetEnvironmentVariable("DNS_SERVER_ALLOW_TXT_BLOCKING_REPORT");
  665. if (!string.IsNullOrEmpty(strAllowTxtBlockingReport))
  666. _dnsServer.AllowTxtBlockingReport = bool.Parse(strAllowTxtBlockingReport);
  667. string strBlockListUrls = Environment.GetEnvironmentVariable("DNS_SERVER_BLOCK_LIST_URLS");
  668. if (!string.IsNullOrEmpty(strBlockListUrls))
  669. {
  670. string[] strBlockListUrlList = strBlockListUrls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  671. foreach (string strBlockListUrl in strBlockListUrlList)
  672. {
  673. if (strBlockListUrl.StartsWith('!'))
  674. {
  675. Uri allowListUrl = new Uri(strBlockListUrl.Substring(1));
  676. if (!_dnsServer.BlockListZoneManager.AllowListUrls.Contains(allowListUrl))
  677. _dnsServer.BlockListZoneManager.AllowListUrls.Add(allowListUrl);
  678. }
  679. else
  680. {
  681. Uri blockListUrl = new Uri(strBlockListUrl);
  682. if (!_dnsServer.BlockListZoneManager.BlockListUrls.Contains(blockListUrl))
  683. _dnsServer.BlockListZoneManager.BlockListUrls.Add(blockListUrl);
  684. }
  685. }
  686. }
  687. //proxy & forwarders
  688. string strForwarders = Environment.GetEnvironmentVariable("DNS_SERVER_FORWARDERS");
  689. if (!string.IsNullOrEmpty(strForwarders))
  690. {
  691. DnsTransportProtocol forwarderProtocol;
  692. string strForwarderProtocol = Environment.GetEnvironmentVariable("DNS_SERVER_FORWARDER_PROTOCOL");
  693. if (string.IsNullOrEmpty(strForwarderProtocol))
  694. {
  695. forwarderProtocol = DnsTransportProtocol.Udp;
  696. }
  697. else
  698. {
  699. forwarderProtocol = Enum.Parse<DnsTransportProtocol>(strForwarderProtocol, true);
  700. if (forwarderProtocol == DnsTransportProtocol.HttpsJson)
  701. forwarderProtocol = DnsTransportProtocol.Https;
  702. }
  703. _dnsServer.Forwarders = strForwarders.Split(delegate (string value)
  704. {
  705. NameServerAddress forwarder = NameServerAddress.Parse(value);
  706. if (forwarder.Protocol != forwarderProtocol)
  707. forwarder = forwarder.ChangeProtocol(forwarderProtocol);
  708. return forwarder;
  709. }, ',');
  710. }
  711. //logging
  712. string strUseLocalTime = Environment.GetEnvironmentVariable("DNS_SERVER_LOG_USING_LOCAL_TIME");
  713. if (!string.IsNullOrEmpty(strUseLocalTime))
  714. _log.UseLocalTime = bool.Parse(strUseLocalTime);
  715. SaveConfigFile();
  716. }
  717. catch (Exception ex)
  718. {
  719. _log.Write("DNS Server encountered an error while loading config file: " + configFile + "\r\n" + ex.ToString());
  720. _log.Write("Note: You may try deleting the config file to fix this issue. However, you will lose DNS settings but, zone data wont be affected.");
  721. throw;
  722. }
  723. }
  724. private void CreateForwarderZoneToDisableDnssecForNTP()
  725. {
  726. if (Environment.OSVersion.Platform == PlatformID.Unix)
  727. {
  728. //adding a conditional forwarder zone for disabling DNSSEC validation for ntp.org so that systems with no real-time clock can sync time
  729. string ntpDomain = "ntp.org";
  730. string fwdRecordComments = "This forwarder zone was automatically created to disable DNSSEC validation for ntp.org to allow systems with no real-time clock (e.g. Raspberry Pi) to sync time via NTP when booting.";
  731. if (_dnsServer.AuthZoneManager.CreateForwarderZone(ntpDomain, DnsTransportProtocol.Udp, "this-server", false, NetProxyType.None, null, 0, null, null, fwdRecordComments) is not null)
  732. {
  733. //set permissions
  734. _authManager.SetPermission(PermissionSection.Zones, ntpDomain, _authManager.GetGroup(Group.ADMINISTRATORS), PermissionFlag.ViewModifyDelete);
  735. _authManager.SetPermission(PermissionSection.Zones, ntpDomain, _authManager.GetGroup(Group.DNS_ADMINISTRATORS), PermissionFlag.ViewModifyDelete);
  736. _authManager.SaveConfigFile();
  737. Directory.CreateDirectory(Path.Combine(_dnsServer.ConfigFolder, "zones"));
  738. _dnsServer.AuthZoneManager.SaveZoneFile(ntpDomain);
  739. }
  740. }
  741. }
  742. internal void SaveConfigFile()
  743. {
  744. string configFile = Path.Combine(_configFolder, "dns.config");
  745. using (MemoryStream mS = new MemoryStream())
  746. {
  747. //serialize config
  748. WriteConfigTo(new BinaryWriter(mS));
  749. //write config
  750. mS.Position = 0;
  751. using (FileStream fS = new FileStream(configFile, FileMode.Create, FileAccess.Write))
  752. {
  753. mS.CopyTo(fS);
  754. }
  755. }
  756. _log.Write("DNS Server config file was saved: " + configFile);
  757. }
  758. internal void InspectAndFixZonePermissions()
  759. {
  760. Permission permission = _authManager.GetPermission(PermissionSection.Zones);
  761. IReadOnlyDictionary<string, Permission> subItemPermissions = permission.SubItemPermissions;
  762. //remove ghost permissions
  763. foreach (KeyValuePair<string, Permission> subItemPermission in subItemPermissions)
  764. {
  765. string zoneName = subItemPermission.Key;
  766. if (_dnsServer.AuthZoneManager.GetAuthZoneInfo(zoneName) is null)
  767. permission.RemoveAllSubItemPermissions(zoneName); //no such zone exists; remove permissions
  768. }
  769. //add missing admin permissions
  770. IReadOnlyList<AuthZoneInfo> zones = _dnsServer.AuthZoneManager.GetAllZones();
  771. Group admins = _authManager.GetGroup(Group.ADMINISTRATORS);
  772. Group dnsAdmins = _authManager.GetGroup(Group.DNS_ADMINISTRATORS);
  773. foreach (AuthZoneInfo zone in zones)
  774. {
  775. if (zone.Internal)
  776. {
  777. _authManager.SetPermission(PermissionSection.Zones, zone.Name, admins, PermissionFlag.View);
  778. _authManager.SetPermission(PermissionSection.Zones, zone.Name, dnsAdmins, PermissionFlag.View);
  779. }
  780. else
  781. {
  782. _authManager.SetPermission(PermissionSection.Zones, zone.Name, admins, PermissionFlag.ViewModifyDelete);
  783. _authManager.SetPermission(PermissionSection.Zones, zone.Name, dnsAdmins, PermissionFlag.ViewModifyDelete);
  784. }
  785. }
  786. _authManager.SaveConfigFile();
  787. }
  788. private int ReadConfigFrom(BinaryReader bR)
  789. {
  790. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DS") //format
  791. throw new InvalidDataException("DNS Server config file format is invalid.");
  792. int version = bR.ReadByte();
  793. if ((version >= 28) && (version <= 31))
  794. {
  795. ReadConfigFrom(bR, version);
  796. }
  797. else if ((version >= 2) && (version <= 27))
  798. {
  799. ReadOldConfigFrom(bR, version);
  800. //new default settings
  801. _appsApi.EnableAutomaticUpdate = true;
  802. }
  803. else
  804. {
  805. throw new InvalidDataException("DNS Server config version not supported.");
  806. }
  807. return version;
  808. }
  809. private void ReadConfigFrom(BinaryReader bR, int version)
  810. {
  811. //web service
  812. {
  813. _webServiceHttpPort = bR.ReadInt32();
  814. _webServiceTlsPort = bR.ReadInt32();
  815. {
  816. int count = bR.ReadByte();
  817. if (count > 0)
  818. {
  819. IPAddress[] localAddresses = new IPAddress[count];
  820. for (int i = 0; i < count; i++)
  821. localAddresses[i] = IPAddressExtensions.ReadFrom(bR);
  822. _webServiceLocalAddresses = localAddresses;
  823. }
  824. }
  825. _webServiceEnableTls = bR.ReadBoolean();
  826. _webServiceHttpToTlsRedirect = bR.ReadBoolean();
  827. _webServiceUseSelfSignedTlsCertificate = bR.ReadBoolean();
  828. _webServiceTlsCertificatePath = bR.ReadShortString();
  829. _webServiceTlsCertificatePassword = bR.ReadShortString();
  830. if (_webServiceTlsCertificatePath.Length == 0)
  831. _webServiceTlsCertificatePath = null;
  832. if (_webServiceTlsCertificatePath != null)
  833. {
  834. try
  835. {
  836. LoadWebServiceTlsCertificate(_webServiceTlsCertificatePath, _webServiceTlsCertificatePassword);
  837. }
  838. catch (Exception ex)
  839. {
  840. _log.Write("DNS Server encountered an error while loading Web Service TLS certificate: " + _webServiceTlsCertificatePath + "\r\n" + ex.ToString());
  841. }
  842. StartTlsCertificateUpdateTimer();
  843. }
  844. SelfSignedCertCheck(false, false);
  845. }
  846. //dns
  847. {
  848. //general
  849. _dnsServer.ServerDomain = bR.ReadShortString();
  850. {
  851. int count = bR.ReadByte();
  852. if (count > 0)
  853. {
  854. IPEndPoint[] localEndPoints = new IPEndPoint[count];
  855. for (int i = 0; i < count; i++)
  856. localEndPoints[i] = (IPEndPoint)EndPointExtensions.ReadFrom(bR);
  857. _dnsServer.LocalEndPoints = localEndPoints;
  858. }
  859. }
  860. _zonesApi.DefaultRecordTtl = bR.ReadUInt32();
  861. _appsApi.EnableAutomaticUpdate = bR.ReadBoolean();
  862. _dnsServer.PreferIPv6 = bR.ReadBoolean();
  863. _dnsServer.UdpPayloadSize = bR.ReadUInt16();
  864. _dnsServer.DnssecValidation = bR.ReadBoolean();
  865. if (version >= 29)
  866. {
  867. _dnsServer.EDnsClientSubnet = bR.ReadBoolean();
  868. _dnsServer.EDnsClientSubnetIPv4PrefixLength = bR.ReadByte();
  869. _dnsServer.EDnsClientSubnetIPv6PrefixLength = bR.ReadByte();
  870. }
  871. else
  872. {
  873. _dnsServer.EDnsClientSubnet = false;
  874. _dnsServer.EDnsClientSubnetIPv4PrefixLength = 24;
  875. _dnsServer.EDnsClientSubnetIPv6PrefixLength = 56;
  876. }
  877. _dnsServer.QpmLimitRequests = bR.ReadInt32();
  878. _dnsServer.QpmLimitErrors = bR.ReadInt32();
  879. _dnsServer.QpmLimitSampleMinutes = bR.ReadInt32();
  880. _dnsServer.QpmLimitIPv4PrefixLength = bR.ReadInt32();
  881. _dnsServer.QpmLimitIPv6PrefixLength = bR.ReadInt32();
  882. _dnsServer.ClientTimeout = bR.ReadInt32();
  883. _dnsServer.TcpSendTimeout = bR.ReadInt32();
  884. _dnsServer.TcpReceiveTimeout = bR.ReadInt32();
  885. if (version >= 30)
  886. {
  887. _dnsServer.QuicIdleTimeout = bR.ReadInt32();
  888. _dnsServer.QuicMaxInboundStreams = bR.ReadInt32();
  889. _dnsServer.ListenBacklog = bR.ReadInt32();
  890. }
  891. else
  892. {
  893. _dnsServer.QuicIdleTimeout = 60000;
  894. _dnsServer.QuicMaxInboundStreams = 100;
  895. _dnsServer.ListenBacklog = 100;
  896. }
  897. //optional protocols
  898. _dnsServer.EnableDnsOverHttp = bR.ReadBoolean();
  899. _dnsServer.EnableDnsOverTls = bR.ReadBoolean();
  900. _dnsServer.EnableDnsOverHttps = bR.ReadBoolean();
  901. if (version >= 31)
  902. {
  903. _dnsServer.EnableDnsOverQuic = bR.ReadBoolean();
  904. _dnsServer.DnsOverHttpPort = bR.ReadInt32();
  905. _dnsServer.DnsOverTlsPort = bR.ReadInt32();
  906. _dnsServer.DnsOverHttpsPort = bR.ReadInt32();
  907. _dnsServer.DnsOverQuicPort = bR.ReadInt32();
  908. }
  909. else if (version >= 30)
  910. {
  911. _ = bR.ReadBoolean(); //removed EnableDnsOverHttpPort80 value
  912. _dnsServer.EnableDnsOverQuic = bR.ReadBoolean();
  913. _dnsServer.DnsOverHttpPort = bR.ReadInt32();
  914. _dnsServer.DnsOverTlsPort = bR.ReadInt32();
  915. _dnsServer.DnsOverHttpsPort = bR.ReadInt32();
  916. _dnsServer.DnsOverQuicPort = bR.ReadInt32();
  917. }
  918. else
  919. {
  920. _dnsServer.EnableDnsOverQuic = false;
  921. if (_dnsServer.EnableDnsOverHttps)
  922. {
  923. _dnsServer.EnableDnsOverHttp = true;
  924. _dnsServer.DnsOverHttpPort = 80;
  925. }
  926. else if (_dnsServer.EnableDnsOverHttp)
  927. {
  928. _dnsServer.DnsOverHttpPort = 8053;
  929. }
  930. else
  931. {
  932. _dnsServer.DnsOverHttpPort = 80;
  933. }
  934. _dnsServer.DnsOverTlsPort = 853;
  935. _dnsServer.DnsOverHttpsPort = 443;
  936. _dnsServer.DnsOverQuicPort = 853;
  937. }
  938. _dnsTlsCertificatePath = bR.ReadShortString();
  939. _dnsTlsCertificatePassword = bR.ReadShortString();
  940. if (_dnsTlsCertificatePath.Length == 0)
  941. _dnsTlsCertificatePath = null;
  942. if (_dnsTlsCertificatePath != null)
  943. {
  944. try
  945. {
  946. LoadDnsTlsCertificate(_dnsTlsCertificatePath, _dnsTlsCertificatePassword);
  947. }
  948. catch (Exception ex)
  949. {
  950. _log.Write("DNS Server encountered an error while loading DNS Server TLS certificate: " + _dnsTlsCertificatePath + "\r\n" + ex.ToString());
  951. }
  952. StartTlsCertificateUpdateTimer();
  953. }
  954. //tsig
  955. {
  956. int count = bR.ReadByte();
  957. Dictionary<string, TsigKey> tsigKeys = new Dictionary<string, TsigKey>(count);
  958. for (int i = 0; i < count; i++)
  959. {
  960. string keyName = bR.ReadShortString();
  961. string sharedSecret = bR.ReadShortString();
  962. TsigAlgorithm algorithm = (TsigAlgorithm)bR.ReadByte();
  963. tsigKeys.Add(keyName, new TsigKey(keyName, sharedSecret, algorithm));
  964. }
  965. _dnsServer.TsigKeys = tsigKeys;
  966. }
  967. //recursion
  968. _dnsServer.Recursion = (DnsServerRecursion)bR.ReadByte();
  969. {
  970. int count = bR.ReadByte();
  971. if (count > 0)
  972. {
  973. NetworkAddress[] networks = new NetworkAddress[count];
  974. for (int i = 0; i < count; i++)
  975. networks[i] = NetworkAddress.ReadFrom(bR);
  976. _dnsServer.RecursionDeniedNetworks = networks;
  977. }
  978. }
  979. {
  980. int count = bR.ReadByte();
  981. if (count > 0)
  982. {
  983. NetworkAddress[] networks = new NetworkAddress[count];
  984. for (int i = 0; i < count; i++)
  985. networks[i] = NetworkAddress.ReadFrom(bR);
  986. _dnsServer.RecursionAllowedNetworks = networks;
  987. }
  988. }
  989. _dnsServer.RandomizeName = bR.ReadBoolean();
  990. _dnsServer.QnameMinimization = bR.ReadBoolean();
  991. _dnsServer.NsRevalidation = bR.ReadBoolean();
  992. _dnsServer.ResolverRetries = bR.ReadInt32();
  993. _dnsServer.ResolverTimeout = bR.ReadInt32();
  994. _dnsServer.ResolverMaxStackCount = bR.ReadInt32();
  995. //cache
  996. if (version >= 30)
  997. _saveCache = bR.ReadBoolean();
  998. else
  999. _saveCache = false;
  1000. _dnsServer.ServeStale = bR.ReadBoolean();
  1001. _dnsServer.CacheZoneManager.ServeStaleTtl = bR.ReadUInt32();
  1002. _dnsServer.CacheZoneManager.MaximumEntries = bR.ReadInt64();
  1003. _dnsServer.CacheZoneManager.MinimumRecordTtl = bR.ReadUInt32();
  1004. _dnsServer.CacheZoneManager.MaximumRecordTtl = bR.ReadUInt32();
  1005. _dnsServer.CacheZoneManager.NegativeRecordTtl = bR.ReadUInt32();
  1006. _dnsServer.CacheZoneManager.FailureRecordTtl = bR.ReadUInt32();
  1007. _dnsServer.CachePrefetchEligibility = bR.ReadInt32();
  1008. _dnsServer.CachePrefetchTrigger = bR.ReadInt32();
  1009. _dnsServer.CachePrefetchSampleIntervalInMinutes = bR.ReadInt32();
  1010. _dnsServer.CachePrefetchSampleEligibilityHitsPerHour = bR.ReadInt32();
  1011. //blocking
  1012. _dnsServer.EnableBlocking = bR.ReadBoolean();
  1013. _dnsServer.AllowTxtBlockingReport = bR.ReadBoolean();
  1014. _dnsServer.BlockingType = (DnsServerBlockingType)bR.ReadByte();
  1015. {
  1016. //read custom blocking addresses
  1017. int count = bR.ReadByte();
  1018. if (count > 0)
  1019. {
  1020. List<DnsARecordData> dnsARecords = new List<DnsARecordData>();
  1021. List<DnsAAAARecordData> dnsAAAARecords = new List<DnsAAAARecordData>();
  1022. for (int i = 0; i < count; i++)
  1023. {
  1024. IPAddress customAddress = IPAddressExtensions.ReadFrom(bR);
  1025. switch (customAddress.AddressFamily)
  1026. {
  1027. case AddressFamily.InterNetwork:
  1028. dnsARecords.Add(new DnsARecordData(customAddress));
  1029. break;
  1030. case AddressFamily.InterNetworkV6:
  1031. dnsAAAARecords.Add(new DnsAAAARecordData(customAddress));
  1032. break;
  1033. }
  1034. }
  1035. _dnsServer.CustomBlockingARecords = dnsARecords;
  1036. _dnsServer.CustomBlockingAAAARecords = dnsAAAARecords;
  1037. }
  1038. }
  1039. {
  1040. //read block list urls
  1041. int count = bR.ReadByte();
  1042. for (int i = 0; i < count; i++)
  1043. {
  1044. string listUrl = bR.ReadShortString();
  1045. if (listUrl.StartsWith('!'))
  1046. _dnsServer.BlockListZoneManager.AllowListUrls.Add(new Uri(listUrl.Substring(1)));
  1047. else
  1048. _dnsServer.BlockListZoneManager.BlockListUrls.Add(new Uri(listUrl));
  1049. }
  1050. _settingsApi.BlockListUpdateIntervalHours = bR.ReadInt32();
  1051. _settingsApi.BlockListLastUpdatedOn = bR.ReadDateTime();
  1052. }
  1053. //proxy & forwarders
  1054. NetProxyType proxyType = (NetProxyType)bR.ReadByte();
  1055. if (proxyType != NetProxyType.None)
  1056. {
  1057. string address = bR.ReadShortString();
  1058. int port = bR.ReadInt32();
  1059. NetworkCredential credential = null;
  1060. if (bR.ReadBoolean()) //credential set
  1061. credential = new NetworkCredential(bR.ReadShortString(), bR.ReadShortString());
  1062. _dnsServer.Proxy = NetProxy.CreateProxy(proxyType, address, port, credential);
  1063. int count = bR.ReadByte();
  1064. List<NetProxyBypassItem> bypassList = new List<NetProxyBypassItem>(count);
  1065. for (int i = 0; i < count; i++)
  1066. bypassList.Add(new NetProxyBypassItem(bR.ReadShortString()));
  1067. _dnsServer.Proxy.BypassList = bypassList;
  1068. }
  1069. else
  1070. {
  1071. _dnsServer.Proxy = null;
  1072. }
  1073. {
  1074. int count = bR.ReadByte();
  1075. if (count > 0)
  1076. {
  1077. NameServerAddress[] forwarders = new NameServerAddress[count];
  1078. for (int i = 0; i < count; i++)
  1079. {
  1080. forwarders[i] = new NameServerAddress(bR);
  1081. if (forwarders[i].Protocol == DnsTransportProtocol.HttpsJson)
  1082. forwarders[i] = forwarders[i].ChangeProtocol(DnsTransportProtocol.Https);
  1083. }
  1084. _dnsServer.Forwarders = forwarders;
  1085. }
  1086. }
  1087. _dnsServer.ForwarderRetries = bR.ReadInt32();
  1088. _dnsServer.ForwarderTimeout = bR.ReadInt32();
  1089. _dnsServer.ForwarderConcurrency = bR.ReadInt32();
  1090. //logging
  1091. if (bR.ReadBoolean()) //log all queries
  1092. _dnsServer.QueryLogManager = _log;
  1093. else
  1094. _dnsServer.QueryLogManager = null;
  1095. _dnsServer.StatsManager.MaxStatFileDays = bR.ReadInt32();
  1096. }
  1097. if ((_webServiceTlsCertificatePath == null) && (_dnsTlsCertificatePath == null))
  1098. StopTlsCertificateUpdateTimer();
  1099. }
  1100. private void ReadOldConfigFrom(BinaryReader bR, int version)
  1101. {
  1102. _dnsServer.ServerDomain = bR.ReadShortString();
  1103. _webServiceHttpPort = bR.ReadInt32();
  1104. if (version >= 13)
  1105. {
  1106. {
  1107. int count = bR.ReadByte();
  1108. if (count > 0)
  1109. {
  1110. IPAddress[] localAddresses = new IPAddress[count];
  1111. for (int i = 0; i < count; i++)
  1112. localAddresses[i] = IPAddressExtensions.ReadFrom(bR);
  1113. _webServiceLocalAddresses = localAddresses;
  1114. }
  1115. }
  1116. _webServiceTlsPort = bR.ReadInt32();
  1117. _webServiceEnableTls = bR.ReadBoolean();
  1118. _webServiceHttpToTlsRedirect = bR.ReadBoolean();
  1119. _webServiceTlsCertificatePath = bR.ReadShortString();
  1120. _webServiceTlsCertificatePassword = bR.ReadShortString();
  1121. if (_webServiceTlsCertificatePath.Length == 0)
  1122. _webServiceTlsCertificatePath = null;
  1123. if (_webServiceTlsCertificatePath != null)
  1124. {
  1125. try
  1126. {
  1127. LoadWebServiceTlsCertificate(_webServiceTlsCertificatePath, _webServiceTlsCertificatePassword);
  1128. }
  1129. catch (Exception ex)
  1130. {
  1131. _log.Write("DNS Server encountered an error while loading Web Service TLS certificate: " + _webServiceTlsCertificatePath + "\r\n" + ex.ToString());
  1132. }
  1133. StartTlsCertificateUpdateTimer();
  1134. }
  1135. }
  1136. else
  1137. {
  1138. _webServiceLocalAddresses = new IPAddress[] { IPAddress.Any, IPAddress.IPv6Any };
  1139. _webServiceTlsPort = 53443;
  1140. _webServiceEnableTls = false;
  1141. _webServiceHttpToTlsRedirect = false;
  1142. _webServiceTlsCertificatePath = string.Empty;
  1143. _webServiceTlsCertificatePassword = string.Empty;
  1144. }
  1145. _dnsServer.PreferIPv6 = bR.ReadBoolean();
  1146. if (bR.ReadBoolean()) //logQueries
  1147. _dnsServer.QueryLogManager = _log;
  1148. if (version >= 14)
  1149. _dnsServer.StatsManager.MaxStatFileDays = bR.ReadInt32();
  1150. else
  1151. _dnsServer.StatsManager.MaxStatFileDays = 0;
  1152. if (version >= 17)
  1153. {
  1154. _dnsServer.Recursion = (DnsServerRecursion)bR.ReadByte();
  1155. {
  1156. int count = bR.ReadByte();
  1157. if (count > 0)
  1158. {
  1159. NetworkAddress[] networks = new NetworkAddress[count];
  1160. for (int i = 0; i < count; i++)
  1161. networks[i] = NetworkAddress.ReadFrom(bR);
  1162. _dnsServer.RecursionDeniedNetworks = networks;
  1163. }
  1164. }
  1165. {
  1166. int count = bR.ReadByte();
  1167. if (count > 0)
  1168. {
  1169. NetworkAddress[] networks = new NetworkAddress[count];
  1170. for (int i = 0; i < count; i++)
  1171. networks[i] = NetworkAddress.ReadFrom(bR);
  1172. _dnsServer.RecursionAllowedNetworks = networks;
  1173. }
  1174. }
  1175. }
  1176. else
  1177. {
  1178. bool allowRecursion = bR.ReadBoolean();
  1179. bool allowRecursionOnlyForPrivateNetworks;
  1180. if (version >= 4)
  1181. allowRecursionOnlyForPrivateNetworks = bR.ReadBoolean();
  1182. else
  1183. allowRecursionOnlyForPrivateNetworks = true; //default true for security reasons
  1184. if (allowRecursion)
  1185. {
  1186. if (allowRecursionOnlyForPrivateNetworks)
  1187. _dnsServer.Recursion = DnsServerRecursion.AllowOnlyForPrivateNetworks;
  1188. else
  1189. _dnsServer.Recursion = DnsServerRecursion.Allow;
  1190. }
  1191. else
  1192. {
  1193. _dnsServer.Recursion = DnsServerRecursion.Deny;
  1194. }
  1195. }
  1196. if (version >= 12)
  1197. _dnsServer.RandomizeName = bR.ReadBoolean();
  1198. else
  1199. _dnsServer.RandomizeName = true; //default true to enable security feature
  1200. if (version >= 15)
  1201. _dnsServer.QnameMinimization = bR.ReadBoolean();
  1202. else
  1203. _dnsServer.QnameMinimization = true; //default true to enable privacy feature
  1204. if (version >= 20)
  1205. {
  1206. _dnsServer.QpmLimitRequests = bR.ReadInt32();
  1207. _dnsServer.QpmLimitErrors = bR.ReadInt32();
  1208. _dnsServer.QpmLimitSampleMinutes = bR.ReadInt32();
  1209. _dnsServer.QpmLimitIPv4PrefixLength = bR.ReadInt32();
  1210. _dnsServer.QpmLimitIPv6PrefixLength = bR.ReadInt32();
  1211. }
  1212. else if (version >= 17)
  1213. {
  1214. _dnsServer.QpmLimitRequests = bR.ReadInt32();
  1215. _dnsServer.QpmLimitSampleMinutes = bR.ReadInt32();
  1216. _ = bR.ReadInt32(); //read obsolete value _dnsServer.QpmLimitSamplingIntervalInMinutes
  1217. }
  1218. else
  1219. {
  1220. _dnsServer.QpmLimitRequests = 0;
  1221. _dnsServer.QpmLimitErrors = 0;
  1222. _dnsServer.QpmLimitSampleMinutes = 1;
  1223. _dnsServer.QpmLimitIPv4PrefixLength = 24;
  1224. _dnsServer.QpmLimitIPv6PrefixLength = 56;
  1225. }
  1226. if (version >= 13)
  1227. {
  1228. _dnsServer.ServeStale = bR.ReadBoolean();
  1229. _dnsServer.CacheZoneManager.ServeStaleTtl = bR.ReadUInt32();
  1230. }
  1231. else
  1232. {
  1233. _dnsServer.ServeStale = true;
  1234. _dnsServer.CacheZoneManager.ServeStaleTtl = CacheZoneManager.SERVE_STALE_TTL;
  1235. }
  1236. if (version >= 9)
  1237. {
  1238. _dnsServer.CachePrefetchEligibility = bR.ReadInt32();
  1239. _dnsServer.CachePrefetchTrigger = bR.ReadInt32();
  1240. _dnsServer.CachePrefetchSampleIntervalInMinutes = bR.ReadInt32();
  1241. _dnsServer.CachePrefetchSampleEligibilityHitsPerHour = bR.ReadInt32();
  1242. }
  1243. else
  1244. {
  1245. _dnsServer.CachePrefetchEligibility = 2;
  1246. _dnsServer.CachePrefetchTrigger = 9;
  1247. _dnsServer.CachePrefetchSampleIntervalInMinutes = 5;
  1248. _dnsServer.CachePrefetchSampleEligibilityHitsPerHour = 30;
  1249. }
  1250. NetProxyType proxyType = (NetProxyType)bR.ReadByte();
  1251. if (proxyType != NetProxyType.None)
  1252. {
  1253. string address = bR.ReadShortString();
  1254. int port = bR.ReadInt32();
  1255. NetworkCredential credential = null;
  1256. if (bR.ReadBoolean()) //credential set
  1257. credential = new NetworkCredential(bR.ReadShortString(), bR.ReadShortString());
  1258. _dnsServer.Proxy = NetProxy.CreateProxy(proxyType, address, port, credential);
  1259. if (version >= 10)
  1260. {
  1261. int count = bR.ReadByte();
  1262. List<NetProxyBypassItem> bypassList = new List<NetProxyBypassItem>(count);
  1263. for (int i = 0; i < count; i++)
  1264. bypassList.Add(new NetProxyBypassItem(bR.ReadShortString()));
  1265. _dnsServer.Proxy.BypassList = bypassList;
  1266. }
  1267. else
  1268. {
  1269. _dnsServer.Proxy.BypassList = null;
  1270. }
  1271. }
  1272. else
  1273. {
  1274. _dnsServer.Proxy = null;
  1275. }
  1276. {
  1277. int count = bR.ReadByte();
  1278. if (count > 0)
  1279. {
  1280. NameServerAddress[] forwarders = new NameServerAddress[count];
  1281. for (int i = 0; i < count; i++)
  1282. {
  1283. forwarders[i] = new NameServerAddress(bR);
  1284. if (forwarders[i].Protocol == DnsTransportProtocol.HttpsJson)
  1285. forwarders[i] = forwarders[i].ChangeProtocol(DnsTransportProtocol.Https);
  1286. }
  1287. _dnsServer.Forwarders = forwarders;
  1288. }
  1289. }
  1290. if (version <= 10)
  1291. {
  1292. DnsTransportProtocol forwarderProtocol = (DnsTransportProtocol)bR.ReadByte();
  1293. if (forwarderProtocol == DnsTransportProtocol.HttpsJson)
  1294. forwarderProtocol = DnsTransportProtocol.Https;
  1295. if (_dnsServer.Forwarders != null)
  1296. {
  1297. List<NameServerAddress> forwarders = new List<NameServerAddress>();
  1298. foreach (NameServerAddress forwarder in _dnsServer.Forwarders)
  1299. {
  1300. if (forwarder.Protocol == forwarderProtocol)
  1301. forwarders.Add(forwarder);
  1302. else
  1303. forwarders.Add(forwarder.ChangeProtocol(forwarderProtocol));
  1304. }
  1305. _dnsServer.Forwarders = forwarders;
  1306. }
  1307. }
  1308. {
  1309. int count = bR.ReadByte();
  1310. if (count > 0)
  1311. {
  1312. if (version > 2)
  1313. {
  1314. for (int i = 0; i < count; i++)
  1315. {
  1316. string username = bR.ReadShortString();
  1317. string passwordHash = bR.ReadShortString();
  1318. if (username.Equals("admin", StringComparison.OrdinalIgnoreCase))
  1319. {
  1320. _authManager.LoadOldConfig(passwordHash, true);
  1321. break;
  1322. }
  1323. }
  1324. }
  1325. else
  1326. {
  1327. for (int i = 0; i < count; i++)
  1328. {
  1329. string username = bR.ReadShortString();
  1330. string password = bR.ReadShortString();
  1331. if (username.Equals("admin", StringComparison.OrdinalIgnoreCase))
  1332. {
  1333. _authManager.LoadOldConfig(password, false);
  1334. break;
  1335. }
  1336. }
  1337. }
  1338. }
  1339. }
  1340. if (version <= 6)
  1341. {
  1342. int count = bR.ReadInt32();
  1343. _configDisabledZones = new List<string>(count);
  1344. for (int i = 0; i < count; i++)
  1345. {
  1346. string domain = bR.ReadShortString();
  1347. _configDisabledZones.Add(domain);
  1348. }
  1349. }
  1350. if (version >= 18)
  1351. _dnsServer.EnableBlocking = bR.ReadBoolean();
  1352. else
  1353. _dnsServer.EnableBlocking = true;
  1354. if (version >= 18)
  1355. _dnsServer.BlockingType = (DnsServerBlockingType)bR.ReadByte();
  1356. else if (version >= 16)
  1357. _dnsServer.BlockingType = bR.ReadBoolean() ? DnsServerBlockingType.NxDomain : DnsServerBlockingType.AnyAddress;
  1358. else
  1359. _dnsServer.BlockingType = DnsServerBlockingType.AnyAddress;
  1360. if (version >= 18)
  1361. {
  1362. //read custom blocking addresses
  1363. int count = bR.ReadByte();
  1364. if (count > 0)
  1365. {
  1366. List<DnsARecordData> dnsARecords = new List<DnsARecordData>();
  1367. List<DnsAAAARecordData> dnsAAAARecords = new List<DnsAAAARecordData>();
  1368. for (int i = 0; i < count; i++)
  1369. {
  1370. IPAddress customAddress = IPAddressExtensions.ReadFrom(bR);
  1371. switch (customAddress.AddressFamily)
  1372. {
  1373. case AddressFamily.InterNetwork:
  1374. dnsARecords.Add(new DnsARecordData(customAddress));
  1375. break;
  1376. case AddressFamily.InterNetworkV6:
  1377. dnsAAAARecords.Add(new DnsAAAARecordData(customAddress));
  1378. break;
  1379. }
  1380. }
  1381. _dnsServer.CustomBlockingARecords = dnsARecords;
  1382. _dnsServer.CustomBlockingAAAARecords = dnsAAAARecords;
  1383. }
  1384. }
  1385. else
  1386. {
  1387. _dnsServer.CustomBlockingARecords = null;
  1388. _dnsServer.CustomBlockingAAAARecords = null;
  1389. }
  1390. if (version > 4)
  1391. {
  1392. //read block list urls
  1393. int count = bR.ReadByte();
  1394. for (int i = 0; i < count; i++)
  1395. {
  1396. string listUrl = bR.ReadShortString();
  1397. if (listUrl.StartsWith('!'))
  1398. _dnsServer.BlockListZoneManager.AllowListUrls.Add(new Uri(listUrl.Substring(1)));
  1399. else
  1400. _dnsServer.BlockListZoneManager.BlockListUrls.Add(new Uri(listUrl));
  1401. }
  1402. _settingsApi.BlockListLastUpdatedOn = bR.ReadDateTime();
  1403. if (version >= 13)
  1404. _settingsApi.BlockListUpdateIntervalHours = bR.ReadInt32();
  1405. }
  1406. else
  1407. {
  1408. _dnsServer.BlockListZoneManager.AllowListUrls.Clear();
  1409. _dnsServer.BlockListZoneManager.BlockListUrls.Clear();
  1410. _settingsApi.BlockListLastUpdatedOn = DateTime.MinValue;
  1411. _settingsApi.BlockListUpdateIntervalHours = 24;
  1412. }
  1413. if (version >= 11)
  1414. {
  1415. int count = bR.ReadByte();
  1416. if (count > 0)
  1417. {
  1418. IPEndPoint[] localEndPoints = new IPEndPoint[count];
  1419. for (int i = 0; i < count; i++)
  1420. localEndPoints[i] = (IPEndPoint)EndPointExtensions.ReadFrom(bR);
  1421. _dnsServer.LocalEndPoints = localEndPoints;
  1422. }
  1423. }
  1424. else if (version >= 6)
  1425. {
  1426. int count = bR.ReadByte();
  1427. if (count > 0)
  1428. {
  1429. IPEndPoint[] localEndPoints = new IPEndPoint[count];
  1430. for (int i = 0; i < count; i++)
  1431. localEndPoints[i] = new IPEndPoint(IPAddressExtensions.ReadFrom(bR), 53);
  1432. _dnsServer.LocalEndPoints = localEndPoints;
  1433. }
  1434. }
  1435. else
  1436. {
  1437. _dnsServer.LocalEndPoints = new IPEndPoint[] { new IPEndPoint(IPAddress.Any, 53), new IPEndPoint(IPAddress.IPv6Any, 53) };
  1438. }
  1439. if (version >= 8)
  1440. {
  1441. _dnsServer.EnableDnsOverHttp = bR.ReadBoolean();
  1442. _dnsServer.EnableDnsOverTls = bR.ReadBoolean();
  1443. _dnsServer.EnableDnsOverHttps = bR.ReadBoolean();
  1444. _dnsTlsCertificatePath = bR.ReadShortString();
  1445. _dnsTlsCertificatePassword = bR.ReadShortString();
  1446. if (_dnsTlsCertificatePath.Length == 0)
  1447. _dnsTlsCertificatePath = null;
  1448. if (_dnsTlsCertificatePath != null)
  1449. {
  1450. try
  1451. {
  1452. LoadDnsTlsCertificate(_dnsTlsCertificatePath, _dnsTlsCertificatePassword);
  1453. }
  1454. catch (Exception ex)
  1455. {
  1456. _log.Write("DNS Server encountered an error while loading DNS Server TLS certificate: " + _dnsTlsCertificatePath + "\r\n" + ex.ToString());
  1457. }
  1458. StartTlsCertificateUpdateTimer();
  1459. }
  1460. }
  1461. else
  1462. {
  1463. _dnsServer.EnableDnsOverHttp = false;
  1464. _dnsServer.EnableDnsOverTls = false;
  1465. _dnsServer.EnableDnsOverHttps = false;
  1466. _dnsTlsCertificatePath = string.Empty;
  1467. _dnsTlsCertificatePassword = string.Empty;
  1468. }
  1469. if (version >= 19)
  1470. {
  1471. _dnsServer.CacheZoneManager.MinimumRecordTtl = bR.ReadUInt32();
  1472. _dnsServer.CacheZoneManager.MaximumRecordTtl = bR.ReadUInt32();
  1473. _dnsServer.CacheZoneManager.NegativeRecordTtl = bR.ReadUInt32();
  1474. _dnsServer.CacheZoneManager.FailureRecordTtl = bR.ReadUInt32();
  1475. }
  1476. else
  1477. {
  1478. _dnsServer.CacheZoneManager.MinimumRecordTtl = CacheZoneManager.MINIMUM_RECORD_TTL;
  1479. _dnsServer.CacheZoneManager.MaximumRecordTtl = CacheZoneManager.MAXIMUM_RECORD_TTL;
  1480. _dnsServer.CacheZoneManager.NegativeRecordTtl = CacheZoneManager.NEGATIVE_RECORD_TTL;
  1481. _dnsServer.CacheZoneManager.FailureRecordTtl = CacheZoneManager.FAILURE_RECORD_TTL;
  1482. }
  1483. if (version >= 21)
  1484. {
  1485. int count = bR.ReadByte();
  1486. Dictionary<string, TsigKey> tsigKeys = new Dictionary<string, TsigKey>(count);
  1487. for (int i = 0; i < count; i++)
  1488. {
  1489. string keyName = bR.ReadShortString();
  1490. string sharedSecret = bR.ReadShortString();
  1491. TsigAlgorithm algorithm = (TsigAlgorithm)bR.ReadByte();
  1492. tsigKeys.Add(keyName, new TsigKey(keyName, sharedSecret, algorithm));
  1493. }
  1494. _dnsServer.TsigKeys = tsigKeys;
  1495. }
  1496. else if (version >= 20)
  1497. {
  1498. int count = bR.ReadByte();
  1499. Dictionary<string, TsigKey> tsigKeys = new Dictionary<string, TsigKey>(count);
  1500. for (int i = 0; i < count; i++)
  1501. {
  1502. string keyName = bR.ReadShortString();
  1503. string sharedSecret = bR.ReadShortString();
  1504. tsigKeys.Add(keyName, new TsigKey(keyName, sharedSecret, TsigAlgorithm.HMAC_SHA256));
  1505. }
  1506. _dnsServer.TsigKeys = tsigKeys;
  1507. }
  1508. else
  1509. {
  1510. _dnsServer.TsigKeys = null;
  1511. }
  1512. if (version >= 22)
  1513. _dnsServer.NsRevalidation = bR.ReadBoolean();
  1514. else
  1515. _dnsServer.NsRevalidation = true; //default true for security reasons
  1516. if (version >= 23)
  1517. {
  1518. _dnsServer.AllowTxtBlockingReport = bR.ReadBoolean();
  1519. _zonesApi.DefaultRecordTtl = bR.ReadUInt32();
  1520. }
  1521. else
  1522. {
  1523. _dnsServer.AllowTxtBlockingReport = true;
  1524. _zonesApi.DefaultRecordTtl = 3600;
  1525. }
  1526. if (version >= 24)
  1527. {
  1528. _webServiceUseSelfSignedTlsCertificate = bR.ReadBoolean();
  1529. SelfSignedCertCheck(false, false);
  1530. }
  1531. else
  1532. {
  1533. _webServiceUseSelfSignedTlsCertificate = false;
  1534. }
  1535. if (version >= 25)
  1536. _dnsServer.UdpPayloadSize = bR.ReadUInt16();
  1537. else
  1538. _dnsServer.UdpPayloadSize = DnsDatagram.EDNS_DEFAULT_UDP_PAYLOAD_SIZE;
  1539. if (version >= 26)
  1540. {
  1541. _dnsServer.DnssecValidation = bR.ReadBoolean();
  1542. _dnsServer.ResolverRetries = bR.ReadInt32();
  1543. _dnsServer.ResolverTimeout = bR.ReadInt32();
  1544. _dnsServer.ResolverMaxStackCount = bR.ReadInt32();
  1545. _dnsServer.ForwarderRetries = bR.ReadInt32();
  1546. _dnsServer.ForwarderTimeout = bR.ReadInt32();
  1547. _dnsServer.ForwarderConcurrency = bR.ReadInt32();
  1548. _dnsServer.ClientTimeout = bR.ReadInt32();
  1549. _dnsServer.TcpSendTimeout = bR.ReadInt32();
  1550. _dnsServer.TcpReceiveTimeout = bR.ReadInt32();
  1551. }
  1552. else
  1553. {
  1554. _dnsServer.DnssecValidation = true;
  1555. CreateForwarderZoneToDisableDnssecForNTP();
  1556. _dnsServer.ResolverRetries = 2;
  1557. _dnsServer.ResolverTimeout = 2000;
  1558. _dnsServer.ResolverMaxStackCount = 16;
  1559. _dnsServer.ForwarderRetries = 3;
  1560. _dnsServer.ForwarderTimeout = 2000;
  1561. _dnsServer.ForwarderConcurrency = 2;
  1562. _dnsServer.ClientTimeout = 4000;
  1563. _dnsServer.TcpSendTimeout = 10000;
  1564. _dnsServer.TcpReceiveTimeout = 10000;
  1565. }
  1566. if (version >= 27)
  1567. _dnsServer.CacheZoneManager.MaximumEntries = bR.ReadInt32();
  1568. else
  1569. _dnsServer.CacheZoneManager.MaximumEntries = 10000;
  1570. }
  1571. private void WriteConfigTo(BinaryWriter bW)
  1572. {
  1573. bW.Write(Encoding.ASCII.GetBytes("DS")); //format
  1574. bW.Write((byte)31); //version
  1575. //web service
  1576. {
  1577. bW.Write(_webServiceHttpPort);
  1578. bW.Write(_webServiceTlsPort);
  1579. {
  1580. bW.Write(Convert.ToByte(_webServiceLocalAddresses.Count));
  1581. foreach (IPAddress localAddress in _webServiceLocalAddresses)
  1582. localAddress.WriteTo(bW);
  1583. }
  1584. bW.Write(_webServiceEnableTls);
  1585. bW.Write(_webServiceHttpToTlsRedirect);
  1586. bW.Write(_webServiceUseSelfSignedTlsCertificate);
  1587. if (_webServiceTlsCertificatePath is null)
  1588. bW.WriteShortString(string.Empty);
  1589. else
  1590. bW.WriteShortString(_webServiceTlsCertificatePath);
  1591. if (_webServiceTlsCertificatePassword is null)
  1592. bW.WriteShortString(string.Empty);
  1593. else
  1594. bW.WriteShortString(_webServiceTlsCertificatePassword);
  1595. }
  1596. //dns
  1597. {
  1598. //general
  1599. bW.WriteShortString(_dnsServer.ServerDomain);
  1600. {
  1601. bW.Write(Convert.ToByte(_dnsServer.LocalEndPoints.Count));
  1602. foreach (IPEndPoint localEP in _dnsServer.LocalEndPoints)
  1603. localEP.WriteTo(bW);
  1604. }
  1605. bW.Write(_zonesApi.DefaultRecordTtl);
  1606. bW.Write(_appsApi.EnableAutomaticUpdate);
  1607. bW.Write(_dnsServer.PreferIPv6);
  1608. bW.Write(_dnsServer.UdpPayloadSize);
  1609. bW.Write(_dnsServer.DnssecValidation);
  1610. bW.Write(_dnsServer.EDnsClientSubnet);
  1611. bW.Write(_dnsServer.EDnsClientSubnetIPv4PrefixLength);
  1612. bW.Write(_dnsServer.EDnsClientSubnetIPv6PrefixLength);
  1613. bW.Write(_dnsServer.QpmLimitRequests);
  1614. bW.Write(_dnsServer.QpmLimitErrors);
  1615. bW.Write(_dnsServer.QpmLimitSampleMinutes);
  1616. bW.Write(_dnsServer.QpmLimitIPv4PrefixLength);
  1617. bW.Write(_dnsServer.QpmLimitIPv6PrefixLength);
  1618. bW.Write(_dnsServer.ClientTimeout);
  1619. bW.Write(_dnsServer.TcpSendTimeout);
  1620. bW.Write(_dnsServer.TcpReceiveTimeout);
  1621. bW.Write(_dnsServer.QuicIdleTimeout);
  1622. bW.Write(_dnsServer.QuicMaxInboundStreams);
  1623. bW.Write(_dnsServer.ListenBacklog);
  1624. //optional protocols
  1625. bW.Write(_dnsServer.EnableDnsOverHttp);
  1626. bW.Write(_dnsServer.EnableDnsOverTls);
  1627. bW.Write(_dnsServer.EnableDnsOverHttps);
  1628. bW.Write(_dnsServer.EnableDnsOverQuic);
  1629. bW.Write(_dnsServer.DnsOverHttpPort);
  1630. bW.Write(_dnsServer.DnsOverTlsPort);
  1631. bW.Write(_dnsServer.DnsOverHttpsPort);
  1632. bW.Write(_dnsServer.DnsOverQuicPort);
  1633. if (_dnsTlsCertificatePath == null)
  1634. bW.WriteShortString(string.Empty);
  1635. else
  1636. bW.WriteShortString(_dnsTlsCertificatePath);
  1637. if (_dnsTlsCertificatePassword == null)
  1638. bW.WriteShortString(string.Empty);
  1639. else
  1640. bW.WriteShortString(_dnsTlsCertificatePassword);
  1641. //tsig
  1642. if (_dnsServer.TsigKeys is null)
  1643. {
  1644. bW.Write((byte)0);
  1645. }
  1646. else
  1647. {
  1648. bW.Write(Convert.ToByte(_dnsServer.TsigKeys.Count));
  1649. foreach (KeyValuePair<string, TsigKey> tsigKey in _dnsServer.TsigKeys)
  1650. {
  1651. bW.WriteShortString(tsigKey.Key);
  1652. bW.WriteShortString(tsigKey.Value.SharedSecret);
  1653. bW.Write((byte)tsigKey.Value.Algorithm);
  1654. }
  1655. }
  1656. //recursion
  1657. bW.Write((byte)_dnsServer.Recursion);
  1658. if (_dnsServer.RecursionDeniedNetworks is null)
  1659. {
  1660. bW.Write((byte)0);
  1661. }
  1662. else
  1663. {
  1664. bW.Write(Convert.ToByte(_dnsServer.RecursionDeniedNetworks.Count));
  1665. foreach (NetworkAddress networkAddress in _dnsServer.RecursionDeniedNetworks)
  1666. networkAddress.WriteTo(bW);
  1667. }
  1668. if (_dnsServer.RecursionAllowedNetworks is null)
  1669. {
  1670. bW.Write((byte)0);
  1671. }
  1672. else
  1673. {
  1674. bW.Write(Convert.ToByte(_dnsServer.RecursionAllowedNetworks.Count));
  1675. foreach (NetworkAddress networkAddress in _dnsServer.RecursionAllowedNetworks)
  1676. networkAddress.WriteTo(bW);
  1677. }
  1678. bW.Write(_dnsServer.RandomizeName);
  1679. bW.Write(_dnsServer.QnameMinimization);
  1680. bW.Write(_dnsServer.NsRevalidation);
  1681. bW.Write(_dnsServer.ResolverRetries);
  1682. bW.Write(_dnsServer.ResolverTimeout);
  1683. bW.Write(_dnsServer.ResolverMaxStackCount);
  1684. //cache
  1685. bW.Write(_saveCache);
  1686. bW.Write(_dnsServer.ServeStale);
  1687. bW.Write(_dnsServer.CacheZoneManager.ServeStaleTtl);
  1688. bW.Write(_dnsServer.CacheZoneManager.MaximumEntries);
  1689. bW.Write(_dnsServer.CacheZoneManager.MinimumRecordTtl);
  1690. bW.Write(_dnsServer.CacheZoneManager.MaximumRecordTtl);
  1691. bW.Write(_dnsServer.CacheZoneManager.NegativeRecordTtl);
  1692. bW.Write(_dnsServer.CacheZoneManager.FailureRecordTtl);
  1693. bW.Write(_dnsServer.CachePrefetchEligibility);
  1694. bW.Write(_dnsServer.CachePrefetchTrigger);
  1695. bW.Write(_dnsServer.CachePrefetchSampleIntervalInMinutes);
  1696. bW.Write(_dnsServer.CachePrefetchSampleEligibilityHitsPerHour);
  1697. //blocking
  1698. bW.Write(_dnsServer.EnableBlocking);
  1699. bW.Write(_dnsServer.AllowTxtBlockingReport);
  1700. bW.Write((byte)_dnsServer.BlockingType);
  1701. {
  1702. bW.Write(Convert.ToByte(_dnsServer.CustomBlockingARecords.Count + _dnsServer.CustomBlockingAAAARecords.Count));
  1703. foreach (DnsARecordData record in _dnsServer.CustomBlockingARecords)
  1704. record.Address.WriteTo(bW);
  1705. foreach (DnsAAAARecordData record in _dnsServer.CustomBlockingAAAARecords)
  1706. record.Address.WriteTo(bW);
  1707. }
  1708. {
  1709. bW.Write(Convert.ToByte(_dnsServer.BlockListZoneManager.AllowListUrls.Count + _dnsServer.BlockListZoneManager.BlockListUrls.Count));
  1710. foreach (Uri allowListUrl in _dnsServer.BlockListZoneManager.AllowListUrls)
  1711. bW.WriteShortString("!" + allowListUrl.AbsoluteUri);
  1712. foreach (Uri blockListUrl in _dnsServer.BlockListZoneManager.BlockListUrls)
  1713. bW.WriteShortString(blockListUrl.AbsoluteUri);
  1714. bW.Write(_settingsApi.BlockListUpdateIntervalHours);
  1715. bW.Write(_settingsApi.BlockListLastUpdatedOn);
  1716. }
  1717. //proxy & forwarders
  1718. if (_dnsServer.Proxy == null)
  1719. {
  1720. bW.Write((byte)NetProxyType.None);
  1721. }
  1722. else
  1723. {
  1724. bW.Write((byte)_dnsServer.Proxy.Type);
  1725. bW.WriteShortString(_dnsServer.Proxy.Address);
  1726. bW.Write(_dnsServer.Proxy.Port);
  1727. NetworkCredential credential = _dnsServer.Proxy.Credential;
  1728. if (credential == null)
  1729. {
  1730. bW.Write(false);
  1731. }
  1732. else
  1733. {
  1734. bW.Write(true);
  1735. bW.WriteShortString(credential.UserName);
  1736. bW.WriteShortString(credential.Password);
  1737. }
  1738. //bypass list
  1739. {
  1740. bW.Write(Convert.ToByte(_dnsServer.Proxy.BypassList.Count));
  1741. foreach (NetProxyBypassItem item in _dnsServer.Proxy.BypassList)
  1742. bW.WriteShortString(item.Value);
  1743. }
  1744. }
  1745. if (_dnsServer.Forwarders == null)
  1746. {
  1747. bW.Write((byte)0);
  1748. }
  1749. else
  1750. {
  1751. bW.Write(Convert.ToByte(_dnsServer.Forwarders.Count));
  1752. foreach (NameServerAddress forwarder in _dnsServer.Forwarders)
  1753. forwarder.WriteTo(bW);
  1754. }
  1755. bW.Write(_dnsServer.ForwarderRetries);
  1756. bW.Write(_dnsServer.ForwarderTimeout);
  1757. bW.Write(_dnsServer.ForwarderConcurrency);
  1758. //logging
  1759. bW.Write(_dnsServer.QueryLogManager is not null); //log all queries
  1760. bW.Write(_dnsServer.StatsManager.MaxStatFileDays);
  1761. }
  1762. }
  1763. #endregion
  1764. #region public
  1765. public async Task StartAsync()
  1766. {
  1767. if (_disposed)
  1768. throw new ObjectDisposedException(nameof(DnsWebService));
  1769. try
  1770. {
  1771. //get initial server domain
  1772. string dnsServerDomain = Environment.MachineName.ToLower();
  1773. if (!DnsClient.IsDomainNameValid(dnsServerDomain))
  1774. dnsServerDomain = "dns-server-1"; //use this name instead since machine name is not a valid domain name
  1775. //init dns server
  1776. _dnsServer = new DnsServer(dnsServerDomain, _configFolder, Path.Combine(_appFolder, "dohwww"), _log);
  1777. //init dhcp server
  1778. _dhcpServer = new DhcpServer(Path.Combine(_configFolder, "scopes"), _log);
  1779. _dhcpServer.DnsServer = _dnsServer;
  1780. _dhcpServer.AuthManager = _authManager;
  1781. //load auth config
  1782. _authManager.LoadConfigFile();
  1783. //load config
  1784. LoadConfigFile();
  1785. //load all dns applications
  1786. _dnsServer.DnsApplicationManager.LoadAllApplications();
  1787. //load all zones files
  1788. _dnsServer.AuthZoneManager.LoadAllZoneFiles();
  1789. InspectAndFixZonePermissions();
  1790. //disable zones from old config format
  1791. if (_configDisabledZones != null)
  1792. {
  1793. foreach (string domain in _configDisabledZones)
  1794. {
  1795. AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
  1796. if (zoneInfo is not null)
  1797. {
  1798. zoneInfo.Disabled = true;
  1799. _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
  1800. }
  1801. }
  1802. }
  1803. //load allowed zone and blocked zone
  1804. _dnsServer.AllowedZoneManager.LoadAllowedZoneFile();
  1805. _dnsServer.BlockedZoneManager.LoadBlockedZoneFile();
  1806. //load block list zone async
  1807. if ((_settingsApi.BlockListUpdateIntervalHours > 0) && (_dnsServer.BlockListZoneManager.BlockListUrls.Count > 0))
  1808. {
  1809. ThreadPool.QueueUserWorkItem(delegate (object state)
  1810. {
  1811. try
  1812. {
  1813. _dnsServer.BlockListZoneManager.LoadBlockLists();
  1814. _settingsApi.StartBlockListUpdateTimer();
  1815. }
  1816. catch (Exception ex)
  1817. {
  1818. _log.Write(ex);
  1819. }
  1820. });
  1821. }
  1822. //load dns cache async
  1823. if (_saveCache)
  1824. {
  1825. ThreadPool.QueueUserWorkItem(delegate (object state)
  1826. {
  1827. try
  1828. {
  1829. _dnsServer.CacheZoneManager.LoadCacheZoneFile();
  1830. }
  1831. catch (Exception ex)
  1832. {
  1833. _log.Write(ex);
  1834. }
  1835. });
  1836. }
  1837. //start web service
  1838. await TryStartWebServiceAsync();
  1839. //start dns and dhcp
  1840. await _dnsServer.StartAsync();
  1841. _dhcpServer.Start();
  1842. _log.Write("DNS Server (v" + _currentVersion.ToString() + ") was started successfully.");
  1843. }
  1844. catch (Exception ex)
  1845. {
  1846. _log.Write("Failed to start DNS Server (v" + _currentVersion.ToString() + ")\r\n" + ex.ToString());
  1847. throw;
  1848. }
  1849. }
  1850. public async Task StopAsync()
  1851. {
  1852. if (_disposed)
  1853. return;
  1854. try
  1855. {
  1856. //stop dns
  1857. if (_dnsServer is not null)
  1858. await _dnsServer.DisposeAsync();
  1859. //stop dhcp
  1860. if (_dhcpServer is not null)
  1861. _dhcpServer.Dispose();
  1862. //stop web service
  1863. if (_settingsApi is not null)
  1864. {
  1865. _settingsApi.StopBlockListUpdateTimer();
  1866. _settingsApi.StopTemporaryDisableBlockingTimer();
  1867. }
  1868. StopTlsCertificateUpdateTimer();
  1869. await StopWebServiceAsync();
  1870. if (_saveCache)
  1871. {
  1872. try
  1873. {
  1874. _dnsServer.CacheZoneManager.SaveCacheZoneFile();
  1875. }
  1876. catch (Exception ex)
  1877. {
  1878. _log.Write(ex);
  1879. }
  1880. }
  1881. _log?.Write("DNS Server (v" + _currentVersion.ToString() + ") was stopped successfully.");
  1882. }
  1883. catch (Exception ex)
  1884. {
  1885. _log?.Write("Failed to stop DNS Server (v" + _currentVersion.ToString() + ")\r\n" + ex.ToString());
  1886. throw;
  1887. }
  1888. }
  1889. public void Start()
  1890. {
  1891. StartAsync().Sync();
  1892. }
  1893. public void Stop()
  1894. {
  1895. StopAsync().Sync();
  1896. }
  1897. #endregion
  1898. #region properties
  1899. internal DnsServer DnsServer
  1900. { get { return _dnsServer; } }
  1901. internal DhcpServer DhcpServer
  1902. { get { return _dhcpServer; } }
  1903. public string ConfigFolder
  1904. { get { return _configFolder; } }
  1905. public int WebServiceHttpPort
  1906. { get { return _webServiceHttpPort; } }
  1907. public int WebServiceTlsPort
  1908. { get { return _webServiceTlsPort; } }
  1909. #endregion
  1910. }
  1911. }