WebServiceApi.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2024 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerCore.Auth;
  16. using DnsServerCore.Dns;
  17. using DnsServerCore.Dns.ResourceRecords;
  18. using DnsServerCore.Dns.Zones;
  19. using Microsoft.AspNetCore.Http;
  20. using System;
  21. using System.Collections.Generic;
  22. using System.Net;
  23. using System.Net.Http;
  24. using System.Net.Sockets;
  25. using System.Text.Json;
  26. using System.Threading;
  27. using System.Threading.Tasks;
  28. using TechnitiumLibrary;
  29. using TechnitiumLibrary.Net;
  30. using TechnitiumLibrary.Net.Dns;
  31. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  32. using TechnitiumLibrary.Net.Http.Client;
  33. using TechnitiumLibrary.Net.Proxy;
  34. namespace DnsServerCore
  35. {
  36. class WebServiceApi
  37. {
  38. #region variables
  39. static readonly char[] _domainTrimChars = new char[] { '\t', ' ', '.' };
  40. readonly DnsWebService _dnsWebService;
  41. readonly Uri _updateCheckUri;
  42. string _checkForUpdateJsonData;
  43. DateTime _checkForUpdateJsonDataUpdatedOn;
  44. const int CHECK_FOR_UPDATE_JSON_DATA_CACHE_TIME_SECONDS = 3600;
  45. #endregion
  46. #region constructor
  47. public WebServiceApi(DnsWebService dnsWebService, Uri updateCheckUri)
  48. {
  49. _dnsWebService = dnsWebService;
  50. _updateCheckUri = updateCheckUri;
  51. }
  52. #endregion
  53. #region private
  54. private async Task<string> GetCheckForUpdateJsonData()
  55. {
  56. if ((_checkForUpdateJsonData is null) || (DateTime.UtcNow > _checkForUpdateJsonDataUpdatedOn.AddSeconds(CHECK_FOR_UPDATE_JSON_DATA_CACHE_TIME_SECONDS)))
  57. {
  58. SocketsHttpHandler handler = new SocketsHttpHandler();
  59. handler.Proxy = _dnsWebService.DnsServer.Proxy;
  60. handler.UseProxy = _dnsWebService.DnsServer.Proxy is not null;
  61. handler.AutomaticDecompression = DecompressionMethods.All;
  62. using (HttpClient http = new HttpClient(new HttpClientNetworkHandler(handler, _dnsWebService.DnsServer.PreferIPv6 ? HttpClientNetworkType.PreferIPv6 : HttpClientNetworkType.Default, _dnsWebService.DnsServer)))
  63. {
  64. _checkForUpdateJsonData = await http.GetStringAsync(_updateCheckUri);
  65. _checkForUpdateJsonDataUpdatedOn = DateTime.UtcNow;
  66. }
  67. }
  68. return _checkForUpdateJsonData;
  69. }
  70. #endregion
  71. #region public
  72. public async Task CheckForUpdateAsync(HttpContext context)
  73. {
  74. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  75. if (_updateCheckUri is null)
  76. {
  77. jsonWriter.WriteBoolean("updateAvailable", false);
  78. return;
  79. }
  80. try
  81. {
  82. string jsonData = await GetCheckForUpdateJsonData();
  83. using JsonDocument jsonDocument = JsonDocument.Parse(jsonData);
  84. JsonElement jsonResponse = jsonDocument.RootElement;
  85. string updateVersion = jsonResponse.GetProperty("updateVersion").GetString();
  86. string updateTitle = jsonResponse.GetPropertyValue("updateTitle", null);
  87. string updateMessage = jsonResponse.GetPropertyValue("updateMessage", null);
  88. string downloadLink = jsonResponse.GetPropertyValue("downloadLink", null);
  89. string instructionsLink = jsonResponse.GetPropertyValue("instructionsLink", null);
  90. string changeLogLink = jsonResponse.GetPropertyValue("changeLogLink", null);
  91. bool updateAvailable = new Version(updateVersion) > _dnsWebService._currentVersion;
  92. jsonWriter.WriteBoolean("updateAvailable", updateAvailable);
  93. jsonWriter.WriteString("updateVersion", updateVersion);
  94. jsonWriter.WriteString("currentVersion", _dnsWebService.GetServerVersion());
  95. if (updateAvailable)
  96. {
  97. jsonWriter.WriteString("updateTitle", updateTitle);
  98. jsonWriter.WriteString("updateMessage", updateMessage);
  99. jsonWriter.WriteString("downloadLink", downloadLink);
  100. jsonWriter.WriteString("instructionsLink", instructionsLink);
  101. jsonWriter.WriteString("changeLogLink", changeLogLink);
  102. }
  103. string strLog = "Check for update was done {updateAvailable: " + updateAvailable + "; updateVersion: " + updateVersion + ";";
  104. if (!string.IsNullOrEmpty(updateTitle))
  105. strLog += " updateTitle: " + updateTitle + ";";
  106. if (!string.IsNullOrEmpty(updateMessage))
  107. strLog += " updateMessage: " + updateMessage + ";";
  108. if (!string.IsNullOrEmpty(downloadLink))
  109. strLog += " downloadLink: " + downloadLink + ";";
  110. if (!string.IsNullOrEmpty(instructionsLink))
  111. strLog += " instructionsLink: " + instructionsLink + ";";
  112. if (!string.IsNullOrEmpty(changeLogLink))
  113. strLog += " changeLogLink: " + changeLogLink + ";";
  114. strLog += "}";
  115. _dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), strLog);
  116. }
  117. catch (Exception ex)
  118. {
  119. _dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "Check for update was done {updateAvailable: False;}\r\n" + ex.ToString());
  120. jsonWriter.WriteBoolean("updateAvailable", false);
  121. }
  122. }
  123. public async Task ResolveQueryAsync(HttpContext context)
  124. {
  125. UserSession session = context.GetCurrentSession();
  126. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.DnsClient, session.User, PermissionFlag.View))
  127. throw new DnsWebServiceException("Access was denied.");
  128. HttpRequest request = context.Request;
  129. string server = request.GetQueryOrForm("server");
  130. string domain = request.GetQueryOrForm("domain").Trim(_domainTrimChars);
  131. DnsResourceRecordType type = request.GetQueryOrFormEnum<DnsResourceRecordType>("type");
  132. DnsTransportProtocol protocol = request.GetQueryOrFormEnum("protocol", DnsTransportProtocol.Udp);
  133. bool dnssecValidation = request.GetQueryOrForm("dnssec", bool.Parse, false);
  134. NetworkAddress eDnsClientSubnet = request.GetQueryOrForm("eDnsClientSubnet", NetworkAddress.Parse, null);
  135. if (eDnsClientSubnet is not null)
  136. {
  137. switch (eDnsClientSubnet.AddressFamily)
  138. {
  139. case AddressFamily.InterNetwork:
  140. if (eDnsClientSubnet.PrefixLength == 32)
  141. eDnsClientSubnet = new NetworkAddress(eDnsClientSubnet.Address, 24);
  142. break;
  143. case AddressFamily.InterNetworkV6:
  144. if (eDnsClientSubnet.PrefixLength == 128)
  145. eDnsClientSubnet = new NetworkAddress(eDnsClientSubnet.Address, 56);
  146. break;
  147. }
  148. }
  149. bool importResponse = request.GetQueryOrForm("import", bool.Parse, false);
  150. NetProxy proxy = _dnsWebService.DnsServer.Proxy;
  151. bool preferIPv6 = _dnsWebService.DnsServer.PreferIPv6;
  152. ushort udpPayloadSize = _dnsWebService.DnsServer.UdpPayloadSize;
  153. bool randomizeName = false;
  154. bool qnameMinimization = _dnsWebService.DnsServer.QnameMinimization;
  155. const int RETRIES = 1;
  156. const int TIMEOUT = 10000;
  157. DnsDatagram dnsResponse;
  158. List<DnsDatagram> rawResponses = new List<DnsDatagram>();
  159. string dnssecErrorMessage = null;
  160. if (server.Equals("recursive-resolver", StringComparison.OrdinalIgnoreCase))
  161. {
  162. if (type == DnsResourceRecordType.AXFR)
  163. throw new DnsServerException("Cannot do zone transfer (AXFR) for 'recursive-resolver'.");
  164. DnsQuestionRecord question;
  165. if ((type == DnsResourceRecordType.PTR) && IPAddress.TryParse(domain, out IPAddress address))
  166. question = new DnsQuestionRecord(address, DnsClass.IN);
  167. else
  168. question = new DnsQuestionRecord(domain, type, DnsClass.IN);
  169. DnsCache dnsCache = new DnsCache();
  170. dnsCache.MinimumRecordTtl = 0;
  171. dnsCache.MaximumRecordTtl = 7 * 24 * 60 * 60;
  172. try
  173. {
  174. dnsResponse = await TechnitiumLibrary.TaskExtensions.TimeoutAsync(async delegate (CancellationToken cancellationToken1)
  175. {
  176. return await DnsClient.RecursiveResolveAsync(question, dnsCache, proxy, preferIPv6, udpPayloadSize, randomizeName, qnameMinimization, dnssecValidation, eDnsClientSubnet, RETRIES, TIMEOUT, rawResponses: rawResponses, cancellationToken: cancellationToken1);
  177. }, DnsServer.RECURSIVE_RESOLUTION_TIMEOUT);
  178. }
  179. catch (DnsClientResponseDnssecValidationException ex)
  180. {
  181. dnsResponse = ex.Response;
  182. dnssecErrorMessage = ex.Message;
  183. importResponse = false;
  184. }
  185. }
  186. else if (server.Equals("system-dns", StringComparison.OrdinalIgnoreCase))
  187. {
  188. DnsClient dnsClient = new DnsClient();
  189. dnsClient.Proxy = proxy;
  190. dnsClient.PreferIPv6 = preferIPv6;
  191. dnsClient.RandomizeName = randomizeName;
  192. dnsClient.Retries = RETRIES;
  193. dnsClient.Timeout = TIMEOUT;
  194. dnsClient.UdpPayloadSize = udpPayloadSize;
  195. dnsClient.DnssecValidation = dnssecValidation;
  196. dnsClient.EDnsClientSubnet = eDnsClientSubnet;
  197. try
  198. {
  199. dnsResponse = await dnsClient.ResolveAsync(domain, type);
  200. }
  201. catch (DnsClientResponseDnssecValidationException ex)
  202. {
  203. dnsResponse = ex.Response;
  204. dnssecErrorMessage = ex.Message;
  205. importResponse = false;
  206. }
  207. }
  208. else
  209. {
  210. if ((type == DnsResourceRecordType.AXFR) && (protocol == DnsTransportProtocol.Udp))
  211. protocol = DnsTransportProtocol.Tcp;
  212. NameServerAddress nameServer;
  213. if (server.Equals("this-server", StringComparison.OrdinalIgnoreCase))
  214. {
  215. switch (protocol)
  216. {
  217. case DnsTransportProtocol.Udp:
  218. nameServer = _dnsWebService.DnsServer.ThisServer;
  219. break;
  220. case DnsTransportProtocol.Tcp:
  221. nameServer = _dnsWebService.DnsServer.ThisServer.ChangeProtocol(DnsTransportProtocol.Tcp);
  222. break;
  223. case DnsTransportProtocol.Tls:
  224. throw new DnsServerException("Cannot use DNS-over-TLS protocol for 'this-server'. Please use the TLS certificate domain name as the server.");
  225. case DnsTransportProtocol.Https:
  226. throw new DnsServerException("Cannot use DNS-over-HTTPS protocol for 'this-server'. Please use the TLS certificate domain name with a url as the server.");
  227. case DnsTransportProtocol.Quic:
  228. throw new DnsServerException("Cannot use DNS-over-QUIC protocol for 'this-server'. Please use the TLS certificate domain name as the server.");
  229. default:
  230. throw new NotSupportedException("DNS transport protocol is not supported: " + protocol.ToString());
  231. }
  232. proxy = null; //no proxy required for this server
  233. }
  234. else
  235. {
  236. nameServer = NameServerAddress.Parse(server);
  237. if (nameServer.Protocol != protocol)
  238. nameServer = nameServer.ChangeProtocol(protocol);
  239. if (nameServer.IsIPEndPointStale)
  240. await nameServer.ResolveIPAddressAsync(_dnsWebService.DnsServer, _dnsWebService.DnsServer.PreferIPv6);
  241. if ((nameServer.DomainEndPoint is null) && ((protocol == DnsTransportProtocol.Udp) || (protocol == DnsTransportProtocol.Tcp)))
  242. {
  243. try
  244. {
  245. await nameServer.ResolveDomainNameAsync(_dnsWebService.DnsServer);
  246. }
  247. catch
  248. { }
  249. }
  250. }
  251. DnsClient dnsClient = new DnsClient(nameServer);
  252. dnsClient.Proxy = proxy;
  253. dnsClient.PreferIPv6 = preferIPv6;
  254. dnsClient.RandomizeName = randomizeName;
  255. dnsClient.Retries = RETRIES;
  256. dnsClient.Timeout = TIMEOUT;
  257. dnsClient.UdpPayloadSize = udpPayloadSize;
  258. dnsClient.DnssecValidation = dnssecValidation;
  259. dnsClient.EDnsClientSubnet = eDnsClientSubnet;
  260. if (dnssecValidation)
  261. {
  262. if ((type == DnsResourceRecordType.PTR) && IPAddress.TryParse(domain, out IPAddress ptrIp))
  263. domain = ptrIp.GetReverseDomain();
  264. //load trust anchors into dns client if domain is locally hosted
  265. _dnsWebService.DnsServer.AuthZoneManager.LoadTrustAnchorsTo(dnsClient, domain, type);
  266. }
  267. try
  268. {
  269. dnsResponse = await dnsClient.ResolveAsync(domain, type);
  270. }
  271. catch (DnsClientResponseDnssecValidationException ex)
  272. {
  273. dnsResponse = ex.Response;
  274. dnssecErrorMessage = ex.Message;
  275. importResponse = false;
  276. }
  277. if (type == DnsResourceRecordType.AXFR)
  278. dnsResponse = dnsResponse.Join();
  279. }
  280. if (importResponse)
  281. {
  282. bool isZoneImport = false;
  283. if (type == DnsResourceRecordType.AXFR)
  284. {
  285. isZoneImport = true;
  286. }
  287. else
  288. {
  289. foreach (DnsResourceRecord record in dnsResponse.Answer)
  290. {
  291. if (record.Type == DnsResourceRecordType.SOA)
  292. {
  293. if (record.Name.Equals(domain, StringComparison.OrdinalIgnoreCase))
  294. isZoneImport = true;
  295. break;
  296. }
  297. }
  298. }
  299. AuthZoneInfo zoneInfo = _dnsWebService.DnsServer.AuthZoneManager.FindAuthZoneInfo(domain);
  300. if ((zoneInfo is null) || ((zoneInfo.Type != AuthZoneType.Primary) && !zoneInfo.Name.Equals(domain, StringComparison.OrdinalIgnoreCase)) || (isZoneImport && !zoneInfo.Name.Equals(domain, StringComparison.OrdinalIgnoreCase)))
  301. {
  302. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Zones, session.User, PermissionFlag.Modify))
  303. throw new DnsWebServiceException("Access was denied.");
  304. zoneInfo = _dnsWebService.DnsServer.AuthZoneManager.CreatePrimaryZone(domain);
  305. if (zoneInfo is null)
  306. throw new DnsServerException("Cannot import records: failed to create primary zone.");
  307. //set permissions
  308. _dnsWebService._authManager.SetPermission(PermissionSection.Zones, zoneInfo.Name, session.User, PermissionFlag.ViewModifyDelete);
  309. _dnsWebService._authManager.SetPermission(PermissionSection.Zones, zoneInfo.Name, _dnsWebService._authManager.GetGroup(Group.ADMINISTRATORS), PermissionFlag.ViewModifyDelete);
  310. _dnsWebService._authManager.SetPermission(PermissionSection.Zones, zoneInfo.Name, _dnsWebService._authManager.GetGroup(Group.DNS_ADMINISTRATORS), PermissionFlag.ViewModifyDelete);
  311. _dnsWebService._authManager.SaveConfigFile();
  312. }
  313. else
  314. {
  315. if (!_dnsWebService._authManager.IsPermitted(PermissionSection.Zones, zoneInfo.Name, session.User, PermissionFlag.Modify))
  316. throw new DnsWebServiceException("Access was denied.");
  317. switch (zoneInfo.Type)
  318. {
  319. case AuthZoneType.Primary:
  320. break;
  321. case AuthZoneType.Forwarder:
  322. if (type == DnsResourceRecordType.AXFR)
  323. throw new DnsServerException("Cannot import records via zone transfer: import zone must be of primary type.");
  324. break;
  325. default:
  326. throw new DnsServerException("Cannot import records: import zone must be of primary or forwarder type.");
  327. }
  328. }
  329. if (type == DnsResourceRecordType.AXFR)
  330. {
  331. _dnsWebService.DnsServer.AuthZoneManager.SyncZoneTransferRecords(zoneInfo.Name, dnsResponse.Answer);
  332. }
  333. else
  334. {
  335. List<DnsResourceRecord> importRecords = new List<DnsResourceRecord>(dnsResponse.Answer.Count + dnsResponse.Authority.Count);
  336. foreach (DnsResourceRecord record in dnsResponse.Answer)
  337. {
  338. if (record.Name.Equals(zoneInfo.Name, StringComparison.OrdinalIgnoreCase) || record.Name.EndsWith("." + zoneInfo.Name, StringComparison.OrdinalIgnoreCase) || (zoneInfo.Name.Length == 0))
  339. {
  340. record.RemoveExpiry();
  341. importRecords.Add(record);
  342. if (record.Type == DnsResourceRecordType.NS)
  343. record.SyncGlueRecords(dnsResponse.Additional);
  344. }
  345. }
  346. foreach (DnsResourceRecord record in dnsResponse.Authority)
  347. {
  348. if (record.Name.Equals(zoneInfo.Name, StringComparison.OrdinalIgnoreCase) || record.Name.EndsWith("." + zoneInfo.Name, StringComparison.OrdinalIgnoreCase) || (zoneInfo.Name.Length == 0))
  349. {
  350. record.RemoveExpiry();
  351. importRecords.Add(record);
  352. if (record.Type == DnsResourceRecordType.NS)
  353. record.SyncGlueRecords(dnsResponse.Additional);
  354. }
  355. }
  356. _dnsWebService.DnsServer.AuthZoneManager.ImportRecords(zoneInfo.Name, importRecords, true, true);
  357. }
  358. _dnsWebService._log.Write(context.GetRemoteEndPoint(_dnsWebService._webServiceRealIpHeader), "[" + session.User.Username + "] DNS Client imported record(s) for authoritative zone {server: " + server + "; zone: " + zoneInfo.DisplayName + "; type: " + type + ";}");
  359. }
  360. Utf8JsonWriter jsonWriter = context.GetCurrentJsonWriter();
  361. if (dnssecErrorMessage is not null)
  362. jsonWriter.WriteString("warningMessage", dnssecErrorMessage);
  363. jsonWriter.WritePropertyName("result");
  364. dnsResponse.SerializeTo(jsonWriter);
  365. jsonWriter.WritePropertyName("rawResponses");
  366. jsonWriter.WriteStartArray();
  367. for (int i = 0; i < rawResponses.Count; i++)
  368. rawResponses[i].SerializeTo(jsonWriter);
  369. jsonWriter.WriteEndArray();
  370. }
  371. #endregion
  372. }
  373. }