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