WebServiceApi.cs 17 KB

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