AuthZoneTree.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  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.Dns.Zones;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Threading;
  19. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  20. namespace DnsServerCore.Dns.Trees
  21. {
  22. class AuthZoneTree : ZoneTree<AuthZoneNode, SubDomainZone, ApexZone>
  23. {
  24. #region variables
  25. static readonly char[] _starPeriodTrimChars = new char[] { '*', '.' };
  26. #endregion
  27. #region private
  28. private static Node GetPreviousSubDomainZoneNode(byte[] key, Node currentNode, int baseDepth)
  29. {
  30. int k;
  31. NodeValue currentValue = currentNode.Value;
  32. if (currentValue is null)
  33. {
  34. //key value does not exists
  35. if (currentNode.Children is null)
  36. {
  37. //no children available; move to previous sibling
  38. k = currentNode.K - 1; //find previous node from sibling starting at k - 1
  39. currentNode = currentNode.Parent;
  40. }
  41. else
  42. {
  43. if (key.Length == currentNode.Depth)
  44. {
  45. //current node belongs to the key
  46. k = currentNode.K - 1; //find previous node from sibling starting at k - 1
  47. currentNode = currentNode.Parent;
  48. }
  49. else
  50. {
  51. //find the previous node for the given k in current node's children
  52. k = key[currentNode.Depth];
  53. }
  54. }
  55. }
  56. else
  57. {
  58. int x = DnsNSECRecordData.CanonicalComparison(currentValue.Key, key);
  59. if (x == 0)
  60. {
  61. //current node value matches the key
  62. k = currentNode.K - 1; //find previous node from sibling starting at k - 1
  63. currentNode = currentNode.Parent;
  64. }
  65. else if (x > 0)
  66. {
  67. //current node value is larger for the key
  68. k = currentNode.K - 1; //find previous node from sibling starting at k - 1
  69. currentNode = currentNode.Parent;
  70. }
  71. else
  72. {
  73. //current node value is smaller for the key
  74. if (currentNode.Children is null)
  75. {
  76. //the current node is previous node since no children exists and value is smaller for the key
  77. return currentNode;
  78. }
  79. else
  80. {
  81. //find the previous node for the given k in current node's children
  82. k = key[currentNode.Depth];
  83. }
  84. }
  85. }
  86. //start reverse tree traversal
  87. while ((currentNode is not null) && (currentNode.Depth >= baseDepth))
  88. {
  89. Node[] children = currentNode.Children;
  90. if (children is not null)
  91. {
  92. //find previous child node
  93. Node child = null;
  94. for (int i = k; i > -1; i--)
  95. {
  96. child = Volatile.Read(ref children[i]);
  97. if (child is not null)
  98. {
  99. bool childNodeHasApexZone = false;
  100. NodeValue childValue = child.Value;
  101. if (childValue is not null)
  102. {
  103. AuthZoneNode authZoneNode = childValue.Value;
  104. if (authZoneNode is not null)
  105. {
  106. if (authZoneNode.ApexZone is not null)
  107. childNodeHasApexZone = true; //must stop checking children of the apex of the sub zone
  108. }
  109. }
  110. if (!childNodeHasApexZone && child.Children is not null)
  111. break; //child has further children so check them first
  112. if (childValue is not null)
  113. {
  114. AuthZoneNode authZoneNode = childValue.Value;
  115. if (authZoneNode is not null)
  116. {
  117. if (authZoneNode.ParentSideZone is not null)
  118. {
  119. //is sub domain zone
  120. return child; //child has value so return it
  121. }
  122. if (authZoneNode.ApexZone is not null)
  123. {
  124. //is apex zone
  125. //skip to next child to avoid listing this auth zone's sub domains
  126. child = null; //set null to avoid child being set as current after the loop
  127. }
  128. }
  129. }
  130. }
  131. }
  132. if (child is not null)
  133. {
  134. //make found child as current
  135. k = children.Length - 1;
  136. currentNode = child;
  137. continue; //start over
  138. }
  139. }
  140. //no child node available; check for current node value
  141. {
  142. NodeValue value = currentNode.Value;
  143. if (value is not null)
  144. {
  145. AuthZoneNode authZoneNode = value.Value;
  146. if (authZoneNode is not null)
  147. {
  148. if ((authZoneNode.ApexZone is not null) && (currentNode.Depth == baseDepth))
  149. {
  150. //current node contains apex zone for the base depth i.e. current zone; return it
  151. return currentNode;
  152. }
  153. if (authZoneNode.ParentSideZone is not null)
  154. {
  155. //current node contains sub domain zone; return it
  156. return currentNode;
  157. }
  158. }
  159. }
  160. }
  161. //move up to parent node for previous sibling
  162. k = currentNode.K - 1;
  163. currentNode = currentNode.Parent;
  164. }
  165. return null;
  166. }
  167. private static Node GetNextSubDomainZoneNode(byte[] key, Node currentNode, int baseDepth)
  168. {
  169. int k;
  170. NodeValue currentValue = currentNode.Value;
  171. if (currentValue is null)
  172. {
  173. //key value does not exists
  174. if (currentNode.Children is null)
  175. {
  176. //no children available; move to next sibling
  177. k = currentNode.K + 1; //find next node from sibling starting at k + 1
  178. currentNode = currentNode.Parent;
  179. }
  180. else
  181. {
  182. if (key.Length == currentNode.Depth)
  183. {
  184. //current node belongs to the key
  185. k = 0; //find next node from first child of current node
  186. }
  187. else
  188. {
  189. //find next node for the given k in current node's children
  190. k = key[currentNode.Depth];
  191. }
  192. }
  193. }
  194. else
  195. {
  196. //check if node contains apex zone
  197. bool foundApexZone = false;
  198. if (currentNode.Depth > baseDepth)
  199. {
  200. AuthZoneNode authZoneNode = currentValue.Value;
  201. if (authZoneNode is not null)
  202. {
  203. ApexZone apexZone = authZoneNode.ApexZone;
  204. if (apexZone is not null)
  205. foundApexZone = true;
  206. }
  207. }
  208. if (foundApexZone)
  209. {
  210. //current contains apex for a sub zone; move up to parent node
  211. k = currentNode.K + 1; //find next node from sibling starting at k + 1
  212. currentNode = currentNode.Parent;
  213. }
  214. else
  215. {
  216. int x = DnsNSECRecordData.CanonicalComparison(currentValue.Key, key);
  217. if (x == 0)
  218. {
  219. //current node value matches the key
  220. k = 0; //find next node from children starting at k
  221. }
  222. else if (x > 0)
  223. {
  224. //current node value is larger for the key thus current is the next node
  225. return currentNode;
  226. }
  227. else
  228. {
  229. //current node value is smaller for the key
  230. k = key[currentNode.Depth]; //find next node from children starting at k = key[depth]
  231. }
  232. }
  233. }
  234. //start tree traversal
  235. while ((currentNode is not null) && (currentNode.Depth >= baseDepth))
  236. {
  237. Node[] children = currentNode.Children;
  238. if (children is not null)
  239. {
  240. //find next child node
  241. Node child = null;
  242. for (int i = k; i < children.Length; i++)
  243. {
  244. child = Volatile.Read(ref children[i]);
  245. if (child is not null)
  246. {
  247. NodeValue childValue = child.Value;
  248. if (childValue is not null)
  249. {
  250. AuthZoneNode authZoneNode = childValue.Value;
  251. if (authZoneNode is not null)
  252. {
  253. if (authZoneNode.ParentSideZone is not null)
  254. {
  255. //is sub domain zone
  256. return child; //child has value so return it
  257. }
  258. if (authZoneNode.ApexZone is not null)
  259. {
  260. //is apex zone
  261. //skip to next child to avoid listing this auth zone's sub domains
  262. child = null; //set null to avoid child being set as current after the loop
  263. continue;
  264. }
  265. }
  266. }
  267. if (child.Children is not null)
  268. break;
  269. }
  270. }
  271. if (child is not null)
  272. {
  273. //make found child as current
  274. k = 0;
  275. currentNode = child;
  276. continue; //start over
  277. }
  278. }
  279. //no child nodes available; move up to parent node
  280. k = currentNode.K + 1;
  281. currentNode = currentNode.Parent;
  282. }
  283. return null;
  284. }
  285. private static bool SubDomainExists(byte[] key, Node currentNode)
  286. {
  287. Node[] children = currentNode.Children;
  288. if (children is not null)
  289. {
  290. Node child = Volatile.Read(ref children[1]); //[*]
  291. if (child is not null)
  292. return true; //wildcard exists so subdomain name exists: RFC 4592 section 4.9
  293. }
  294. Node nextSubDomain = GetNextSubDomainZoneNode(key, currentNode, currentNode.Depth);
  295. if (nextSubDomain is null)
  296. return false;
  297. NodeValue value = nextSubDomain.Value;
  298. if (value is null)
  299. return false;
  300. return IsKeySubDomain(key, value.Key, false);
  301. }
  302. private static AuthZone GetAuthZoneFromNode(Node node, string zoneName)
  303. {
  304. NodeValue value = node.Value;
  305. if (value is not null)
  306. {
  307. AuthZoneNode authZoneNode = value.Value;
  308. if (authZoneNode is not null)
  309. return authZoneNode.GetAuthZone(zoneName);
  310. }
  311. return null;
  312. }
  313. private void RemoveAllSubDomains(string domain, Node currentNode)
  314. {
  315. //remove all sub domains under current zone
  316. Node current = currentNode;
  317. byte[] currentKey = ConvertToByteKey(domain);
  318. do
  319. {
  320. current = GetNextSubDomainZoneNode(currentKey, current, currentNode.Depth);
  321. if (current is null)
  322. break;
  323. NodeValue v = current.Value;
  324. if (v is not null)
  325. {
  326. AuthZoneNode z = v.Value;
  327. if (z is not null)
  328. {
  329. if (z.ApexZone is null)
  330. {
  331. //no apex zone at this node; remove complete zone node
  332. current.RemoveNodeValue(v.Key, out _); //remove node value
  333. current.CleanThisBranch();
  334. }
  335. else
  336. {
  337. //apex node exists; remove parent size sub domain
  338. z.TryRemove(out SubDomainZone _);
  339. }
  340. }
  341. currentKey = v.Key;
  342. }
  343. }
  344. while (true);
  345. }
  346. #endregion
  347. #region protected
  348. protected override void GetClosestValuesForZone(AuthZoneNode zoneValue, out SubDomainZone closestSubDomain, out SubDomainZone closestDelegation, out ApexZone closestAuthority)
  349. {
  350. ApexZone apexZone = zoneValue.ApexZone;
  351. if (apexZone is not null)
  352. {
  353. //hosted primary/secondary/stub/forwarder zone found
  354. closestSubDomain = null;
  355. closestDelegation = zoneValue.ParentSideZone;
  356. closestAuthority = apexZone;
  357. }
  358. else
  359. {
  360. //hosted sub domain
  361. SubDomainZone subDomainZone = zoneValue.ParentSideZone;
  362. if (subDomainZone.ContainsNameServerRecords())
  363. {
  364. //delegated sub domain found
  365. closestSubDomain = null;
  366. closestDelegation = subDomainZone;
  367. }
  368. else
  369. {
  370. closestSubDomain = subDomainZone;
  371. closestDelegation = null;
  372. }
  373. closestAuthority = null;
  374. }
  375. }
  376. #endregion
  377. #region public
  378. public bool TryAdd(ApexZone zone)
  379. {
  380. AuthZoneNode zoneNode = GetOrAdd(zone.Name, delegate (string key)
  381. {
  382. return new AuthZoneNode(null, zone);
  383. });
  384. if (ReferenceEquals(zoneNode.ApexZone, zone))
  385. return true; //added successfully
  386. return zoneNode.TryAdd(zone);
  387. }
  388. public bool TryGet(string zoneName, string domain, out AuthZone authZone)
  389. {
  390. if (TryGet(domain, out AuthZoneNode authZoneNode))
  391. {
  392. authZone = authZoneNode.GetAuthZone(zoneName);
  393. return authZone is not null;
  394. }
  395. authZone = null;
  396. return false;
  397. }
  398. public bool TryGet(string zoneName, out ApexZone apexZone)
  399. {
  400. if (TryGet(zoneName, out AuthZoneNode authZoneNode) && (authZoneNode.ApexZone is not null))
  401. {
  402. apexZone = authZoneNode.ApexZone;
  403. return true;
  404. }
  405. apexZone = null;
  406. return false;
  407. }
  408. public bool TryRemove(string domain, out ApexZone apexZone)
  409. {
  410. if (!TryGet(domain, out AuthZoneNode authZoneNode, out Node currentNode) || (authZoneNode.ApexZone is null))
  411. {
  412. apexZone = null;
  413. return false;
  414. }
  415. apexZone = authZoneNode.ApexZone;
  416. if (authZoneNode.ParentSideZone is null)
  417. {
  418. //remove complete zone node
  419. if (!base.TryRemove(domain, out AuthZoneNode _))
  420. {
  421. apexZone = null;
  422. return false;
  423. }
  424. }
  425. else
  426. {
  427. //parent side sub domain exists; remove only apex zone from zone node
  428. if (!authZoneNode.TryRemove(out ApexZone _))
  429. {
  430. apexZone = null;
  431. return false;
  432. }
  433. }
  434. //remove all sub domains under current apex zone
  435. RemoveAllSubDomains(domain, currentNode);
  436. currentNode.CleanThisBranch();
  437. return true;
  438. }
  439. public bool TryRemove(string domain, out SubDomainZone subDomainZone, bool removeAllSubDomains = false)
  440. {
  441. if (!TryGet(domain, out AuthZoneNode zoneNode, out Node currentNode) || (zoneNode.ParentSideZone is null))
  442. {
  443. subDomainZone = null;
  444. return false;
  445. }
  446. subDomainZone = zoneNode.ParentSideZone;
  447. if (zoneNode.ApexZone is null)
  448. {
  449. //remove complete zone node
  450. if (!base.TryRemove(domain, out AuthZoneNode _))
  451. {
  452. subDomainZone = null;
  453. return false;
  454. }
  455. }
  456. else
  457. {
  458. //apex zone exists; remove only parent side sub domain from zone node
  459. if (!zoneNode.TryRemove(out SubDomainZone _))
  460. {
  461. subDomainZone = null;
  462. return false;
  463. }
  464. }
  465. if (removeAllSubDomains)
  466. RemoveAllSubDomains(domain, currentNode); //remove all sub domains under current subdomain zone
  467. currentNode.CleanThisBranch();
  468. return true;
  469. }
  470. public override bool TryRemove(string key, out AuthZoneNode authZoneNode)
  471. {
  472. throw new InvalidOperationException();
  473. }
  474. public IReadOnlyList<AuthZone> GetApexZoneWithSubDomainZones(string zoneName)
  475. {
  476. List<AuthZone> zones = new List<AuthZone>();
  477. byte[] key = ConvertToByteKey(zoneName);
  478. NodeValue nodeValue = _root.FindNodeValue(key, out Node currentNode);
  479. if (nodeValue is not null)
  480. {
  481. AuthZoneNode authZoneNode = nodeValue.Value;
  482. if (authZoneNode is not null)
  483. {
  484. ApexZone apexZone = authZoneNode.ApexZone;
  485. if (apexZone is not null)
  486. {
  487. zones.Add(apexZone);
  488. Node current = currentNode;
  489. byte[] currentKey = key;
  490. do
  491. {
  492. current = GetNextSubDomainZoneNode(currentKey, current, currentNode.Depth);
  493. if (current is null)
  494. break;
  495. NodeValue value = current.Value;
  496. if (value is not null)
  497. {
  498. authZoneNode = value.Value;
  499. if (authZoneNode is not null)
  500. zones.Add(authZoneNode.ParentSideZone);
  501. currentKey = value.Key;
  502. }
  503. }
  504. while (true);
  505. }
  506. }
  507. }
  508. return zones;
  509. }
  510. public IReadOnlyList<AuthZone> GetSubDomainZoneWithSubDomainZones(string domain)
  511. {
  512. List<AuthZone> zones = new List<AuthZone>();
  513. byte[] key = ConvertToByteKey(domain);
  514. NodeValue nodeValue = _root.FindNodeValue(key, out Node currentNode);
  515. if (nodeValue is not null)
  516. {
  517. AuthZoneNode authZoneNode = nodeValue.Value;
  518. if (authZoneNode is not null)
  519. {
  520. SubDomainZone subDomainZone = authZoneNode.ParentSideZone;
  521. if (subDomainZone is not null)
  522. {
  523. zones.Add(subDomainZone);
  524. Node current = currentNode;
  525. byte[] currentKey = key;
  526. do
  527. {
  528. current = GetNextSubDomainZoneNode(currentKey, current, currentNode.Depth);
  529. if (current is null)
  530. break;
  531. NodeValue value = current.Value;
  532. if (value is not null)
  533. {
  534. authZoneNode = value.Value;
  535. if (authZoneNode is not null)
  536. zones.Add(authZoneNode.ParentSideZone);
  537. currentKey = value.Key;
  538. }
  539. }
  540. while (true);
  541. }
  542. }
  543. }
  544. return zones;
  545. }
  546. public AuthZone GetOrAddSubDomainZone(string zoneName, string domain, Func<SubDomainZone> valueFactory)
  547. {
  548. bool isApex = zoneName.Equals(domain, StringComparison.OrdinalIgnoreCase);
  549. AuthZoneNode authZoneNode = GetOrAdd(domain, delegate (string key)
  550. {
  551. if (isApex)
  552. throw new DnsServerException("Zone was not found for domain: " + key);
  553. return new AuthZoneNode(valueFactory(), null);
  554. });
  555. if (isApex)
  556. {
  557. if (authZoneNode.ApexZone is null)
  558. throw new DnsServerException("Zone was not found: " + zoneName);
  559. return authZoneNode.ApexZone;
  560. }
  561. else
  562. {
  563. return authZoneNode.GetOrAddParentSideZone(valueFactory);
  564. }
  565. }
  566. public AuthZone GetAuthZone(string zoneName, string domain)
  567. {
  568. if (TryGet(domain, out AuthZoneNode authZoneNode))
  569. return authZoneNode.GetAuthZone(zoneName);
  570. return null;
  571. }
  572. public ApexZone GetApexZone(string zoneName)
  573. {
  574. if (TryGet(zoneName, out AuthZoneNode authZoneNode))
  575. return authZoneNode.ApexZone;
  576. return null;
  577. }
  578. public AuthZone FindZone(string domain, out SubDomainZone closest, out SubDomainZone delegation, out ApexZone authority, out bool hasSubDomains)
  579. {
  580. byte[] key = ConvertToByteKey(domain);
  581. AuthZoneNode authZoneNode = FindZoneNode(key, true, out Node currentNode, out Node closestSubDomainNode, out _, out SubDomainZone closestSubDomain, out SubDomainZone closestDelegation, out ApexZone closestAuthority);
  582. if (authZoneNode is null)
  583. {
  584. //zone not found
  585. closest = closestSubDomain;
  586. delegation = closestDelegation;
  587. authority = closestAuthority;
  588. if (authority is null)
  589. {
  590. //no authority so no sub domains
  591. hasSubDomains = false;
  592. }
  593. else if ((closestSubDomainNode is not null) && !closestSubDomainNode.HasChildren)
  594. {
  595. //closest sub domain node does not have any children so no sub domains
  596. hasSubDomains = false;
  597. }
  598. else
  599. {
  600. //check if current node has sub domains
  601. hasSubDomains = SubDomainExists(key, currentNode);
  602. }
  603. return null;
  604. }
  605. else
  606. {
  607. //zone found
  608. AuthZone zone;
  609. ApexZone apexZone = authZoneNode.ApexZone;
  610. if (apexZone is not null)
  611. {
  612. zone = apexZone;
  613. closest = null;
  614. delegation = authZoneNode.ParentSideZone;
  615. authority = apexZone;
  616. }
  617. else
  618. {
  619. SubDomainZone subDomainZone = authZoneNode.ParentSideZone;
  620. zone = subDomainZone;
  621. if (zone == closestSubDomain)
  622. closest = null;
  623. else
  624. closest = closestSubDomain;
  625. if (closestDelegation is not null)
  626. delegation = closestDelegation;
  627. else if (subDomainZone.ContainsNameServerRecords())
  628. delegation = subDomainZone;
  629. else
  630. delegation = null;
  631. authority = closestAuthority;
  632. }
  633. if (zone.Disabled)
  634. {
  635. if ((closestSubDomainNode is not null) && !closestSubDomainNode.HasChildren)
  636. {
  637. //closest sub domain node does not have any children so no sub domains
  638. hasSubDomains = false;
  639. }
  640. else
  641. {
  642. //check if current node has sub domains
  643. hasSubDomains = SubDomainExists(key, currentNode);
  644. }
  645. }
  646. else
  647. {
  648. //since zone is found, it does not matter if subdomain exists or not
  649. hasSubDomains = false;
  650. }
  651. return zone;
  652. }
  653. }
  654. public AuthZone FindPreviousSubDomainZone(string zoneName, string domain)
  655. {
  656. byte[] key = ConvertToByteKey(domain);
  657. AuthZoneNode authZoneNode = FindZoneNode(key, false, out Node currentNode, out _, out Node closestAuthorityNode, out _, out _, out _);
  658. if (authZoneNode is not null)
  659. {
  660. //zone exists
  661. ApexZone apexZone = authZoneNode.ApexZone;
  662. SubDomainZone parentSideZone = authZoneNode.ParentSideZone;
  663. if ((apexZone is not null) && (parentSideZone is not null))
  664. {
  665. //found ambiguity between apex zone and sub domain zone
  666. if (!apexZone.Name.Equals(zoneName, StringComparison.OrdinalIgnoreCase))
  667. {
  668. //zone name does not match with apex zone and thus not match with closest authority node
  669. //find the closest authority zone for given zone name
  670. if (!TryGet(zoneName, out _, out Node closestNodeForZoneName))
  671. throw new InvalidOperationException();
  672. closestAuthorityNode = closestNodeForZoneName;
  673. }
  674. }
  675. }
  676. Node previousNode = GetPreviousSubDomainZoneNode(key, currentNode, closestAuthorityNode.Depth);
  677. if (previousNode is not null)
  678. {
  679. AuthZone authZone = GetAuthZoneFromNode(previousNode, zoneName);
  680. if (authZone is not null)
  681. return authZone;
  682. }
  683. return null;
  684. }
  685. public AuthZone FindNextSubDomainZone(string zoneName, string domain)
  686. {
  687. byte[] key = ConvertToByteKey(domain);
  688. AuthZoneNode authZoneNode = FindZoneNode(key, false, out Node currentNode, out _, out Node closestAuthorityNode, out _, out _, out _);
  689. if (authZoneNode is not null)
  690. {
  691. //zone exists
  692. ApexZone apexZone = authZoneNode.ApexZone;
  693. SubDomainZone parentSideZone = authZoneNode.ParentSideZone;
  694. if ((apexZone is not null) && (parentSideZone is not null))
  695. {
  696. //found ambiguity between apex zone and sub domain zone
  697. if (!apexZone.Name.Equals(zoneName, StringComparison.OrdinalIgnoreCase))
  698. {
  699. //zone name does not match with apex zone and thus not match with closest authority node
  700. //find the closest authority zone for given zone name
  701. if (!TryGet(zoneName, out _, out Node closestNodeForZoneName))
  702. throw new InvalidOperationException();
  703. closestAuthorityNode = closestNodeForZoneName;
  704. }
  705. }
  706. }
  707. Node nextNode = GetNextSubDomainZoneNode(key, currentNode, closestAuthorityNode.Depth);
  708. if (nextNode is not null)
  709. {
  710. AuthZone authZone = GetAuthZoneFromNode(nextNode, zoneName);
  711. if (authZone is not null)
  712. return authZone;
  713. }
  714. return null;
  715. }
  716. public bool SubDomainExistsFor(string zoneName, string domain)
  717. {
  718. AuthZone nextAuthZone = FindNextSubDomainZone(zoneName, domain);
  719. if (nextAuthZone is null)
  720. return false;
  721. return nextAuthZone.Name.EndsWith("." + domain);
  722. }
  723. #endregion
  724. #region DNSSEC
  725. public IReadOnlyList<DnsResourceRecord> FindNSecProofOfNonExistenceNxDomain(string domain, bool isWildcardAnswer)
  726. {
  727. List<DnsResourceRecord> nsecRecords = new List<DnsResourceRecord>(2 * 2);
  728. void AddProofOfCoverFor(string domain)
  729. {
  730. byte[] key = ConvertToByteKey(domain);
  731. AuthZoneNode authZoneNode = FindZoneNode(key, false, out Node currentNode, out _, out Node closestAuthorityNode, out _, out _, out ApexZone closestAuthority);
  732. if (authZoneNode is not null)
  733. throw new InvalidOperationException(); //domain exists! cannot prove non-existence
  734. Node previousNode = GetPreviousSubDomainZoneNode(key, currentNode, closestAuthorityNode.Depth);
  735. if (previousNode is not null)
  736. {
  737. AuthZone authZone = GetAuthZoneFromNode(previousNode, closestAuthority.Name);
  738. if (authZone is not null)
  739. {
  740. IReadOnlyList<DnsResourceRecord> proofOfCoverRecords = authZone.QueryRecords(DnsResourceRecordType.NSEC, true);
  741. foreach (DnsResourceRecord proofOfCoverRecord in proofOfCoverRecords)
  742. {
  743. if (!nsecRecords.Contains(proofOfCoverRecord))
  744. nsecRecords.Add(proofOfCoverRecord);
  745. }
  746. }
  747. }
  748. }
  749. //add proof of cover for domain
  750. AddProofOfCoverFor(domain);
  751. if (isWildcardAnswer)
  752. return nsecRecords;
  753. //add proof of cover for wildcard
  754. if (nsecRecords.Count > 0)
  755. {
  756. //add wildcard proof to prove that a wildcard expansion was not possible
  757. DnsResourceRecord nsecRecord = nsecRecords[0];
  758. DnsNSECRecordData nsec = nsecRecord.RDATA as DnsNSECRecordData;
  759. string wildcardName = DnsNSECRecordData.GetWildcardFor(nsecRecord, domain);
  760. if (!DnsNSECRecordData.IsDomainCovered(nsecRecord.Name, nsec.NextDomainName, wildcardName))
  761. AddProofOfCoverFor(wildcardName);
  762. }
  763. return nsecRecords;
  764. }
  765. public IReadOnlyList<DnsResourceRecord> FindNSec3ProofOfNonExistenceNxDomain(string domain, bool isWildcardAnswer, CancellationToken cancellationToken)
  766. {
  767. List<DnsResourceRecord> nsec3Records = new List<DnsResourceRecord>(3 * 2);
  768. void AddProofOfCoverFor(string hashedOwnerName, string zoneName)
  769. {
  770. //find previous NSEC3 for the hashed owner name
  771. IReadOnlyList<DnsResourceRecord> proofOfCoverRecords = null;
  772. string currentOwnerName = hashedOwnerName;
  773. while (true)
  774. {
  775. cancellationToken.ThrowIfCancellationRequested();
  776. AuthZone previousNSec3Zone = FindPreviousSubDomainZone(zoneName, currentOwnerName);
  777. if (previousNSec3Zone is null)
  778. break;
  779. IReadOnlyList<DnsResourceRecord> previousNSec3Records = previousNSec3Zone.QueryRecords(DnsResourceRecordType.NSEC3, true);
  780. if (previousNSec3Records.Count > 0)
  781. {
  782. proofOfCoverRecords = previousNSec3Records;
  783. break;
  784. }
  785. currentOwnerName = previousNSec3Zone.Name;
  786. }
  787. if (proofOfCoverRecords is null)
  788. {
  789. //didnt find previous NSEC3; find the last NSEC3
  790. currentOwnerName = hashedOwnerName;
  791. while (true)
  792. {
  793. cancellationToken.ThrowIfCancellationRequested();
  794. AuthZone nextNSec3Zone = GetAuthZone(zoneName, currentOwnerName);
  795. if (nextNSec3Zone is null)
  796. {
  797. nextNSec3Zone = FindNextSubDomainZone(zoneName, currentOwnerName);
  798. if (nextNSec3Zone is null)
  799. break;
  800. }
  801. IReadOnlyList<DnsResourceRecord> nextNSec3Records = nextNSec3Zone.QueryRecords(DnsResourceRecordType.NSEC3, true);
  802. if (nextNSec3Records.Count > 0)
  803. {
  804. proofOfCoverRecords = nextNSec3Records;
  805. DnsResourceRecord previousNSec3Record = nextNSec3Records[0];
  806. string nextHashedOwnerNameString = (previousNSec3Record.RDATA as DnsNSEC3RecordData).NextHashedOwnerName + (zoneName.Length > 0 ? "." + zoneName : "");
  807. if (DnsNSECRecordData.CanonicalComparison(previousNSec3Record.Name, nextHashedOwnerNameString) >= 0)
  808. break; //found last NSEC3
  809. //jump to next hashed owner
  810. currentOwnerName = nextHashedOwnerNameString;
  811. }
  812. else
  813. {
  814. currentOwnerName = nextNSec3Zone.Name;
  815. }
  816. }
  817. }
  818. if (proofOfCoverRecords is null)
  819. throw new InvalidOperationException();
  820. foreach (DnsResourceRecord proofOfCoverRecord in proofOfCoverRecords)
  821. {
  822. if (!nsec3Records.Contains(proofOfCoverRecord))
  823. nsec3Records.Add(proofOfCoverRecord);
  824. }
  825. }
  826. byte[] key = ConvertToByteKey(domain);
  827. string closestEncloser;
  828. AuthZoneNode authZoneNode = FindZoneNode(key, isWildcardAnswer, out _, out _, out _, out SubDomainZone closestSubDomain, out _, out ApexZone closestAuthority);
  829. if (authZoneNode is not null)
  830. {
  831. if (isWildcardAnswer && (closestSubDomain is not null) && closestSubDomain.Name.StartsWith('*'))
  832. {
  833. closestEncloser = closestSubDomain.Name.TrimStart(_starPeriodTrimChars);
  834. }
  835. else
  836. {
  837. //subdomain that contains only NSEC3 record does not really exists: RFC5155 section 7.2.8
  838. if ((authZoneNode.ApexZone is not null) || ((authZoneNode.ParentSideZone is not null) && !authZoneNode.ParentSideZone.HasOnlyNSec3Records()))
  839. throw new InvalidOperationException(); //domain exists! cannot prove non-existence
  840. //continue to prove non-existence of this nsec3 owner name
  841. closestEncloser = closestAuthority.Name;
  842. }
  843. }
  844. else
  845. {
  846. if (closestSubDomain is not null)
  847. closestEncloser = closestSubDomain.Name;
  848. else if (closestAuthority is not null)
  849. closestEncloser = closestAuthority.Name;
  850. else
  851. throw new InvalidOperationException(); //cannot find closest encloser
  852. }
  853. IReadOnlyList<DnsResourceRecord> nsec3ParamRecords = closestAuthority.GetRecords(DnsResourceRecordType.NSEC3PARAM);
  854. if (nsec3ParamRecords.Count == 0)
  855. throw new InvalidOperationException("Zone does not have NSEC3 deployed.");
  856. DnsNSEC3PARAMRecordData nsec3Param = nsec3ParamRecords[0].RDATA as DnsNSEC3PARAMRecordData;
  857. //find correct closest encloser
  858. string hashedNextCloserName;
  859. while (true)
  860. {
  861. cancellationToken.ThrowIfCancellationRequested();
  862. string nextCloserName = DnsNSEC3RecordData.GetNextCloserName(domain, closestEncloser);
  863. hashedNextCloserName = nsec3Param.ComputeHashedOwnerNameBase32HexString(nextCloserName) + (closestAuthority.Name.Length > 0 ? "." + closestAuthority.Name : "");
  864. AuthZone nsec3Zone = GetAuthZone(closestAuthority.Name, hashedNextCloserName);
  865. if (nsec3Zone is null)
  866. break; //next closer name does not exists
  867. //next closer name exists as an ENT
  868. closestEncloser = nextCloserName;
  869. if (domain.Equals(closestEncloser, StringComparison.OrdinalIgnoreCase))
  870. {
  871. //domain exists as an ENT; return no data proof
  872. return FindNSec3ProofOfNonExistenceNoData(nsec3Zone);
  873. }
  874. }
  875. if (isWildcardAnswer)
  876. {
  877. //add proof of cover for the domain to prove non-existence (wildcard)
  878. AddProofOfCoverFor(hashedNextCloserName, closestAuthority.Name);
  879. }
  880. else
  881. {
  882. //add closest encloser proof
  883. string hashedClosestEncloser = nsec3Param.ComputeHashedOwnerNameBase32HexString(closestEncloser) + (closestAuthority.Name.Length > 0 ? "." + closestAuthority.Name : "");
  884. AuthZone nsec3Zone = GetAuthZone(closestAuthority.Name, hashedClosestEncloser);
  885. if (nsec3Zone is null)
  886. throw new InvalidOperationException();
  887. IReadOnlyList<DnsResourceRecord> closestEncloserProofRecords = nsec3Zone.QueryRecords(DnsResourceRecordType.NSEC3, true);
  888. if (closestEncloserProofRecords.Count == 0)
  889. throw new InvalidOperationException();
  890. nsec3Records.AddRange(closestEncloserProofRecords);
  891. DnsResourceRecord closestEncloserProofRecord = closestEncloserProofRecords[0];
  892. DnsNSEC3RecordData closestEncloserProof = closestEncloserProofRecord.RDATA as DnsNSEC3RecordData;
  893. //add proof of cover for the next closer name
  894. if (!DnsNSECRecordData.IsDomainCovered(closestEncloserProofRecord.Name, closestEncloserProof.NextHashedOwnerName + (closestAuthority.Name.Length > 0 ? "." + closestAuthority.Name : ""), hashedNextCloserName))
  895. AddProofOfCoverFor(hashedNextCloserName, closestAuthority.Name);
  896. //add proof of cover to prove that a wildcard expansion was not possible
  897. string wildcardDomain = closestEncloser.Length > 0 ? "*." + closestEncloser : "*";
  898. string hashedWildcardDomainName = nsec3Param.ComputeHashedOwnerNameBase32HexString(wildcardDomain) + (closestAuthority.Name.Length > 0 ? "." + closestAuthority.Name : "");
  899. if (!DnsNSECRecordData.IsDomainCovered(closestEncloserProofRecord.Name, closestEncloserProof.NextHashedOwnerName + (closestAuthority.Name.Length > 0 ? "." + closestAuthority.Name : ""), hashedWildcardDomainName))
  900. AddProofOfCoverFor(hashedWildcardDomainName, closestAuthority.Name);
  901. }
  902. return nsec3Records;
  903. }
  904. public static IReadOnlyList<DnsResourceRecord> FindNSecProofOfNonExistenceNoData(AuthZone zone)
  905. {
  906. IReadOnlyList<DnsResourceRecord> nsecRecords = zone.QueryRecords(DnsResourceRecordType.NSEC, true);
  907. if (nsecRecords.Count == 0)
  908. throw new InvalidOperationException("Zone does not have NSEC deployed correctly.");
  909. return nsecRecords;
  910. }
  911. public IReadOnlyList<DnsResourceRecord> FindNSec3ProofOfNonExistenceNoData(AuthZone zone, ApexZone apexZone, CancellationToken cancellationToken)
  912. {
  913. IReadOnlyList<DnsResourceRecord> nsec3ParamRecords = apexZone.GetRecords(DnsResourceRecordType.NSEC3PARAM);
  914. if (nsec3ParamRecords.Count == 0)
  915. throw new InvalidOperationException("Zone does not have NSEC3 deployed.");
  916. DnsNSEC3PARAMRecordData nsec3Param = nsec3ParamRecords[0].RDATA as DnsNSEC3PARAMRecordData;
  917. string hashedOwnerName = nsec3Param.ComputeHashedOwnerNameBase32HexString(zone.Name) + (apexZone.Name.Length > 0 ? "." + apexZone.Name : "");
  918. AuthZone nsec3Zone = GetAuthZone(apexZone.Name, hashedOwnerName);
  919. if (nsec3Zone is null)
  920. {
  921. //this is probably since the domain in request is for an nsec3 record owner name
  922. return FindNSec3ProofOfNonExistenceNxDomain(zone.Name, false, cancellationToken);
  923. }
  924. return FindNSec3ProofOfNonExistenceNoData(nsec3Zone);
  925. }
  926. private static IReadOnlyList<DnsResourceRecord> FindNSec3ProofOfNonExistenceNoData(AuthZone nsec3Zone)
  927. {
  928. IReadOnlyList<DnsResourceRecord> nsec3Records = nsec3Zone.QueryRecords(DnsResourceRecordType.NSEC3, true);
  929. if (nsec3Records.Count > 0)
  930. return nsec3Records;
  931. return Array.Empty<DnsResourceRecord>();
  932. }
  933. #endregion
  934. }
  935. }