PrimaryZone.cs 122 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989
  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.Dnssec;
  16. using DnsServerCore.Dns.ResourceRecords;
  17. using DnsServerCore.Dns.ZoneManagers;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Security.Cryptography;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. using TechnitiumLibrary.Net.Dns;
  24. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  25. namespace DnsServerCore.Dns.Zones
  26. {
  27. public enum AuthZoneDnssecStatus : byte
  28. {
  29. Unsigned = 0,
  30. SignedWithNSEC = 1,
  31. SignedWithNSEC3 = 2,
  32. }
  33. //DNSSEC Operational Practices, Version 2
  34. //https://datatracker.ietf.org/doc/html/rfc6781
  35. //DNSSEC Key Rollover Timing Considerations
  36. //https://datatracker.ietf.org/doc/html/rfc7583
  37. class PrimaryZone : ApexZone
  38. {
  39. #region variables
  40. readonly bool _internal;
  41. Dictionary<ushort, DnssecPrivateKey> _dnssecPrivateKeys;
  42. const uint DNSSEC_SIGNATURE_INCEPTION_OFFSET = 60 * 60;
  43. Timer _dnssecTimer;
  44. const int DNSSEC_TIMER_INITIAL_INTERVAL = 30000;
  45. const int DNSSEC_TIMER_PERIODIC_INTERVAL = 900000;
  46. DateTime _lastSignatureRefreshCheckedOn;
  47. readonly object _dnssecUpdateLock = new object();
  48. #endregion
  49. #region constructor
  50. public PrimaryZone(DnsServer dnsServer, AuthZoneInfo zoneInfo)
  51. : base(dnsServer, zoneInfo)
  52. {
  53. IReadOnlyCollection<DnssecPrivateKey> dnssecPrivateKeys = zoneInfo.DnssecPrivateKeys;
  54. if (dnssecPrivateKeys is not null)
  55. {
  56. _dnssecPrivateKeys = new Dictionary<ushort, DnssecPrivateKey>(dnssecPrivateKeys.Count);
  57. foreach (DnssecPrivateKey dnssecPrivateKey in dnssecPrivateKeys)
  58. _dnssecPrivateKeys.Add(dnssecPrivateKey.KeyTag, dnssecPrivateKey);
  59. }
  60. InitNotify();
  61. InitRecordExpiry();
  62. }
  63. public PrimaryZone(DnsServer dnsServer, string name, bool @internal, bool useSoaSerialDateScheme)
  64. : base(dnsServer, name)
  65. {
  66. _internal = @internal;
  67. if (!_internal)
  68. {
  69. InitNotify();
  70. InitRecordExpiry();
  71. ZoneTransfer = AuthZoneTransfer.AllowOnlyZoneNameServers;
  72. Notify = AuthZoneNotify.ZoneNameServers;
  73. }
  74. string rp;
  75. if (_dnsServer.ResponsiblePersonInternal is null)
  76. rp = _name.Length == 0 ? _dnsServer.ResponsiblePerson.Address : "hostadmin@" + _name;
  77. else
  78. rp = _dnsServer.ResponsiblePersonInternal.Address;
  79. uint serial = GetNewSerial(0, 0, useSoaSerialDateScheme);
  80. DnsSOARecordData soa = new DnsSOARecordData(_dnsServer.ServerDomain, rp, serial, 900, 300, 604800, 900);
  81. DnsResourceRecord soaRecord = new DnsResourceRecord(_name, DnsResourceRecordType.SOA, DnsClass.IN, soa.Minimum, soa);
  82. soaRecord.GetAuthSOARecordInfo().UseSoaSerialDateScheme = useSoaSerialDateScheme;
  83. soaRecord.GetAuthSOARecordInfo().LastModified = DateTime.UtcNow;
  84. DnsResourceRecord nsRecord = new DnsResourceRecord(_name, DnsResourceRecordType.NS, DnsClass.IN, 3600, new DnsNSRecordData(soa.PrimaryNameServer));
  85. nsRecord.GetAuthNSRecordInfo().LastModified = DateTime.UtcNow;
  86. _entries[DnsResourceRecordType.SOA] = [soaRecord];
  87. _entries[DnsResourceRecordType.NS] = [nsRecord];
  88. }
  89. internal PrimaryZone(DnsServer dnsServer, string name, DnsSOARecordData soa, DnsNSRecordData ns)
  90. : base(dnsServer, name)
  91. {
  92. _internal = true;
  93. _entries[DnsResourceRecordType.SOA] = [new DnsResourceRecord(_name, DnsResourceRecordType.SOA, DnsClass.IN, soa.Minimum, soa)];
  94. _entries[DnsResourceRecordType.NS] = [new DnsResourceRecord(_name, DnsResourceRecordType.NS, DnsClass.IN, 3600, ns)];
  95. }
  96. #endregion
  97. #region IDisposable
  98. bool _disposed;
  99. protected override void Dispose(bool disposing)
  100. {
  101. try
  102. {
  103. if (_disposed)
  104. return;
  105. if (disposing)
  106. {
  107. Timer dnssecTimer = _dnssecTimer;
  108. if (dnssecTimer is not null)
  109. {
  110. lock (dnssecTimer)
  111. {
  112. dnssecTimer.Dispose();
  113. _dnssecTimer = null;
  114. }
  115. }
  116. }
  117. _disposed = true;
  118. }
  119. finally
  120. {
  121. base.Dispose(disposing);
  122. }
  123. }
  124. #endregion
  125. #region DNSSEC
  126. internal override void UpdateDnssecStatus()
  127. {
  128. base.UpdateDnssecStatus();
  129. if (_dnssecStatus != AuthZoneDnssecStatus.Unsigned)
  130. {
  131. if (_dnssecPrivateKeys is not null)
  132. _dnssecTimer = new Timer(DnssecTimerCallback, null, DNSSEC_TIMER_INITIAL_INTERVAL, Timeout.Infinite);
  133. }
  134. }
  135. private async void DnssecTimerCallback(object state)
  136. {
  137. try
  138. {
  139. List<DnssecPrivateKey> kskToReady = null;
  140. List<DnssecPrivateKey> kskToActivate = null;
  141. List<DnssecPrivateKey> kskToRetire = null;
  142. List<DnssecPrivateKey> kskToRevoke = null;
  143. List<DnssecPrivateKey> zskToActivate = null;
  144. List<DnssecPrivateKey> zskToRetire = null;
  145. List<DnssecPrivateKey> zskToRollover = null;
  146. List<DnssecPrivateKey> keysToUnpublish = null;
  147. bool saveZone = false;
  148. lock (_dnssecPrivateKeys)
  149. {
  150. foreach (KeyValuePair<ushort, DnssecPrivateKey> privateKeyEntry in _dnssecPrivateKeys)
  151. {
  152. DnssecPrivateKey privateKey = privateKeyEntry.Value;
  153. if (privateKey.KeyType == DnssecPrivateKeyType.KeySigningKey)
  154. {
  155. //KSK
  156. switch (privateKey.State)
  157. {
  158. case DnssecPrivateKeyState.Published:
  159. if (DateTime.UtcNow > GetKskDnsKeyStateReadyOn(privateKey))
  160. {
  161. //long enough time for old RRsets to expire from caches
  162. if (kskToReady is null)
  163. kskToReady = new List<DnssecPrivateKey>();
  164. kskToReady.Add(privateKey);
  165. }
  166. break;
  167. case DnssecPrivateKeyState.Ready:
  168. if (privateKey.IsRetiring)
  169. {
  170. if (kskToRetire is null)
  171. kskToRetire = new List<DnssecPrivateKey>();
  172. kskToRetire.Add(privateKey);
  173. }
  174. else
  175. {
  176. if (kskToActivate is null)
  177. kskToActivate = new List<DnssecPrivateKey>();
  178. kskToActivate.Add(privateKey);
  179. }
  180. break;
  181. case DnssecPrivateKeyState.Active:
  182. if (privateKey.IsRetiring)
  183. {
  184. if (kskToRetire is null)
  185. kskToRetire = new List<DnssecPrivateKey>();
  186. kskToRetire.Add(privateKey);
  187. }
  188. break;
  189. case DnssecPrivateKeyState.Retired:
  190. //KSK needs to be revoked for RFC5011 consideration
  191. if (kskToRevoke is null)
  192. kskToRevoke = new List<DnssecPrivateKey>();
  193. kskToRevoke.Add(privateKey);
  194. break;
  195. case DnssecPrivateKeyState.Revoked:
  196. //rfc7583#section-3.3.4
  197. //modifiedQueryInterval = MAX(1hr, MIN(15 days, TTLkey / 2))
  198. uint modifiedQueryInterval = Math.Max(3600u, Math.Min(15 * 24 * 60 * 60, GetDnsKeyTtl() / 2));
  199. if (DateTime.UtcNow > privateKey.StateChangedOn.AddSeconds(modifiedQueryInterval))
  200. {
  201. //key has been revoked for sufficient time
  202. if (keysToUnpublish is null)
  203. keysToUnpublish = new List<DnssecPrivateKey>();
  204. keysToUnpublish.Add(privateKey);
  205. }
  206. break;
  207. }
  208. }
  209. else
  210. {
  211. //ZSK
  212. switch (privateKey.State)
  213. {
  214. case DnssecPrivateKeyState.Published:
  215. if (DateTime.UtcNow > privateKey.StateChangedOn.AddSeconds(GetDnsKeyTtl() + GetPropagationDelay()))
  216. {
  217. //long enough time old RRset to expire from caches
  218. privateKey.SetState(DnssecPrivateKeyState.Ready);
  219. if (zskToActivate is null)
  220. zskToActivate = new List<DnssecPrivateKey>();
  221. zskToActivate.Add(privateKey);
  222. }
  223. break;
  224. case DnssecPrivateKeyState.Ready:
  225. if (zskToActivate is null)
  226. zskToActivate = new List<DnssecPrivateKey>();
  227. zskToActivate.Add(privateKey);
  228. break;
  229. case DnssecPrivateKeyState.Active:
  230. if (privateKey.IsRetiring)
  231. {
  232. if (zskToRetire is null)
  233. zskToRetire = new List<DnssecPrivateKey>();
  234. zskToRetire.Add(privateKey);
  235. }
  236. else
  237. {
  238. if (privateKey.IsRolloverNeeded())
  239. {
  240. if (zskToRollover is null)
  241. zskToRollover = new List<DnssecPrivateKey>();
  242. zskToRollover.Add(privateKey);
  243. }
  244. }
  245. break;
  246. case DnssecPrivateKeyState.Retired:
  247. if (DateTime.UtcNow > privateKey.StateChangedOn.AddSeconds(GetMaxRRSigTtl() + GetPropagationDelay()))
  248. {
  249. //key has been retired for sufficient time
  250. if (keysToUnpublish is null)
  251. keysToUnpublish = new List<DnssecPrivateKey>();
  252. keysToUnpublish.Add(privateKey);
  253. }
  254. break;
  255. }
  256. }
  257. }
  258. }
  259. #region KSK actions
  260. if (kskToReady is not null)
  261. {
  262. string dnsKeyTags = null;
  263. foreach (DnssecPrivateKey kskPrivateKey in kskToReady)
  264. {
  265. kskPrivateKey.SetState(DnssecPrivateKeyState.Ready);
  266. if (kskToActivate is null)
  267. kskToActivate = new List<DnssecPrivateKey>();
  268. kskToActivate.Add(kskPrivateKey);
  269. if (dnsKeyTags is null)
  270. dnsKeyTags = kskPrivateKey.KeyTag.ToString();
  271. else
  272. dnsKeyTags += ", " + kskPrivateKey.KeyTag.ToString();
  273. }
  274. saveZone = true;
  275. LogManager log = _dnsServer.LogManager;
  276. if (log is not null)
  277. log.Write("The KSK DNSKEYs (" + dnsKeyTags + ") from the primary zone are ready for changing the DS records at the parent zone: " + ToString());
  278. }
  279. if (kskToActivate is not null)
  280. {
  281. try
  282. {
  283. IReadOnlyList<DnssecPrivateKey> kskPrivateKeys = await GetDSPublishedPrivateKeysAsync(kskToActivate);
  284. if (kskPrivateKeys.Count > 0)
  285. {
  286. string dnsKeyTags = null;
  287. foreach (DnssecPrivateKey kskPrivateKey in kskPrivateKeys)
  288. {
  289. kskPrivateKey.SetState(DnssecPrivateKeyState.Active);
  290. if (dnsKeyTags is null)
  291. dnsKeyTags = kskPrivateKey.KeyTag.ToString();
  292. else
  293. dnsKeyTags += ", " + kskPrivateKey.KeyTag.ToString();
  294. }
  295. saveZone = true;
  296. LogManager log = _dnsServer.LogManager;
  297. if (log is not null)
  298. log.Write("The KSK DNSKEYs (" + dnsKeyTags + ") from the primary zone were activated successfully: " + ToString());
  299. }
  300. }
  301. catch (Exception ex)
  302. {
  303. LogManager log = _dnsServer.LogManager;
  304. if (log is not null)
  305. log.Write(ex);
  306. }
  307. }
  308. if (kskToRetire is not null)
  309. saveZone = RetireKskDnsKeys(kskToRetire, false);
  310. if (kskToRevoke is not null)
  311. {
  312. uint dsTtl = await GetDSTtlAsync();
  313. uint parentSidePropagationDelay = await GetParentSidePropagationDelayAsync();
  314. List<DnssecPrivateKey> revokeKskPrivateKeys = null;
  315. foreach (DnssecPrivateKey privateKey in kskToRevoke)
  316. {
  317. if (DateTime.UtcNow > privateKey.StateChangedOn.AddSeconds(dsTtl + parentSidePropagationDelay))
  318. {
  319. if (revokeKskPrivateKeys is null)
  320. revokeKskPrivateKeys = new List<DnssecPrivateKey>();
  321. revokeKskPrivateKeys.Add(privateKey);
  322. }
  323. }
  324. if (revokeKskPrivateKeys is not null)
  325. {
  326. RevokeKskDnsKeys(revokeKskPrivateKeys);
  327. saveZone = true;
  328. }
  329. }
  330. #endregion
  331. #region ZSK actions
  332. if (zskToActivate is not null)
  333. {
  334. ActivateZskDnsKeys(zskToActivate);
  335. saveZone = true;
  336. }
  337. if (zskToRetire is not null)
  338. saveZone = RetireZskDnsKeys(zskToRetire, false);
  339. if (zskToRollover is not null)
  340. {
  341. foreach (DnssecPrivateKey zskPrivateKey in zskToRollover)
  342. RolloverDnsKey(zskPrivateKey.KeyTag);
  343. saveZone = true;
  344. }
  345. #endregion
  346. if (keysToUnpublish is not null)
  347. {
  348. UnpublishDnsKeys(keysToUnpublish);
  349. saveZone = true;
  350. }
  351. //re-signing task
  352. uint reSignPeriod = GetSignatureValidityPeriod() / 10; //the period when signature refresh check is done
  353. if (DateTime.UtcNow > _lastSignatureRefreshCheckedOn.AddSeconds(reSignPeriod))
  354. {
  355. if (TryRefreshAllSignatures())
  356. saveZone = true;
  357. _lastSignatureRefreshCheckedOn = DateTime.UtcNow;
  358. }
  359. if (saveZone)
  360. _dnsServer.AuthZoneManager.SaveZoneFile(_name);
  361. }
  362. catch (Exception ex)
  363. {
  364. LogManager log = _dnsServer.LogManager;
  365. if (log is not null)
  366. log.Write(ex);
  367. }
  368. finally
  369. {
  370. Timer dnssecTimer = _dnssecTimer;
  371. if (dnssecTimer is not null)
  372. {
  373. lock (dnssecTimer)
  374. {
  375. dnssecTimer.Change(DNSSEC_TIMER_PERIODIC_INTERVAL, Timeout.Infinite);
  376. }
  377. }
  378. }
  379. }
  380. public void SignZoneWithRsaNSec(string hashAlgorithm, int kskKeySize, int zskKeySize, uint dnsKeyTtl, ushort zskRolloverDays)
  381. {
  382. SignZoneWithRsa(hashAlgorithm, kskKeySize, zskKeySize, false, 0, 0, dnsKeyTtl, zskRolloverDays);
  383. }
  384. public void SignZoneWithRsaNSec3(string hashAlgorithm, int kskKeySize, int zskKeySize, ushort iterations, byte saltLength, uint dnsKeyTtl, ushort zskRolloverDays)
  385. {
  386. SignZoneWithRsa(hashAlgorithm, kskKeySize, zskKeySize, true, iterations, saltLength, dnsKeyTtl, zskRolloverDays);
  387. }
  388. private void SignZoneWithRsa(string hashAlgorithm, int kskKeySize, int zskKeySize, bool useNSec3, ushort iterations, byte saltLength, uint dnsKeyTtl, ushort zskRolloverDays)
  389. {
  390. if (_dnssecStatus != AuthZoneDnssecStatus.Unsigned)
  391. throw new DnsServerException("Cannot sign zone: the zone is already signed.");
  392. if (iterations > 50)
  393. throw new ArgumentOutOfRangeException(nameof(iterations), "NSEC3 iterations valid range is 0-50");
  394. if (saltLength > 32)
  395. throw new ArgumentOutOfRangeException(nameof(saltLength), "NSEC3 salt length valid range is 0-32");
  396. //generate private keys
  397. DnssecAlgorithm algorithm;
  398. switch (hashAlgorithm.ToUpper())
  399. {
  400. case "MD5":
  401. algorithm = DnssecAlgorithm.RSAMD5;
  402. break;
  403. case "SHA1":
  404. algorithm = DnssecAlgorithm.RSASHA1;
  405. break;
  406. case "SHA256":
  407. algorithm = DnssecAlgorithm.RSASHA256;
  408. break;
  409. case "SHA512":
  410. algorithm = DnssecAlgorithm.RSASHA512;
  411. break;
  412. default:
  413. throw new NotSupportedException("Hash algorithm is not supported: " + hashAlgorithm);
  414. }
  415. DnssecPrivateKey kskPrivateKey = DnssecPrivateKey.Create(algorithm, DnssecPrivateKeyType.KeySigningKey, kskKeySize);
  416. DnssecPrivateKey zskPrivateKey = DnssecPrivateKey.Create(algorithm, DnssecPrivateKeyType.ZoneSigningKey, zskKeySize);
  417. zskPrivateKey.RolloverDays = zskRolloverDays;
  418. _dnssecPrivateKeys = new Dictionary<ushort, DnssecPrivateKey>(4);
  419. _dnssecPrivateKeys.Add(kskPrivateKey.KeyTag, kskPrivateKey);
  420. _dnssecPrivateKeys.Add(zskPrivateKey.KeyTag, zskPrivateKey);
  421. //sign zone
  422. SignZone(useNSec3, iterations, saltLength, dnsKeyTtl);
  423. }
  424. public void SignZoneWithEcdsaNSec(string curve, uint dnsKeyTtl, ushort zskRolloverDays)
  425. {
  426. SignZoneWithEcdsa(curve, false, 0, 0, dnsKeyTtl, zskRolloverDays);
  427. }
  428. public void SignZoneWithEcdsaNSec3(string curve, ushort iterations, byte saltLength, uint dnsKeyTtl, ushort zskRolloverDays)
  429. {
  430. SignZoneWithEcdsa(curve, true, iterations, saltLength, dnsKeyTtl, zskRolloverDays);
  431. }
  432. private void SignZoneWithEcdsa(string curve, bool useNSec3, ushort iterations, byte saltLength, uint dnsKeyTtl, ushort zskRolloverDays)
  433. {
  434. if (_dnssecStatus != AuthZoneDnssecStatus.Unsigned)
  435. throw new DnsServerException("Cannot sign zone: the zone is already signed.");
  436. if (iterations > 50)
  437. throw new ArgumentOutOfRangeException(nameof(iterations), "NSEC3 iterations valid range is 0-50");
  438. if (saltLength > 32)
  439. throw new ArgumentOutOfRangeException(nameof(saltLength), "NSEC3 salt length valid range is 0-32");
  440. //generate private keys
  441. DnssecAlgorithm algorithm;
  442. switch (curve.ToUpper())
  443. {
  444. case "P256":
  445. algorithm = DnssecAlgorithm.ECDSAP256SHA256;
  446. break;
  447. case "P384":
  448. algorithm = DnssecAlgorithm.ECDSAP384SHA384;
  449. break;
  450. default:
  451. throw new NotSupportedException("ECDSA curve is not supported: " + curve);
  452. }
  453. DnssecPrivateKey kskPrivateKey = DnssecPrivateKey.Create(algorithm, DnssecPrivateKeyType.KeySigningKey);
  454. DnssecPrivateKey zskPrivateKey = DnssecPrivateKey.Create(algorithm, DnssecPrivateKeyType.ZoneSigningKey);
  455. zskPrivateKey.RolloverDays = zskRolloverDays;
  456. _dnssecPrivateKeys = new Dictionary<ushort, DnssecPrivateKey>(4);
  457. _dnssecPrivateKeys.Add(kskPrivateKey.KeyTag, kskPrivateKey);
  458. _dnssecPrivateKeys.Add(zskPrivateKey.KeyTag, zskPrivateKey);
  459. //sign zone
  460. SignZone(useNSec3, iterations, saltLength, dnsKeyTtl);
  461. }
  462. private void SignZone(bool useNSec3, ushort iterations, byte saltLength, uint dnsKeyTtl)
  463. {
  464. List<DnsResourceRecord> addedRecords = new List<DnsResourceRecord>();
  465. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  466. try
  467. {
  468. //update private key state
  469. foreach (KeyValuePair<ushort, DnssecPrivateKey> privateKeyEntry in _dnssecPrivateKeys)
  470. {
  471. DnssecPrivateKey privateKey = privateKeyEntry.Value;
  472. switch (privateKey.KeyType)
  473. {
  474. case DnssecPrivateKeyType.KeySigningKey:
  475. privateKey.SetState(DnssecPrivateKeyState.Published);
  476. break;
  477. case DnssecPrivateKeyType.ZoneSigningKey:
  478. privateKey.SetState(DnssecPrivateKeyState.Ready);
  479. break;
  480. }
  481. }
  482. //add DNSKEYs
  483. List<DnsResourceRecord> dnsKeyRecords = new List<DnsResourceRecord>(_dnssecPrivateKeys.Count);
  484. foreach (KeyValuePair<ushort, DnssecPrivateKey> privateKey in _dnssecPrivateKeys)
  485. dnsKeyRecords.Add(new DnsResourceRecord(_name, DnsResourceRecordType.DNSKEY, DnsClass.IN, dnsKeyTtl, privateKey.Value.DnsKey));
  486. if (!TrySetRecords(DnsResourceRecordType.DNSKEY, dnsKeyRecords, out IReadOnlyList<DnsResourceRecord> deletedDnsKeyRecords))
  487. throw new InvalidOperationException("Failed to add DNSKEY.");
  488. addedRecords.AddRange(dnsKeyRecords);
  489. deletedRecords.AddRange(deletedDnsKeyRecords);
  490. //sign all RRSets
  491. IReadOnlyList<AuthZone> zones = _dnsServer.AuthZoneManager.GetApexZoneWithSubDomainZones(_name);
  492. foreach (AuthZone zone in zones)
  493. {
  494. IReadOnlyList<DnsResourceRecord> newRRSigRecords = zone.SignAllRRSets();
  495. if (newRRSigRecords.Count > 0)
  496. {
  497. zone.AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  498. addedRecords.AddRange(newRRSigRecords);
  499. deletedRecords.AddRange(deletedRRSigRecords);
  500. }
  501. }
  502. if (useNSec3)
  503. {
  504. EnableNSec3(zones, iterations, saltLength);
  505. _dnssecStatus = AuthZoneDnssecStatus.SignedWithNSEC3;
  506. }
  507. else
  508. {
  509. EnableNSec(zones);
  510. _dnssecStatus = AuthZoneDnssecStatus.SignedWithNSEC;
  511. }
  512. //update private key state
  513. foreach (KeyValuePair<ushort, DnssecPrivateKey> privateKeyEntry in _dnssecPrivateKeys)
  514. {
  515. DnssecPrivateKey privateKey = privateKeyEntry.Value;
  516. switch (privateKey.KeyType)
  517. {
  518. case DnssecPrivateKeyType.ZoneSigningKey:
  519. privateKey.SetState(DnssecPrivateKeyState.Active);
  520. break;
  521. }
  522. }
  523. _dnssecTimer = new Timer(DnssecTimerCallback, null, DNSSEC_TIMER_INITIAL_INTERVAL, Timeout.Infinite);
  524. CommitAndIncrementSerial(deletedRecords, addedRecords);
  525. TriggerNotify();
  526. }
  527. catch
  528. {
  529. _dnssecStatus = AuthZoneDnssecStatus.Unsigned;
  530. _dnssecPrivateKeys = null;
  531. Dictionary<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>> addedRecordGroups = DnsResourceRecord.GroupRecords(addedRecords);
  532. foreach (KeyValuePair<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>> addedRecordGroup in addedRecordGroups)
  533. {
  534. AuthZone zone = _dnsServer.AuthZoneManager.GetAuthZone(_name, addedRecordGroup.Key);
  535. foreach (KeyValuePair<DnsResourceRecordType, List<DnsResourceRecord>> addedRecordEntry in addedRecordGroup.Value)
  536. zone.TryDeleteRecords(addedRecordEntry.Key, addedRecordEntry.Value, out _);
  537. }
  538. Dictionary<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>> deletedRecordGroups = DnsResourceRecord.GroupRecords(deletedRecords);
  539. foreach (KeyValuePair<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>> deletedRecordGroup in deletedRecordGroups)
  540. {
  541. AuthZone zone = _dnsServer.AuthZoneManager.GetAuthZone(_name, deletedRecordGroup.Key);
  542. foreach (KeyValuePair<DnsResourceRecordType, List<DnsResourceRecord>> deletedRecordEntry in deletedRecordGroup.Value)
  543. {
  544. foreach (DnsResourceRecord deletedRecord in deletedRecordEntry.Value)
  545. AddRecord(deletedRecord, out _, out _);
  546. }
  547. }
  548. throw;
  549. }
  550. }
  551. public void UnsignZone()
  552. {
  553. if (_dnssecStatus == AuthZoneDnssecStatus.Unsigned)
  554. throw new DnsServerException("Cannot unsign zone: the is zone not signed.");
  555. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  556. IReadOnlyList<AuthZone> zones = _dnsServer.AuthZoneManager.GetApexZoneWithSubDomainZones(_name);
  557. foreach (AuthZone zone in zones)
  558. {
  559. deletedRecords.AddRange(zone.RemoveAllDnssecRecords());
  560. if (zone is SubDomainZone subDomainZone)
  561. {
  562. if (zone.IsEmpty)
  563. _dnsServer.AuthZoneManager.RemoveSubDomainZone(zone.Name); //remove empty sub zone
  564. else
  565. subDomainZone.AutoUpdateState();
  566. }
  567. }
  568. Timer dnssecTimer = _dnssecTimer;
  569. if (dnssecTimer is not null)
  570. {
  571. lock (dnssecTimer)
  572. {
  573. dnssecTimer.Dispose();
  574. _dnssecTimer = null;
  575. }
  576. }
  577. _dnssecPrivateKeys = null;
  578. _dnssecStatus = AuthZoneDnssecStatus.Unsigned;
  579. CommitAndIncrementSerial(deletedRecords);
  580. TriggerNotify();
  581. }
  582. public void ConvertToNSec()
  583. {
  584. if (_dnssecStatus != AuthZoneDnssecStatus.SignedWithNSEC3)
  585. throw new DnsServerException("Cannot convert to NSEC: the zone must be signed with NSEC3 for conversion.");
  586. lock (_dnssecUpdateLock)
  587. {
  588. IReadOnlyList<AuthZone> zones = _dnsServer.AuthZoneManager.GetApexZoneWithSubDomainZones(_name);
  589. DisableNSec3(zones);
  590. //since zones were removed when disabling NSEC3; get updated non empty zones list
  591. List<AuthZone> nonEmptyZones = new List<AuthZone>(zones.Count);
  592. foreach (AuthZone zone in zones)
  593. {
  594. if (!zone.IsEmpty)
  595. nonEmptyZones.Add(zone);
  596. }
  597. EnableNSec(nonEmptyZones);
  598. _dnssecStatus = AuthZoneDnssecStatus.SignedWithNSEC;
  599. }
  600. TriggerNotify();
  601. }
  602. public void ConvertToNSec3(ushort iterations, byte saltLength)
  603. {
  604. if (_dnssecStatus != AuthZoneDnssecStatus.SignedWithNSEC)
  605. throw new DnsServerException("Cannot convert to NSEC3: the zone must be signed with NSEC for conversion.");
  606. if (iterations > 50)
  607. throw new ArgumentOutOfRangeException(nameof(iterations), "NSEC3 iterations valid range is 0-50");
  608. if (saltLength > 32)
  609. throw new ArgumentOutOfRangeException(nameof(saltLength), "NSEC3 salt length valid range is 0-32");
  610. lock (_dnssecUpdateLock)
  611. {
  612. IReadOnlyList<AuthZone> zones = _dnsServer.AuthZoneManager.GetApexZoneWithSubDomainZones(_name);
  613. DisableNSec(zones);
  614. EnableNSec3(zones, iterations, saltLength);
  615. _dnssecStatus = AuthZoneDnssecStatus.SignedWithNSEC3;
  616. }
  617. TriggerNotify();
  618. }
  619. public void UpdateNSec3Parameters(ushort iterations, byte saltLength)
  620. {
  621. if (_dnssecStatus != AuthZoneDnssecStatus.SignedWithNSEC3)
  622. throw new DnsServerException("Cannot update NSEC3 parameters: the zone must be signed with NSEC3 first.");
  623. if (iterations > 50)
  624. throw new ArgumentOutOfRangeException(nameof(iterations), "NSEC3 iterations valid range is 0-50");
  625. if (saltLength > 32)
  626. throw new ArgumentOutOfRangeException(nameof(saltLength), "NSEC3 salt length valid range is 0-32");
  627. lock (_dnssecUpdateLock)
  628. {
  629. IReadOnlyList<AuthZone> zones = _dnsServer.AuthZoneManager.GetApexZoneWithSubDomainZones(_name);
  630. DisableNSec3(zones);
  631. //since zones were removed when disabling NSEC3; get updated non empty zones list
  632. List<AuthZone> nonEmptyZones = new List<AuthZone>(zones.Count);
  633. foreach (AuthZone zone in zones)
  634. {
  635. if (!zone.IsEmpty)
  636. nonEmptyZones.Add(zone);
  637. }
  638. EnableNSec3(nonEmptyZones, iterations, saltLength);
  639. }
  640. TriggerNotify();
  641. }
  642. private void RefreshNSec()
  643. {
  644. lock (_dnssecUpdateLock)
  645. {
  646. IReadOnlyList<AuthZone> zones = _dnsServer.AuthZoneManager.GetApexZoneWithSubDomainZones(_name);
  647. EnableNSec(zones);
  648. }
  649. }
  650. private void RefreshNSec3()
  651. {
  652. lock (_dnssecUpdateLock)
  653. {
  654. IReadOnlyList<AuthZone> zones = _dnsServer.AuthZoneManager.GetApexZoneWithSubDomainZones(_name);
  655. //get non NSEC3 zones
  656. List<AuthZone> nonNSec3Zones = new List<AuthZone>(zones.Count);
  657. foreach (AuthZone zone in zones)
  658. {
  659. if (zone.HasOnlyNSec3Records())
  660. continue;
  661. nonNSec3Zones.Add(zone);
  662. }
  663. IReadOnlyList<DnsResourceRecord> nsec3ParamRecords = GetRecords(DnsResourceRecordType.NSEC3PARAM);
  664. DnsNSEC3PARAMRecordData nsec3Param = nsec3ParamRecords[0].RDATA as DnsNSEC3PARAMRecordData;
  665. EnableNSec3(nonNSec3Zones, nsec3Param.Iterations, nsec3Param.Salt);
  666. }
  667. }
  668. private void EnableNSec(IReadOnlyList<AuthZone> zones)
  669. {
  670. List<DnsResourceRecord> addedRecords = new List<DnsResourceRecord>();
  671. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  672. uint ttl = GetZoneSoaMinimum();
  673. for (int i = 0; i < zones.Count; i++)
  674. {
  675. AuthZone zone = zones[i];
  676. AuthZone nextZone;
  677. if (i < zones.Count - 1)
  678. nextZone = zones[i + 1];
  679. else
  680. nextZone = zones[0];
  681. IReadOnlyList<DnsResourceRecord> newNSecRecords = zone.GetUpdatedNSecRRSet(nextZone.Name, ttl);
  682. if (newNSecRecords.Count > 0)
  683. {
  684. if (!zone.TrySetRecords(DnsResourceRecordType.NSEC, newNSecRecords, out IReadOnlyList<DnsResourceRecord> deletedNSecRecords))
  685. throw new DnsServerException("Failed to set DNSSEC records. Please try again.");
  686. addedRecords.AddRange(newNSecRecords);
  687. deletedRecords.AddRange(deletedNSecRecords);
  688. IReadOnlyList<DnsResourceRecord> newRRSigRecords = SignRRSet(newNSecRecords);
  689. if (newRRSigRecords.Count > 0)
  690. {
  691. zone.AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  692. addedRecords.AddRange(newRRSigRecords);
  693. deletedRecords.AddRange(deletedRRSigRecords);
  694. }
  695. }
  696. }
  697. CommitAndIncrementSerial(deletedRecords, addedRecords);
  698. }
  699. private void DisableNSec(IReadOnlyList<AuthZone> zones)
  700. {
  701. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  702. foreach (AuthZone zone in zones)
  703. deletedRecords.AddRange(zone.RemoveNSecRecordsWithRRSig());
  704. CommitAndIncrementSerial(deletedRecords);
  705. }
  706. private void EnableNSec3(IReadOnlyList<AuthZone> zones, ushort iterations, byte saltLength)
  707. {
  708. byte[] salt;
  709. if (saltLength > 0)
  710. {
  711. salt = new byte[saltLength];
  712. RandomNumberGenerator.Fill(salt);
  713. }
  714. else
  715. {
  716. salt = Array.Empty<byte>();
  717. }
  718. EnableNSec3(zones, iterations, salt);
  719. }
  720. private void EnableNSec3(IReadOnlyList<AuthZone> zones, ushort iterations, byte[] salt)
  721. {
  722. List<DnsResourceRecord> addedRecords = new List<DnsResourceRecord>();
  723. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  724. List<DnsResourceRecord> partialNSec3Records = new List<DnsResourceRecord>(zones.Count);
  725. int apexLabelCount = DnsRRSIGRecordData.GetLabelCount(_name);
  726. uint ttl = GetZoneSoaMinimum();
  727. //list all partial NSEC3 records
  728. foreach (AuthZone zone in zones)
  729. {
  730. partialNSec3Records.Add(zone.GetPartialNSec3Record(_name, ttl, iterations, salt));
  731. int zoneLabelCount = DnsRRSIGRecordData.GetLabelCount(zone.Name);
  732. if ((zoneLabelCount - apexLabelCount) > 1)
  733. {
  734. //empty non-terminal (ENT) may exists
  735. string currentOwnerName = zone.Name;
  736. while (true)
  737. {
  738. currentOwnerName = AuthZoneManager.GetParentZone(currentOwnerName);
  739. if (currentOwnerName.Equals(_name, StringComparison.OrdinalIgnoreCase))
  740. break;
  741. //add partial NSEC3 record for ENT
  742. AuthZone entZone = new PrimarySubDomainZone(null, currentOwnerName); //dummy empty non-terminal (ENT) sub domain object
  743. partialNSec3Records.Add(entZone.GetPartialNSec3Record(_name, ttl, iterations, salt));
  744. }
  745. }
  746. }
  747. //sort partial NSEC3 records
  748. partialNSec3Records.Sort(delegate (DnsResourceRecord rr1, DnsResourceRecord rr2)
  749. {
  750. return string.CompareOrdinal(rr1.Name, rr2.Name);
  751. });
  752. //deduplicate partial NSEC3 records and insert next hashed owner name to complete them
  753. List<DnsResourceRecord> uniqueNSec3Records = new List<DnsResourceRecord>(partialNSec3Records.Count);
  754. for (int i = 0; i < partialNSec3Records.Count; i++)
  755. {
  756. DnsResourceRecord partialNSec3Record = partialNSec3Records[i];
  757. DnsResourceRecord nextPartialNSec3Record;
  758. if (i < partialNSec3Records.Count - 1)
  759. {
  760. nextPartialNSec3Record = partialNSec3Records[i + 1];
  761. //check for duplicates
  762. if (partialNSec3Record.Name.Equals(nextPartialNSec3Record.Name, StringComparison.OrdinalIgnoreCase))
  763. {
  764. //found duplicate; merge current nsec3 into next nsec3
  765. DnsNSEC3RecordData nsec3 = partialNSec3Record.RDATA as DnsNSEC3RecordData;
  766. DnsNSEC3RecordData nextNSec3 = nextPartialNSec3Record.RDATA as DnsNSEC3RecordData;
  767. List<DnsResourceRecordType> uniqueTypes = new List<DnsResourceRecordType>(nsec3.Types.Count + nextNSec3.Types.Count);
  768. uniqueTypes.AddRange(nsec3.Types);
  769. foreach (DnsResourceRecordType type in nextNSec3.Types)
  770. {
  771. if (!uniqueTypes.Contains(type))
  772. uniqueTypes.Add(type);
  773. }
  774. uniqueTypes.Sort();
  775. //update the next nsec3 record and continue
  776. DnsNSEC3RecordData mergedPartialNSec3 = new DnsNSEC3RecordData(DnssecNSEC3HashAlgorithm.SHA1, DnssecNSEC3Flags.None, iterations, salt, Array.Empty<byte>(), uniqueTypes);
  777. partialNSec3Records[i + 1] = new DnsResourceRecord(partialNSec3Record.Name, DnsResourceRecordType.NSEC3, DnsClass.IN, ttl, mergedPartialNSec3);
  778. continue;
  779. }
  780. }
  781. else
  782. {
  783. //for last NSEC3, next NSEC3 is the first in list
  784. nextPartialNSec3Record = partialNSec3Records[0];
  785. }
  786. //add NSEC3 record with next hashed owner name
  787. {
  788. DnsNSEC3RecordData partialNSec3 = partialNSec3Record.RDATA as DnsNSEC3RecordData;
  789. byte[] nextHashedOwnerName = DnsNSEC3RecordData.GetHashedOwnerNameFrom(nextPartialNSec3Record.Name);
  790. DnsNSEC3RecordData updatedNSec3 = new DnsNSEC3RecordData(DnssecNSEC3HashAlgorithm.SHA1, DnssecNSEC3Flags.None, iterations, salt, nextHashedOwnerName, partialNSec3.Types);
  791. uniqueNSec3Records.Add(new DnsResourceRecord(partialNSec3Record.Name, DnsResourceRecordType.NSEC3, DnsClass.IN, ttl, updatedNSec3));
  792. }
  793. }
  794. //insert and sign NSEC3 records
  795. foreach (DnsResourceRecord uniqueNSec3Record in uniqueNSec3Records)
  796. {
  797. AuthZone zone = _dnsServer.AuthZoneManager.GetOrAddSubDomainZone(_name, uniqueNSec3Record.Name);
  798. DnsResourceRecord[] newNSec3Records = new DnsResourceRecord[] { uniqueNSec3Record };
  799. if (!zone.TrySetRecords(DnsResourceRecordType.NSEC3, newNSec3Records, out IReadOnlyList<DnsResourceRecord> deletedNSec3Records))
  800. throw new InvalidOperationException();
  801. addedRecords.AddRange(newNSec3Records);
  802. deletedRecords.AddRange(deletedNSec3Records);
  803. IReadOnlyList<DnsResourceRecord> newRRSigRecords = SignRRSet(newNSec3Records);
  804. if (newRRSigRecords.Count > 0)
  805. {
  806. zone.AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  807. addedRecords.AddRange(newRRSigRecords);
  808. deletedRecords.AddRange(deletedRRSigRecords);
  809. }
  810. }
  811. //insert and sign NSEC3PARAM record
  812. {
  813. DnsNSEC3PARAMRecordData newNSec3Param = new DnsNSEC3PARAMRecordData(DnssecNSEC3HashAlgorithm.SHA1, DnssecNSEC3Flags.None, iterations, salt);
  814. DnsResourceRecord[] newNSec3ParamRecords = new DnsResourceRecord[] { new DnsResourceRecord(_name, DnsResourceRecordType.NSEC3PARAM, DnsClass.IN, ttl, newNSec3Param) };
  815. if (!TrySetRecords(DnsResourceRecordType.NSEC3PARAM, newNSec3ParamRecords, out IReadOnlyList<DnsResourceRecord> deletedNSec3ParamRecords))
  816. throw new InvalidOperationException();
  817. addedRecords.AddRange(newNSec3ParamRecords);
  818. deletedRecords.AddRange(deletedNSec3ParamRecords);
  819. IReadOnlyList<DnsResourceRecord> newRRSigRecords = SignRRSet(newNSec3ParamRecords);
  820. if (newRRSigRecords.Count > 0)
  821. {
  822. AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  823. addedRecords.AddRange(newRRSigRecords);
  824. deletedRecords.AddRange(deletedRRSigRecords);
  825. }
  826. }
  827. CommitAndIncrementSerial(deletedRecords, addedRecords);
  828. }
  829. private void DisableNSec3(IReadOnlyList<AuthZone> zones)
  830. {
  831. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  832. foreach (AuthZone zone in zones)
  833. {
  834. deletedRecords.AddRange(zone.RemoveNSec3RecordsWithRRSig());
  835. if (zone is SubDomainZone subDomainZone)
  836. {
  837. if (zone.IsEmpty)
  838. _dnsServer.AuthZoneManager.RemoveSubDomainZone(zone.Name); //remove empty sub zone
  839. else
  840. subDomainZone.AutoUpdateState();
  841. }
  842. }
  843. CommitAndIncrementSerial(deletedRecords);
  844. }
  845. public void GenerateAndAddRsaKey(DnssecPrivateKeyType keyType, string hashAlgorithm, int keySize, ushort rolloverDays)
  846. {
  847. if (_dnssecStatus == AuthZoneDnssecStatus.Unsigned)
  848. throw new DnsServerException("The zone must be signed.");
  849. DnssecAlgorithm algorithm;
  850. switch (hashAlgorithm.ToUpper())
  851. {
  852. case "MD5":
  853. algorithm = DnssecAlgorithm.RSAMD5;
  854. break;
  855. case "SHA1":
  856. algorithm = DnssecAlgorithm.RSASHA1;
  857. break;
  858. case "SHA256":
  859. algorithm = DnssecAlgorithm.RSASHA256;
  860. break;
  861. case "SHA512":
  862. algorithm = DnssecAlgorithm.RSASHA512;
  863. break;
  864. default:
  865. throw new NotSupportedException("Hash algorithm is not supported: " + hashAlgorithm);
  866. }
  867. GenerateAndAddRsaKey(keyType, algorithm, keySize, rolloverDays);
  868. }
  869. private void GenerateAndAddRsaKey(DnssecPrivateKeyType keyType, DnssecAlgorithm algorithm, int keySize, ushort rolloverDays)
  870. {
  871. int i = 0;
  872. while (i++ < 5)
  873. {
  874. DnssecPrivateKey privateKey = DnssecPrivateKey.Create(algorithm, keyType, keySize);
  875. privateKey.RolloverDays = rolloverDays;
  876. lock (_dnssecPrivateKeys)
  877. {
  878. if (_dnssecPrivateKeys.TryAdd(privateKey.KeyTag, privateKey))
  879. return;
  880. }
  881. }
  882. throw new DnsServerException("Failed to add private key: key tag collision.");
  883. }
  884. public void GenerateAndAddEcdsaKey(DnssecPrivateKeyType keyType, string curve, ushort rolloverDays)
  885. {
  886. if (_dnssecStatus == AuthZoneDnssecStatus.Unsigned)
  887. throw new DnsServerException("The zone must be signed.");
  888. DnssecAlgorithm algorithm;
  889. switch (curve.ToUpper())
  890. {
  891. case "P256":
  892. algorithm = DnssecAlgorithm.ECDSAP256SHA256;
  893. break;
  894. case "P384":
  895. algorithm = DnssecAlgorithm.ECDSAP384SHA384;
  896. break;
  897. default:
  898. throw new NotSupportedException("ECDSA curve is not supported: " + curve);
  899. }
  900. GenerateAndAddEcdsaKey(keyType, algorithm, rolloverDays);
  901. }
  902. private void GenerateAndAddEcdsaKey(DnssecPrivateKeyType keyType, DnssecAlgorithm algorithm, ushort rolloverDays)
  903. {
  904. int i = 0;
  905. while (i++ < 5)
  906. {
  907. DnssecPrivateKey privateKey = DnssecPrivateKey.Create(algorithm, keyType);
  908. privateKey.RolloverDays = rolloverDays;
  909. lock (_dnssecPrivateKeys)
  910. {
  911. if (_dnssecPrivateKeys.TryAdd(privateKey.KeyTag, privateKey))
  912. return;
  913. }
  914. }
  915. throw new DnsServerException("Failed to add private key: key tag collision.");
  916. }
  917. public void UpdatePrivateKey(ushort keyTag, ushort rolloverDays)
  918. {
  919. lock (_dnssecPrivateKeys)
  920. {
  921. if (!_dnssecPrivateKeys.TryGetValue(keyTag, out DnssecPrivateKey privateKey))
  922. throw new DnsServerException("Cannot update private key: no such private key was found.");
  923. privateKey.RolloverDays = rolloverDays;
  924. }
  925. }
  926. public void DeletePrivateKey(ushort keyTag)
  927. {
  928. if (_dnssecStatus == AuthZoneDnssecStatus.Unsigned)
  929. throw new DnsServerException("The zone must be signed.");
  930. lock (_dnssecPrivateKeys)
  931. {
  932. if (!_dnssecPrivateKeys.TryGetValue(keyTag, out DnssecPrivateKey privateKey))
  933. throw new DnsServerException("Cannot delete private key: no such private key was found.");
  934. if (privateKey.State != DnssecPrivateKeyState.Generated)
  935. throw new DnsServerException("Cannot delete private key: only keys with Generated state can be deleted.");
  936. _dnssecPrivateKeys.Remove(keyTag);
  937. }
  938. }
  939. public void PublishAllGeneratedKeys()
  940. {
  941. if (_dnssecStatus == AuthZoneDnssecStatus.Unsigned)
  942. throw new DnsServerException("The zone must be signed.");
  943. List<DnssecPrivateKey> generatedPrivateKeys = new List<DnssecPrivateKey>();
  944. List<DnsResourceRecord> newDnsKeyRecords = new List<DnsResourceRecord>();
  945. uint dnsKeyTtl = GetDnsKeyTtl();
  946. lock (_dnssecPrivateKeys)
  947. {
  948. foreach (KeyValuePair<ushort, DnssecPrivateKey> privateKeyEntry in _dnssecPrivateKeys)
  949. {
  950. DnssecPrivateKey privateKey = privateKeyEntry.Value;
  951. if (privateKey.State == DnssecPrivateKeyState.Generated)
  952. {
  953. generatedPrivateKeys.Add(privateKey);
  954. newDnsKeyRecords.Add(new DnsResourceRecord(_name, DnsResourceRecordType.DNSKEY, DnsClass.IN, dnsKeyTtl, privateKey.DnsKey));
  955. }
  956. }
  957. }
  958. if (generatedPrivateKeys.Count == 0)
  959. throw new DnsServerException("Cannot publish DNSKEY: no generated private keys were found.");
  960. IReadOnlyList<DnsResourceRecord> dnsKeyRecords = _entries.AddOrUpdate(DnsResourceRecordType.DNSKEY, delegate (DnsResourceRecordType key)
  961. {
  962. return newDnsKeyRecords;
  963. },
  964. delegate (DnsResourceRecordType key, IReadOnlyList<DnsResourceRecord> existingRecords)
  965. {
  966. foreach (DnsResourceRecord existingRecord in existingRecords)
  967. {
  968. foreach (DnsResourceRecord newDnsKeyRecord in newDnsKeyRecords)
  969. {
  970. if (existingRecord.Equals(newDnsKeyRecord))
  971. throw new DnsServerException("Cannot publish DNSKEY: the key is already published.");
  972. }
  973. }
  974. List<DnsResourceRecord> dnsKeyRecords = new List<DnsResourceRecord>(existingRecords.Count + newDnsKeyRecords.Count);
  975. dnsKeyRecords.AddRange(existingRecords);
  976. dnsKeyRecords.AddRange(newDnsKeyRecords);
  977. return dnsKeyRecords;
  978. });
  979. //update private key state before signing
  980. foreach (DnssecPrivateKey privateKey in generatedPrivateKeys)
  981. privateKey.SetState(DnssecPrivateKeyState.Published);
  982. List<DnsResourceRecord> addedRecords = new List<DnsResourceRecord>();
  983. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  984. addedRecords.AddRange(newDnsKeyRecords);
  985. IReadOnlyList<DnsResourceRecord> newRRSigRecords = SignRRSet(dnsKeyRecords);
  986. if (newRRSigRecords.Count > 0)
  987. {
  988. AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  989. addedRecords.AddRange(newRRSigRecords);
  990. deletedRecords.AddRange(deletedRRSigRecords);
  991. }
  992. CommitAndIncrementSerial(deletedRecords, addedRecords);
  993. TriggerNotify();
  994. }
  995. private void ActivateZskDnsKeys(IReadOnlyList<DnssecPrivateKey> zskPrivateKeys)
  996. {
  997. List<DnsResourceRecord> addedRecords = new List<DnsResourceRecord>();
  998. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  999. //re-sign all records with new private keys
  1000. IReadOnlyList<AuthZone> zones = _dnsServer.AuthZoneManager.GetApexZoneWithSubDomainZones(_name);
  1001. foreach (AuthZone zone in zones)
  1002. {
  1003. IReadOnlyList<DnsResourceRecord> newRRSigRecords = zone.SignAllRRSets();
  1004. if (newRRSigRecords.Count > 0)
  1005. {
  1006. zone.AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  1007. addedRecords.AddRange(newRRSigRecords);
  1008. deletedRecords.AddRange(deletedRRSigRecords);
  1009. }
  1010. }
  1011. CommitAndIncrementSerial(deletedRecords, addedRecords);
  1012. TriggerNotify();
  1013. //update private key state
  1014. string dnsKeyTags = null;
  1015. foreach (DnssecPrivateKey privateKey in zskPrivateKeys)
  1016. {
  1017. privateKey.SetState(DnssecPrivateKeyState.Active);
  1018. if (dnsKeyTags is null)
  1019. dnsKeyTags = privateKey.KeyTag.ToString();
  1020. else
  1021. dnsKeyTags += ", " + privateKey.KeyTag.ToString();
  1022. }
  1023. LogManager log = _dnsServer.LogManager;
  1024. if (log is not null)
  1025. log.Write("The ZSK DNSKEYs (" + dnsKeyTags + ") from the primary zone were activated successfully: " + ToString());
  1026. }
  1027. public void RolloverDnsKey(ushort keyTag)
  1028. {
  1029. if (_dnssecStatus == AuthZoneDnssecStatus.Unsigned)
  1030. throw new DnsServerException("The zone must be signed.");
  1031. DnssecPrivateKey privateKey;
  1032. lock (_dnssecPrivateKeys)
  1033. {
  1034. if (!_dnssecPrivateKeys.TryGetValue(keyTag, out privateKey))
  1035. throw new DnsServerException("Cannot rollover private key: no such private key was found.");
  1036. }
  1037. switch (privateKey.State)
  1038. {
  1039. case DnssecPrivateKeyState.Ready:
  1040. case DnssecPrivateKeyState.Active:
  1041. if (privateKey.IsRetiring)
  1042. throw new DnsServerException("Cannot rollover private key: the private key is already set to retire.");
  1043. break;
  1044. default:
  1045. throw new DnsServerException("Cannot rollover private key: the private key state must be Ready or Active to be able to rollover.");
  1046. }
  1047. switch (privateKey.Algorithm)
  1048. {
  1049. case DnssecAlgorithm.RSAMD5:
  1050. case DnssecAlgorithm.RSASHA1:
  1051. case DnssecAlgorithm.RSASHA1_NSEC3_SHA1:
  1052. case DnssecAlgorithm.RSASHA256:
  1053. case DnssecAlgorithm.RSASHA512:
  1054. GenerateAndAddRsaKey(privateKey.KeyType, privateKey.Algorithm, (privateKey as DnssecRsaPrivateKey).KeySize, privateKey.RolloverDays);
  1055. break;
  1056. case DnssecAlgorithm.ECDSAP256SHA256:
  1057. case DnssecAlgorithm.ECDSAP384SHA384:
  1058. GenerateAndAddEcdsaKey(privateKey.KeyType, privateKey.Algorithm, privateKey.RolloverDays);
  1059. break;
  1060. default:
  1061. throw new NotSupportedException("DNSSEC algorithm is not supported: " + privateKey.Algorithm.ToString());
  1062. }
  1063. PublishAllGeneratedKeys();
  1064. privateKey.SetToRetire();
  1065. }
  1066. public void RetireDnsKey(ushort keyTag)
  1067. {
  1068. if (_dnssecStatus == AuthZoneDnssecStatus.Unsigned)
  1069. throw new DnsServerException("The zone must be signed.");
  1070. DnssecPrivateKey privateKeyToRetire;
  1071. lock (_dnssecPrivateKeys)
  1072. {
  1073. if (!_dnssecPrivateKeys.TryGetValue(keyTag, out privateKeyToRetire))
  1074. throw new DnsServerException("Cannot retire private key: no such private key was found.");
  1075. }
  1076. switch (privateKeyToRetire.KeyType)
  1077. {
  1078. case DnssecPrivateKeyType.KeySigningKey:
  1079. switch (privateKeyToRetire.State)
  1080. {
  1081. case DnssecPrivateKeyState.Ready:
  1082. case DnssecPrivateKeyState.Active:
  1083. if (!RetireKskDnsKeys(new DnssecPrivateKey[] { privateKeyToRetire }, true))
  1084. throw new DnsServerException("Cannot retire private key: no successor key was found to safely retire the key.");
  1085. break;
  1086. default:
  1087. throw new DnsServerException("Cannot retire private key: the KSK private key state must be Ready or Active to be able to retire.");
  1088. }
  1089. break;
  1090. case DnssecPrivateKeyType.ZoneSigningKey:
  1091. switch (privateKeyToRetire.State)
  1092. {
  1093. case DnssecPrivateKeyState.Active:
  1094. if (!RetireZskDnsKeys(new DnssecPrivateKey[] { privateKeyToRetire }, true))
  1095. throw new DnsServerException("Cannot retire private key: no successor key was found to safely retire the key.");
  1096. break;
  1097. default:
  1098. throw new DnsServerException("Cannot retire private key: the ZSK private key state must be Active to be able to retire.");
  1099. }
  1100. break;
  1101. default:
  1102. throw new InvalidOperationException();
  1103. }
  1104. }
  1105. private bool RetireKskDnsKeys(IReadOnlyList<DnssecPrivateKey> kskPrivateKeys, bool ignoreAlgorithm)
  1106. {
  1107. string dnsKeyTags = null;
  1108. foreach (DnssecPrivateKey kskPrivateKey in kskPrivateKeys)
  1109. {
  1110. bool isSafeToRetire = false;
  1111. lock (_dnssecPrivateKeys)
  1112. {
  1113. foreach (KeyValuePair<ushort, DnssecPrivateKey> privateKeyEntry in _dnssecPrivateKeys)
  1114. {
  1115. DnssecPrivateKey privateKey = privateKeyEntry.Value;
  1116. if ((privateKey.KeyType == DnssecPrivateKeyType.KeySigningKey) && (privateKey.KeyTag != kskPrivateKey.KeyTag) && !privateKey.IsRetiring)
  1117. {
  1118. if (ignoreAlgorithm)
  1119. {
  1120. //manual retire case
  1121. if (privateKey.Algorithm != kskPrivateKey.Algorithm)
  1122. {
  1123. //check if the sucessor ksk has a matching zsk
  1124. bool foundMatchingZsk = false;
  1125. foreach (KeyValuePair<ushort, DnssecPrivateKey> zskPrivateKeyEntry in _dnssecPrivateKeys)
  1126. {
  1127. DnssecPrivateKey zskPrivateKey = zskPrivateKeyEntry.Value;
  1128. if ((zskPrivateKey.KeyType == DnssecPrivateKeyType.ZoneSigningKey) && (zskPrivateKey.Algorithm == privateKey.Algorithm) && (zskPrivateKey.State == DnssecPrivateKeyState.Active) && !zskPrivateKey.IsRetiring)
  1129. {
  1130. foundMatchingZsk = true;
  1131. break;
  1132. }
  1133. }
  1134. if (!foundMatchingZsk)
  1135. continue;
  1136. }
  1137. }
  1138. else
  1139. {
  1140. //rollover case
  1141. if (privateKey.Algorithm != kskPrivateKey.Algorithm)
  1142. continue;
  1143. }
  1144. if (privateKey.State == DnssecPrivateKeyState.Active)
  1145. {
  1146. isSafeToRetire = true;
  1147. break;
  1148. }
  1149. if ((privateKey.State == DnssecPrivateKeyState.Ready) && (kskPrivateKey.State == DnssecPrivateKeyState.Ready))
  1150. {
  1151. isSafeToRetire = true;
  1152. break;
  1153. }
  1154. }
  1155. }
  1156. }
  1157. if (isSafeToRetire)
  1158. {
  1159. kskPrivateKey.SetState(DnssecPrivateKeyState.Retired);
  1160. if (dnsKeyTags is null)
  1161. dnsKeyTags = kskPrivateKey.KeyTag.ToString();
  1162. else
  1163. dnsKeyTags += ", " + kskPrivateKey.KeyTag.ToString();
  1164. }
  1165. }
  1166. if (dnsKeyTags is not null)
  1167. {
  1168. LogManager log = _dnsServer.LogManager;
  1169. if (log is not null)
  1170. log.Write("The KSK DNSKEYs (" + dnsKeyTags + ") from the primary zone were retired successfully: " + ToString());
  1171. return true;
  1172. }
  1173. return false;
  1174. }
  1175. private bool RetireZskDnsKeys(IReadOnlyList<DnssecPrivateKey> zskPrivateKeys, bool ignoreAlgorithm)
  1176. {
  1177. string dnsKeyTags = null;
  1178. List<DnssecPrivateKey> zskToDeactivate = null;
  1179. foreach (DnssecPrivateKey zskPrivateKey in zskPrivateKeys)
  1180. {
  1181. bool isSafeToRetire = false;
  1182. lock (_dnssecPrivateKeys)
  1183. {
  1184. foreach (KeyValuePair<ushort, DnssecPrivateKey> privateKeyEntry in _dnssecPrivateKeys)
  1185. {
  1186. DnssecPrivateKey privateKey = privateKeyEntry.Value;
  1187. if ((privateKey.KeyType == DnssecPrivateKeyType.ZoneSigningKey) && (privateKey.KeyTag != zskPrivateKey.KeyTag) && (privateKey.State == DnssecPrivateKeyState.Active) && !privateKey.IsRetiring)
  1188. {
  1189. if (ignoreAlgorithm)
  1190. {
  1191. //manual retire case
  1192. if (privateKey.Algorithm != zskPrivateKey.Algorithm)
  1193. {
  1194. //check if the sucessor zsk has a matching ksk
  1195. bool foundMatchingKsk = false;
  1196. foreach (KeyValuePair<ushort, DnssecPrivateKey> kskPrivateKeyEntry in _dnssecPrivateKeys)
  1197. {
  1198. DnssecPrivateKey kskPrivateKey = kskPrivateKeyEntry.Value;
  1199. if ((kskPrivateKey.KeyType == DnssecPrivateKeyType.KeySigningKey) && (kskPrivateKey.Algorithm == privateKey.Algorithm) && ((kskPrivateKey.State == DnssecPrivateKeyState.Ready) || (kskPrivateKey.State == DnssecPrivateKeyState.Active)) && !kskPrivateKey.IsRetiring)
  1200. {
  1201. foundMatchingKsk = true;
  1202. break;
  1203. }
  1204. }
  1205. if (!foundMatchingKsk)
  1206. continue;
  1207. }
  1208. }
  1209. else
  1210. {
  1211. //rollover case
  1212. if (privateKey.Algorithm != zskPrivateKey.Algorithm)
  1213. continue;
  1214. }
  1215. isSafeToRetire = true;
  1216. break;
  1217. }
  1218. }
  1219. }
  1220. if (isSafeToRetire)
  1221. {
  1222. zskPrivateKey.SetState(DnssecPrivateKeyState.Retired);
  1223. if (zskToDeactivate is null)
  1224. zskToDeactivate = new List<DnssecPrivateKey>();
  1225. zskToDeactivate.Add(zskPrivateKey);
  1226. if (dnsKeyTags is null)
  1227. dnsKeyTags = zskPrivateKey.KeyTag.ToString();
  1228. else
  1229. dnsKeyTags += ", " + zskPrivateKey.KeyTag.ToString();
  1230. }
  1231. }
  1232. if (zskToDeactivate is not null)
  1233. DeactivateZskDnsKeys(zskToDeactivate);
  1234. if (dnsKeyTags is not null)
  1235. {
  1236. LogManager log = _dnsServer.LogManager;
  1237. if (log is not null)
  1238. log.Write("The ZSK DNSKEYs (" + dnsKeyTags + ") from the primary zone were retired successfully: " + ToString());
  1239. return true;
  1240. }
  1241. return false;
  1242. }
  1243. private void DeactivateZskDnsKeys(IReadOnlyList<DnssecPrivateKey> zskPrivateKeys)
  1244. {
  1245. //remove all RRSIGs for the DNSKEYs
  1246. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  1247. IReadOnlyList<AuthZone> zones = _dnsServer.AuthZoneManager.GetApexZoneWithSubDomainZones(_name);
  1248. foreach (AuthZone zone in zones)
  1249. {
  1250. IReadOnlyList<DnsResourceRecord> rrsigRecords = zone.GetRecords(DnsResourceRecordType.RRSIG);
  1251. List<DnsResourceRecord> rrsigsToRemove = new List<DnsResourceRecord>();
  1252. foreach (DnsResourceRecord rrsigRecord in rrsigRecords)
  1253. {
  1254. DnsRRSIGRecordData rrsig = rrsigRecord.RDATA as DnsRRSIGRecordData;
  1255. foreach (DnssecPrivateKey privateKey in zskPrivateKeys)
  1256. {
  1257. if (rrsig.KeyTag == privateKey.KeyTag)
  1258. {
  1259. rrsigsToRemove.Add(rrsigRecord);
  1260. break;
  1261. }
  1262. }
  1263. }
  1264. if (zone.TryDeleteRecords(DnsResourceRecordType.RRSIG, rrsigsToRemove, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords))
  1265. deletedRecords.AddRange(deletedRRSigRecords);
  1266. }
  1267. CommitAndIncrementSerial(deletedRecords);
  1268. TriggerNotify();
  1269. string dnsKeyTags = null;
  1270. foreach (DnssecPrivateKey privateKey in zskPrivateKeys)
  1271. {
  1272. if (dnsKeyTags is null)
  1273. dnsKeyTags = privateKey.KeyTag.ToString();
  1274. else
  1275. dnsKeyTags += ", " + privateKey.KeyTag.ToString();
  1276. }
  1277. LogManager log = _dnsServer.LogManager;
  1278. if (log is not null)
  1279. log.Write("The ZSK DNSKEYs (" + dnsKeyTags + ") from the primary zone were deactivated successfully: " + ToString());
  1280. }
  1281. private void RevokeKskDnsKeys(IReadOnlyList<DnssecPrivateKey> kskPrivateKeys)
  1282. {
  1283. if (!_entries.TryGetValue(DnsResourceRecordType.DNSKEY, out IReadOnlyList<DnsResourceRecord> existingDnsKeyRecords))
  1284. throw new InvalidOperationException();
  1285. List<DnsResourceRecord> addedRecords = new List<DnsResourceRecord>();
  1286. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  1287. List<DnsResourceRecord> dnsKeyRecords = new List<DnsResourceRecord>();
  1288. foreach (DnsResourceRecord existingDnsKeyRecord in existingDnsKeyRecords)
  1289. {
  1290. bool found = false;
  1291. foreach (DnssecPrivateKey privateKey in kskPrivateKeys)
  1292. {
  1293. if (existingDnsKeyRecord.RDATA.Equals(privateKey.DnsKey))
  1294. {
  1295. found = true;
  1296. break;
  1297. }
  1298. }
  1299. if (!found)
  1300. dnsKeyRecords.Add(existingDnsKeyRecord);
  1301. }
  1302. uint dnsKeyTtl = existingDnsKeyRecords[0].OriginalTtlValue;
  1303. List<ushort> keyTagsToRemove = new List<ushort>(kskPrivateKeys.Count);
  1304. foreach (DnssecPrivateKey privateKey in kskPrivateKeys)
  1305. {
  1306. keyTagsToRemove.Add(privateKey.KeyTag);
  1307. privateKey.SetState(DnssecPrivateKeyState.Revoked);
  1308. DnsResourceRecord revokedDnsKeyRecord = new DnsResourceRecord(_name, DnsResourceRecordType.DNSKEY, DnsClass.IN, dnsKeyTtl, privateKey.DnsKey);
  1309. dnsKeyRecords.Add(revokedDnsKeyRecord);
  1310. }
  1311. if (!TrySetRecords(DnsResourceRecordType.DNSKEY, dnsKeyRecords, out IReadOnlyList<DnsResourceRecord> deletedDnsKeyRecords))
  1312. throw new InvalidOperationException();
  1313. addedRecords.AddRange(dnsKeyRecords);
  1314. deletedRecords.AddRange(deletedDnsKeyRecords);
  1315. IReadOnlyList<DnsResourceRecord> newRRSigRecords = SignRRSet(dnsKeyRecords);
  1316. if (newRRSigRecords.Count > 0)
  1317. {
  1318. AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  1319. addedRecords.AddRange(newRRSigRecords);
  1320. deletedRecords.AddRange(deletedRRSigRecords);
  1321. }
  1322. //remove RRSIG for removed keys
  1323. {
  1324. IReadOnlyList<DnsResourceRecord> rrsigRecords = GetRecords(DnsResourceRecordType.RRSIG);
  1325. List<DnsResourceRecord> rrsigsToRemove = new List<DnsResourceRecord>();
  1326. foreach (DnsResourceRecord rrsigRecord in rrsigRecords)
  1327. {
  1328. DnsRRSIGRecordData rrsig = rrsigRecord.RDATA as DnsRRSIGRecordData;
  1329. if (rrsig.TypeCovered != DnsResourceRecordType.DNSKEY)
  1330. continue;
  1331. foreach (ushort keyTagToRemove in keyTagsToRemove)
  1332. {
  1333. if (rrsig.KeyTag == keyTagToRemove)
  1334. {
  1335. rrsigsToRemove.Add(rrsigRecord);
  1336. break;
  1337. }
  1338. }
  1339. }
  1340. if (TryDeleteRecords(DnsResourceRecordType.RRSIG, rrsigsToRemove, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords))
  1341. deletedRecords.AddRange(deletedRRSigRecords);
  1342. }
  1343. CommitAndIncrementSerial(deletedRecords, addedRecords);
  1344. TriggerNotify();
  1345. //update revoked private keys
  1346. string dnsKeyTags = null;
  1347. lock (_dnssecPrivateKeys)
  1348. {
  1349. //remove old entry
  1350. foreach (ushort keyTag in keyTagsToRemove)
  1351. {
  1352. if (_dnssecPrivateKeys.Remove(keyTag))
  1353. {
  1354. if (dnsKeyTags is null)
  1355. dnsKeyTags = keyTag.ToString();
  1356. else
  1357. dnsKeyTags += ", " + keyTag.ToString();
  1358. }
  1359. }
  1360. //add new entry
  1361. foreach (DnssecPrivateKey privateKey in kskPrivateKeys)
  1362. _dnssecPrivateKeys.Add(privateKey.KeyTag, privateKey);
  1363. }
  1364. LogManager log = _dnsServer.LogManager;
  1365. if (log is not null)
  1366. log.Write("The KSK DNSKEYs (" + dnsKeyTags + ") from the primary zone were revoked successfully: " + ToString());
  1367. }
  1368. private void UnpublishDnsKeys(IReadOnlyList<DnssecPrivateKey> deadPrivateKeys)
  1369. {
  1370. if (!_entries.TryGetValue(DnsResourceRecordType.DNSKEY, out IReadOnlyList<DnsResourceRecord> existingDnsKeyRecords))
  1371. throw new InvalidOperationException();
  1372. List<DnsResourceRecord> addedRecords = new List<DnsResourceRecord>();
  1373. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  1374. List<DnsResourceRecord> dnsKeyRecords = new List<DnsResourceRecord>();
  1375. foreach (DnsResourceRecord existingDnsKeyRecord in existingDnsKeyRecords)
  1376. {
  1377. bool found = false;
  1378. foreach (DnssecPrivateKey privateKey in deadPrivateKeys)
  1379. {
  1380. if (existingDnsKeyRecord.RDATA.Equals(privateKey.DnsKey))
  1381. {
  1382. found = true;
  1383. break;
  1384. }
  1385. }
  1386. if (!found)
  1387. dnsKeyRecords.Add(existingDnsKeyRecord);
  1388. }
  1389. if (dnsKeyRecords.Count < 2)
  1390. throw new InvalidOperationException();
  1391. if (!TrySetRecords(DnsResourceRecordType.DNSKEY, dnsKeyRecords, out IReadOnlyList<DnsResourceRecord> deletedDnsKeyRecords))
  1392. throw new InvalidOperationException();
  1393. addedRecords.AddRange(dnsKeyRecords);
  1394. deletedRecords.AddRange(deletedDnsKeyRecords);
  1395. IReadOnlyList<DnsResourceRecord> newRRSigRecords = SignRRSet(dnsKeyRecords);
  1396. if (newRRSigRecords.Count > 0)
  1397. {
  1398. AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  1399. addedRecords.AddRange(newRRSigRecords);
  1400. deletedRecords.AddRange(deletedRRSigRecords);
  1401. }
  1402. //remove RRSig for revoked keys
  1403. {
  1404. IReadOnlyList<DnsResourceRecord> rrsigRecords = GetRecords(DnsResourceRecordType.RRSIG);
  1405. List<DnsResourceRecord> rrsigsToRemove = new List<DnsResourceRecord>();
  1406. foreach (DnsResourceRecord rrsigRecord in rrsigRecords)
  1407. {
  1408. DnsRRSIGRecordData rrsig = rrsigRecord.RDATA as DnsRRSIGRecordData;
  1409. if (rrsig.TypeCovered != DnsResourceRecordType.DNSKEY)
  1410. continue;
  1411. foreach (DnssecPrivateKey privateKey in deadPrivateKeys)
  1412. {
  1413. if (rrsig.KeyTag == privateKey.KeyTag)
  1414. {
  1415. rrsigsToRemove.Add(rrsigRecord);
  1416. break;
  1417. }
  1418. }
  1419. }
  1420. if (TryDeleteRecords(DnsResourceRecordType.RRSIG, rrsigsToRemove, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords))
  1421. deletedRecords.AddRange(deletedRRSigRecords);
  1422. }
  1423. CommitAndIncrementSerial(deletedRecords, addedRecords);
  1424. TriggerNotify();
  1425. //remove private keys permanently
  1426. string dnsKeyTags = null;
  1427. lock (_dnssecPrivateKeys)
  1428. {
  1429. foreach (DnssecPrivateKey privateKey in deadPrivateKeys)
  1430. {
  1431. if (_dnssecPrivateKeys.Remove(privateKey.KeyTag))
  1432. {
  1433. if (dnsKeyTags is null)
  1434. dnsKeyTags = privateKey.KeyTag.ToString();
  1435. else
  1436. dnsKeyTags += ", " + privateKey.KeyTag.ToString();
  1437. }
  1438. }
  1439. }
  1440. LogManager log = _dnsServer.LogManager;
  1441. if (log is not null)
  1442. log.Write("The DNSKEYs (" + dnsKeyTags + ") from the primary zone were unpublished successfully: " + ToString());
  1443. }
  1444. private async Task<IReadOnlyList<DnssecPrivateKey>> GetDSPublishedPrivateKeysAsync(IReadOnlyList<DnssecPrivateKey> privateKeys)
  1445. {
  1446. if (_name.Length == 0)
  1447. return privateKeys; //zone is root
  1448. //delete any existing DS entries from cache to allow resolving latest ones
  1449. _dnsServer.CacheZoneManager.DeleteZone(_name);
  1450. IReadOnlyList<DnsDSRecordData> dsRecords;
  1451. try
  1452. {
  1453. dsRecords = DnsClient.ParseResponseDS(await _dnsServer.DirectQueryAsync(new DnsQuestionRecord(_name, DnsResourceRecordType.DS, DnsClass.IN)));
  1454. }
  1455. catch (DnsClientNxDomainException)
  1456. {
  1457. return [];
  1458. }
  1459. List<DnssecPrivateKey> activePrivateKeys = new List<DnssecPrivateKey>(dsRecords.Count);
  1460. foreach (DnsDSRecordData dsRecord in dsRecords)
  1461. {
  1462. foreach (DnssecPrivateKey privateKey in privateKeys)
  1463. {
  1464. if ((dsRecord.KeyTag == privateKey.DnsKey.ComputedKeyTag) && (dsRecord.Algorithm == privateKey.DnsKey.Algorithm) && privateKey.DnsKey.IsDnsKeyValid(_name, dsRecord))
  1465. {
  1466. activePrivateKeys.Add(privateKey);
  1467. break;
  1468. }
  1469. }
  1470. }
  1471. return activePrivateKeys;
  1472. }
  1473. private bool TryRefreshAllSignatures()
  1474. {
  1475. List<DnsResourceRecord> addedRecords = new List<DnsResourceRecord>();
  1476. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  1477. IReadOnlyList<AuthZone> zones = _dnsServer.AuthZoneManager.GetApexZoneWithSubDomainZones(_name);
  1478. foreach (AuthZone zone in zones)
  1479. {
  1480. IReadOnlyList<DnsResourceRecord> newRRSigRecords = zone.RefreshSignatures();
  1481. if (newRRSigRecords.Count > 0)
  1482. {
  1483. zone.AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  1484. addedRecords.AddRange(newRRSigRecords);
  1485. deletedRecords.AddRange(deletedRRSigRecords);
  1486. }
  1487. }
  1488. if ((deletedRecords.Count > 0) || (addedRecords.Count > 0))
  1489. {
  1490. CommitAndIncrementSerial(deletedRecords, addedRecords);
  1491. TriggerNotify();
  1492. return true;
  1493. }
  1494. return false;
  1495. }
  1496. internal override IReadOnlyList<DnsResourceRecord> SignRRSet(IReadOnlyList<DnsResourceRecord> records)
  1497. {
  1498. DnsResourceRecordType rrsetType = records[0].Type;
  1499. List<DnsResourceRecord> rrsigRecords = new List<DnsResourceRecord>();
  1500. uint signatureValidityPeriod = GetSignatureValidityPeriod();
  1501. switch (rrsetType)
  1502. {
  1503. case DnsResourceRecordType.DNSKEY:
  1504. lock (_dnssecPrivateKeys)
  1505. {
  1506. foreach (KeyValuePair<ushort, DnssecPrivateKey> privateKeyEntry in _dnssecPrivateKeys)
  1507. {
  1508. DnssecPrivateKey privateKey = privateKeyEntry.Value;
  1509. if (privateKey.KeyType != DnssecPrivateKeyType.KeySigningKey)
  1510. continue;
  1511. switch (privateKey.State)
  1512. {
  1513. case DnssecPrivateKeyState.Published:
  1514. case DnssecPrivateKeyState.Ready:
  1515. case DnssecPrivateKeyState.Active:
  1516. case DnssecPrivateKeyState.Revoked:
  1517. rrsigRecords.Add(privateKey.SignRRSet(_name, records, DNSSEC_SIGNATURE_INCEPTION_OFFSET, signatureValidityPeriod));
  1518. break;
  1519. }
  1520. }
  1521. }
  1522. break;
  1523. case DnsResourceRecordType.RRSIG:
  1524. throw new InvalidOperationException();
  1525. case DnsResourceRecordType.ANAME:
  1526. case DnsResourceRecordType.APP:
  1527. throw new DnsServerException("Cannot sign RRSet: The record type [" + rrsetType.ToString() + "] is not supported by DNSSEC signed primary zones.");
  1528. default:
  1529. if ((rrsetType == DnsResourceRecordType.NS) && (records[0].Name.Length > _name.Length))
  1530. return Array.Empty<DnsResourceRecord>(); //referrer NS records are not signed
  1531. lock (_dnssecPrivateKeys)
  1532. {
  1533. foreach (KeyValuePair<ushort, DnssecPrivateKey> privateKeyEntry in _dnssecPrivateKeys)
  1534. {
  1535. DnssecPrivateKey privateKey = privateKeyEntry.Value;
  1536. if (privateKey.KeyType != DnssecPrivateKeyType.ZoneSigningKey)
  1537. continue;
  1538. switch (privateKey.State)
  1539. {
  1540. case DnssecPrivateKeyState.Ready:
  1541. case DnssecPrivateKeyState.Active:
  1542. rrsigRecords.Add(privateKey.SignRRSet(_name, records, DNSSEC_SIGNATURE_INCEPTION_OFFSET, signatureValidityPeriod));
  1543. break;
  1544. }
  1545. }
  1546. }
  1547. break;
  1548. }
  1549. if (rrsigRecords.Count == 0)
  1550. throw new InvalidOperationException("Cannot sign RRSet: no private key was available.");
  1551. return rrsigRecords;
  1552. }
  1553. internal void UpdateDnssecRecordsFor(AuthZone zone, DnsResourceRecordType type)
  1554. {
  1555. //lock to sync this call to prevent inconsistent NSEC/NSEC3 updates
  1556. lock (_dnssecUpdateLock)
  1557. {
  1558. IReadOnlyList<DnsResourceRecord> records = zone.GetRecords(type);
  1559. if (records.Count > 0)
  1560. {
  1561. //rrset added or updated
  1562. //sign rrset
  1563. IReadOnlyList<DnsResourceRecord> newRRSigRecords = SignRRSet(records);
  1564. if (newRRSigRecords.Count > 0)
  1565. {
  1566. zone.AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  1567. CommitAndIncrementSerial(deletedRRSigRecords, newRRSigRecords);
  1568. }
  1569. }
  1570. else
  1571. {
  1572. //rrset deleted
  1573. //delete rrsig
  1574. IReadOnlyList<DnsResourceRecord> existingRRSigRecords = zone.GetRecords(DnsResourceRecordType.RRSIG);
  1575. if (existingRRSigRecords.Count > 0)
  1576. {
  1577. List<DnsResourceRecord> recordsToDelete = new List<DnsResourceRecord>();
  1578. foreach (DnsResourceRecord existingRRSigRecord in existingRRSigRecords)
  1579. {
  1580. DnsRRSIGRecordData rrsig = existingRRSigRecord.RDATA as DnsRRSIGRecordData;
  1581. if (rrsig.TypeCovered == type)
  1582. recordsToDelete.Add(existingRRSigRecord);
  1583. }
  1584. if (zone.TryDeleteRecords(DnsResourceRecordType.RRSIG, recordsToDelete, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords))
  1585. CommitAndIncrementSerial(deletedRRSigRecords);
  1586. }
  1587. }
  1588. if (_dnssecStatus == AuthZoneDnssecStatus.SignedWithNSEC)
  1589. {
  1590. UpdateNSecRRSetFor(zone);
  1591. }
  1592. else
  1593. {
  1594. UpdateNSec3RRSetFor(zone);
  1595. int apexLabelCount = DnsRRSIGRecordData.GetLabelCount(_name);
  1596. int zoneLabelCount = DnsRRSIGRecordData.GetLabelCount(zone.Name);
  1597. if ((zoneLabelCount - apexLabelCount) > 1)
  1598. {
  1599. //empty non-terminal (ENT) may exists
  1600. string currentOwnerName = zone.Name;
  1601. while (true)
  1602. {
  1603. currentOwnerName = AuthZoneManager.GetParentZone(currentOwnerName);
  1604. if (currentOwnerName.Equals(_name, StringComparison.OrdinalIgnoreCase))
  1605. break;
  1606. //update NSEC3 rrset for current owner name
  1607. AuthZone entZone = _dnsServer.AuthZoneManager.GetAuthZone(_name, currentOwnerName);
  1608. if (entZone is null)
  1609. entZone = new PrimarySubDomainZone(null, currentOwnerName); //dummy empty non-terminal (ENT) sub domain object
  1610. UpdateNSec3RRSetFor(entZone);
  1611. }
  1612. }
  1613. }
  1614. }
  1615. }
  1616. private void UpdateNSecRRSetFor(AuthZone zone)
  1617. {
  1618. uint ttl = GetZoneSoaMinimum();
  1619. IReadOnlyList<DnsResourceRecord> newNSecRecords = GetUpdatedNSecRRSetFor(zone, ttl);
  1620. if (newNSecRecords.Count > 0)
  1621. {
  1622. DnsResourceRecord newNSecRecord = newNSecRecords[0];
  1623. DnsNSECRecordData newNSec = newNSecRecord.RDATA as DnsNSECRecordData;
  1624. if (newNSec.Types.Count == 2)
  1625. {
  1626. //only NSEC and RRSIG exists so remove NSEC
  1627. IReadOnlyList<DnsResourceRecord> deletedNSecRecords = zone.RemoveNSecRecordsWithRRSig();
  1628. if (deletedNSecRecords.Count > 0)
  1629. CommitAndIncrementSerial(deletedNSecRecords);
  1630. //relink previous nsec
  1631. RelinkPreviousNSecRRSetFor(newNSecRecord, ttl, true);
  1632. }
  1633. else
  1634. {
  1635. List<DnsResourceRecord> addedRecords = new List<DnsResourceRecord>();
  1636. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  1637. if (!zone.TrySetRecords(DnsResourceRecordType.NSEC, newNSecRecords, out IReadOnlyList<DnsResourceRecord> deletedNSecRecords))
  1638. throw new DnsServerException("Failed to set DNSSEC records. Please try again.");
  1639. addedRecords.AddRange(newNSecRecords);
  1640. deletedRecords.AddRange(deletedNSecRecords);
  1641. IReadOnlyList<DnsResourceRecord> newRRSigRecords = SignRRSet(newNSecRecords);
  1642. if (newRRSigRecords.Count > 0)
  1643. {
  1644. zone.AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  1645. addedRecords.AddRange(newRRSigRecords);
  1646. deletedRecords.AddRange(deletedRRSigRecords);
  1647. }
  1648. CommitAndIncrementSerial(deletedRecords, addedRecords);
  1649. if (deletedNSecRecords.Count == 0)
  1650. {
  1651. //new NSEC created since no old NSEC was removed
  1652. //relink previous nsec
  1653. RelinkPreviousNSecRRSetFor(newNSecRecord, ttl, false);
  1654. }
  1655. }
  1656. }
  1657. }
  1658. private void UpdateNSec3RRSetFor(AuthZone zone)
  1659. {
  1660. uint ttl = GetZoneSoaMinimum();
  1661. bool noSubDomainExistsForEmptyZone = (zone.IsEmpty || zone.HasOnlyNSec3Records()) && !_dnsServer.AuthZoneManager.SubDomainExistsFor(_name, zone.Name);
  1662. IReadOnlyList<DnsResourceRecord> newNSec3Records = GetUpdatedNSec3RRSetFor(zone, ttl, noSubDomainExistsForEmptyZone);
  1663. if (newNSec3Records.Count > 0)
  1664. {
  1665. DnsResourceRecord newNSec3Record = newNSec3Records[0];
  1666. AuthZone nsec3Zone = _dnsServer.AuthZoneManager.GetOrAddSubDomainZone(_name, newNSec3Record.Name);
  1667. if (nsec3Zone is null)
  1668. throw new InvalidOperationException();
  1669. if (noSubDomainExistsForEmptyZone)
  1670. {
  1671. //no records exists in real zone and no sub domain exists, so remove NSEC3
  1672. IReadOnlyList<DnsResourceRecord> deletedNSec3Records = nsec3Zone.RemoveNSec3RecordsWithRRSig();
  1673. if (deletedNSec3Records.Count > 0)
  1674. CommitAndIncrementSerial(deletedNSec3Records);
  1675. //remove nsec3 sub domain zone if empty since it wont get removed otherwise
  1676. if (nsec3Zone is SubDomainZone nsec3SubDomainZone)
  1677. {
  1678. if (nsec3Zone.IsEmpty)
  1679. _dnsServer.AuthZoneManager.RemoveSubDomainZone(nsec3Zone.Name); //remove empty sub zone
  1680. else
  1681. nsec3SubDomainZone.AutoUpdateState();
  1682. }
  1683. //remove the real zone if empty so that any of the ENT that exists can also be removed later
  1684. if (zone is SubDomainZone subDomainZone)
  1685. {
  1686. if (zone.IsEmpty)
  1687. _dnsServer.AuthZoneManager.RemoveSubDomainZone(zone.Name); //remove empty sub zone
  1688. else
  1689. subDomainZone.AutoUpdateState();
  1690. }
  1691. //relink previous nsec3
  1692. RelinkPreviousNSec3RRSet(newNSec3Record, ttl, true);
  1693. }
  1694. else
  1695. {
  1696. List<DnsResourceRecord> addedRecords = new List<DnsResourceRecord>();
  1697. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  1698. if (!nsec3Zone.TrySetRecords(DnsResourceRecordType.NSEC3, newNSec3Records, out IReadOnlyList<DnsResourceRecord> deletedNSec3Records))
  1699. throw new DnsServerException("Failed to set DNSSEC records. Please try again.");
  1700. addedRecords.AddRange(newNSec3Records);
  1701. deletedRecords.AddRange(deletedNSec3Records);
  1702. IReadOnlyList<DnsResourceRecord> newRRSigRecords = SignRRSet(newNSec3Records);
  1703. if (newRRSigRecords.Count > 0)
  1704. {
  1705. nsec3Zone.AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  1706. addedRecords.AddRange(newRRSigRecords);
  1707. deletedRecords.AddRange(deletedRRSigRecords);
  1708. }
  1709. CommitAndIncrementSerial(deletedRecords, addedRecords);
  1710. if (deletedNSec3Records.Count == 0)
  1711. {
  1712. //new NSEC3 created since no old NSEC3 was removed
  1713. //relink previous nsec
  1714. RelinkPreviousNSec3RRSet(newNSec3Record, ttl, false);
  1715. }
  1716. }
  1717. }
  1718. }
  1719. private IReadOnlyList<DnsResourceRecord> GetUpdatedNSecRRSetFor(AuthZone zone, uint ttl)
  1720. {
  1721. AuthZone nextZone = _dnsServer.AuthZoneManager.FindNextSubDomainZone(_name, zone.Name);
  1722. if (nextZone is null)
  1723. nextZone = this;
  1724. return zone.GetUpdatedNSecRRSet(nextZone.Name, ttl);
  1725. }
  1726. private IReadOnlyList<DnsResourceRecord> GetUpdatedNSec3RRSetFor(AuthZone zone, uint ttl, bool forceGetNewRRSet)
  1727. {
  1728. if (!_entries.TryGetValue(DnsResourceRecordType.NSEC3PARAM, out IReadOnlyList<DnsResourceRecord> nsec3ParamRecords))
  1729. throw new InvalidOperationException();
  1730. DnsResourceRecord nsec3ParamRecord = nsec3ParamRecords[0];
  1731. DnsNSEC3PARAMRecordData nsec3Param = nsec3ParamRecord.RDATA as DnsNSEC3PARAMRecordData;
  1732. string hashedOwnerName = nsec3Param.ComputeHashedOwnerNameBase32HexString(zone.Name) + (_name.Length > 0 ? "." + _name : "");
  1733. byte[] nextHashedOwnerName = null;
  1734. //find next hashed owner name
  1735. string currentOwnerName = hashedOwnerName;
  1736. while (true)
  1737. {
  1738. AuthZone nextZone = _dnsServer.AuthZoneManager.FindNextSubDomainZone(_name, currentOwnerName);
  1739. if (nextZone is null)
  1740. break;
  1741. IReadOnlyList<DnsResourceRecord> nextNSec3Records = nextZone.GetRecords(DnsResourceRecordType.NSEC3);
  1742. if (nextNSec3Records.Count > 0)
  1743. {
  1744. nextHashedOwnerName = DnsNSEC3RecordData.GetHashedOwnerNameFrom(nextNSec3Records[0].Name);
  1745. break;
  1746. }
  1747. currentOwnerName = nextZone.Name;
  1748. }
  1749. if (nextHashedOwnerName is null)
  1750. {
  1751. //didnt find next NSEC3 record since current must be last; find the first NSEC3 record
  1752. DnsResourceRecord previousNSec3Record = null;
  1753. while (true)
  1754. {
  1755. AuthZone previousZone = _dnsServer.AuthZoneManager.FindPreviousSubDomainZone(_name, currentOwnerName);
  1756. if (previousZone is null)
  1757. break;
  1758. IReadOnlyList<DnsResourceRecord> previousNSec3Records = previousZone.GetRecords(DnsResourceRecordType.NSEC3);
  1759. if (previousNSec3Records.Count > 0)
  1760. previousNSec3Record = previousNSec3Records[0];
  1761. currentOwnerName = previousZone.Name;
  1762. }
  1763. if (previousNSec3Record is not null)
  1764. nextHashedOwnerName = DnsNSEC3RecordData.GetHashedOwnerNameFrom(previousNSec3Record.Name);
  1765. }
  1766. if (nextHashedOwnerName is null)
  1767. nextHashedOwnerName = DnsNSEC3RecordData.GetHashedOwnerNameFrom(hashedOwnerName); //only 1 NSEC3 record in zone
  1768. IReadOnlyList<DnsResourceRecord> newNSec3Records = zone.CreateNSec3RRSet(hashedOwnerName, nextHashedOwnerName, ttl, nsec3Param.Iterations, nsec3Param.Salt);
  1769. if (forceGetNewRRSet)
  1770. return newNSec3Records;
  1771. AuthZone nsec3Zone = _dnsServer.AuthZoneManager.GetAuthZone(_name, hashedOwnerName);
  1772. if (nsec3Zone is null)
  1773. return newNSec3Records;
  1774. return nsec3Zone.GetUpdatedNSec3RRSet(newNSec3Records);
  1775. }
  1776. private void RelinkPreviousNSecRRSetFor(DnsResourceRecord currentNSecRecord, uint ttl, bool wasRemoved)
  1777. {
  1778. AuthZone previousNsecZone = _dnsServer.AuthZoneManager.FindPreviousSubDomainZone(_name, currentNSecRecord.Name);
  1779. if (previousNsecZone is null)
  1780. return; //current zone is apex
  1781. IReadOnlyList<DnsResourceRecord> newPreviousNSecRecords;
  1782. if (wasRemoved)
  1783. newPreviousNSecRecords = previousNsecZone.GetUpdatedNSecRRSet((currentNSecRecord.RDATA as DnsNSECRecordData).NextDomainName, ttl);
  1784. else
  1785. newPreviousNSecRecords = previousNsecZone.GetUpdatedNSecRRSet(currentNSecRecord.Name, ttl);
  1786. if (newPreviousNSecRecords.Count > 0)
  1787. {
  1788. if (!previousNsecZone.TrySetRecords(DnsResourceRecordType.NSEC, newPreviousNSecRecords, out IReadOnlyList<DnsResourceRecord> deletedNSecRecords))
  1789. throw new DnsServerException("Failed to set DNSSEC records. Please try again.");
  1790. List<DnsResourceRecord> addedRecords = new List<DnsResourceRecord>();
  1791. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  1792. addedRecords.AddRange(newPreviousNSecRecords);
  1793. deletedRecords.AddRange(deletedNSecRecords);
  1794. IReadOnlyList<DnsResourceRecord> newRRSigRecords = SignRRSet(newPreviousNSecRecords);
  1795. if (newRRSigRecords.Count > 0)
  1796. {
  1797. previousNsecZone.AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  1798. addedRecords.AddRange(newRRSigRecords);
  1799. deletedRecords.AddRange(deletedRRSigRecords);
  1800. }
  1801. CommitAndIncrementSerial(deletedRecords, addedRecords);
  1802. }
  1803. }
  1804. private void RelinkPreviousNSec3RRSet(DnsResourceRecord currentNSec3Record, uint ttl, bool wasRemoved)
  1805. {
  1806. DnsNSEC3RecordData currentNSec3 = currentNSec3Record.RDATA as DnsNSEC3RecordData;
  1807. //find the previous NSEC3 and update it
  1808. DnsResourceRecord previousNSec3Record = null;
  1809. AuthZone previousNSec3Zone;
  1810. string currentOwnerName = currentNSec3Record.Name;
  1811. while (true)
  1812. {
  1813. previousNSec3Zone = _dnsServer.AuthZoneManager.FindPreviousSubDomainZone(_name, currentOwnerName);
  1814. if (previousNSec3Zone is null)
  1815. break;
  1816. IReadOnlyList<DnsResourceRecord> previousNSec3Records = previousNSec3Zone.GetRecords(DnsResourceRecordType.NSEC3);
  1817. if (previousNSec3Records.Count > 0)
  1818. {
  1819. previousNSec3Record = previousNSec3Records[0];
  1820. break;
  1821. }
  1822. currentOwnerName = previousNSec3Zone.Name;
  1823. }
  1824. if (previousNSec3Record is null)
  1825. {
  1826. //didnt find previous NSEC3; find the last NSEC3 to update
  1827. if (wasRemoved)
  1828. currentOwnerName = currentNSec3.NextHashedOwnerName + (_name.Length > 0 ? "." + _name : "");
  1829. else
  1830. currentOwnerName = currentNSec3Record.Name;
  1831. while (true)
  1832. {
  1833. AuthZone nextNSec3Zone = _dnsServer.AuthZoneManager.GetAuthZone(_name, currentOwnerName);
  1834. if (nextNSec3Zone is null)
  1835. break;
  1836. IReadOnlyList<DnsResourceRecord> nextNSec3Records = nextNSec3Zone.GetRecords(DnsResourceRecordType.NSEC3);
  1837. if (nextNSec3Records.Count > 0)
  1838. {
  1839. previousNSec3Record = nextNSec3Records[0];
  1840. previousNSec3Zone = nextNSec3Zone;
  1841. string nextHashedOwnerNameString = (previousNSec3Record.RDATA as DnsNSEC3RecordData).NextHashedOwnerName + (_name.Length > 0 ? "." + _name : "");
  1842. if (DnsNSECRecordData.CanonicalComparison(previousNSec3Record.Name, nextHashedOwnerNameString) >= 0)
  1843. break; //found last NSEC3
  1844. //jump to next hashed owner
  1845. currentOwnerName = nextHashedOwnerNameString;
  1846. }
  1847. else
  1848. {
  1849. currentOwnerName = nextNSec3Zone.Name;
  1850. }
  1851. }
  1852. }
  1853. if (previousNSec3Record is null)
  1854. throw new InvalidOperationException();
  1855. DnsNSEC3RecordData previousNSec3 = previousNSec3Record.RDATA as DnsNSEC3RecordData;
  1856. DnsNSEC3RecordData newPreviousNSec3;
  1857. if (wasRemoved)
  1858. newPreviousNSec3 = new DnsNSEC3RecordData(DnssecNSEC3HashAlgorithm.SHA1, DnssecNSEC3Flags.None, previousNSec3.Iterations, previousNSec3.Salt, currentNSec3.NextHashedOwnerNameValue, previousNSec3.Types);
  1859. else
  1860. newPreviousNSec3 = new DnsNSEC3RecordData(DnssecNSEC3HashAlgorithm.SHA1, DnssecNSEC3Flags.None, previousNSec3.Iterations, previousNSec3.Salt, DnsNSEC3RecordData.GetHashedOwnerNameFrom(currentNSec3Record.Name), previousNSec3.Types);
  1861. DnsResourceRecord[] newPreviousNSec3Records = new DnsResourceRecord[] { new DnsResourceRecord(previousNSec3Record.Name, DnsResourceRecordType.NSEC3, DnsClass.IN, ttl, newPreviousNSec3) };
  1862. if (!previousNSec3Zone.TrySetRecords(DnsResourceRecordType.NSEC3, newPreviousNSec3Records, out IReadOnlyList<DnsResourceRecord> deletedNSec3Records))
  1863. throw new DnsServerException("Failed to set DNSSEC records. Please try again.");
  1864. List<DnsResourceRecord> addedRecords = new List<DnsResourceRecord>();
  1865. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  1866. addedRecords.AddRange(newPreviousNSec3Records);
  1867. deletedRecords.AddRange(deletedNSec3Records);
  1868. IReadOnlyList<DnsResourceRecord> newRRSigRecords = SignRRSet(newPreviousNSec3Records);
  1869. if (newRRSigRecords.Count > 0)
  1870. {
  1871. previousNSec3Zone.AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  1872. addedRecords.AddRange(newRRSigRecords);
  1873. deletedRecords.AddRange(deletedRRSigRecords);
  1874. }
  1875. CommitAndIncrementSerial(deletedRecords, addedRecords);
  1876. }
  1877. private uint GetSignatureValidityPeriod()
  1878. {
  1879. //SOA EXPIRE + 3 days
  1880. return (_entries[DnsResourceRecordType.SOA][0].RDATA as DnsSOARecordData).Expire + (3 * 24 * 60 * 60);
  1881. }
  1882. internal DateTime GetKskDnsKeyStateReadyBy(DnssecPrivateKey privateKey)
  1883. {
  1884. return GetKskDnsKeyStateReadyOn(privateKey).AddMilliseconds(DNSSEC_TIMER_PERIODIC_INTERVAL);
  1885. }
  1886. private DateTime GetKskDnsKeyStateReadyOn(DnssecPrivateKey privateKey)
  1887. {
  1888. bool foundOldKsk = false;
  1889. lock (_dnssecPrivateKeys)
  1890. {
  1891. foreach (KeyValuePair<ushort, DnssecPrivateKey> dnssecPrivateKey in _dnssecPrivateKeys)
  1892. {
  1893. DnssecPrivateKey kskPrivateKey = dnssecPrivateKey.Value;
  1894. if (kskPrivateKey.KeyType == DnssecPrivateKeyType.KeySigningKey)
  1895. {
  1896. if ((kskPrivateKey.State == DnssecPrivateKeyState.Ready) || (kskPrivateKey.State == DnssecPrivateKeyState.Active))
  1897. {
  1898. foundOldKsk = true;
  1899. break;
  1900. }
  1901. }
  1902. }
  1903. }
  1904. if (foundOldKsk)
  1905. return privateKey.StateChangedOn.AddSeconds(GetDnsKeyTtl() + GetPropagationDelay());
  1906. else
  1907. return privateKey.StateChangedOn.AddSeconds(GetMaxRecordTtl() + GetPropagationDelay()); //newly signed zone case
  1908. }
  1909. private uint GetPropagationDelay()
  1910. {
  1911. //the max time required to sync zone changes to secondaries if NOTIFY fails to trigger a zone transfer
  1912. DnsSOARecordData soa = _entries[DnsResourceRecordType.SOA][0].RDATA as DnsSOARecordData;
  1913. return soa.Refresh + soa.Retry;
  1914. }
  1915. private async Task<uint> GetParentSidePropagationDelayAsync()
  1916. {
  1917. uint parentSidePropagationDelay = 24 * 60 * 60;
  1918. try
  1919. {
  1920. string parent = AuthZoneManager.GetParentZone(_name);
  1921. if (parent is null)
  1922. parent = "";
  1923. DnsDatagram soaResponse = await _dnsServer.DirectQueryAsync(new DnsQuestionRecord(parent, DnsResourceRecordType.SOA, DnsClass.IN), 10000);
  1924. if (soaResponse.RCODE == DnsResponseCode.NoError)
  1925. {
  1926. IReadOnlyList<DnsResourceRecord> records;
  1927. if (soaResponse.Answer.Count > 0)
  1928. records = soaResponse.Answer;
  1929. else if (soaResponse.Authority.Count > 0)
  1930. records = soaResponse.Authority;
  1931. else
  1932. records = null;
  1933. if (records is not null)
  1934. {
  1935. foreach (DnsResourceRecord record in records)
  1936. {
  1937. if (record.Type == DnsResourceRecordType.SOA)
  1938. {
  1939. DnsSOARecordData parentSoa = record.RDATA as DnsSOARecordData;
  1940. parentSidePropagationDelay = parentSoa.Refresh + parentSoa.Retry;
  1941. break;
  1942. }
  1943. }
  1944. }
  1945. }
  1946. }
  1947. catch (Exception ex)
  1948. {
  1949. LogManager log = _dnsServer.LogManager;
  1950. if (log is not null)
  1951. log.Write(ex);
  1952. }
  1953. return parentSidePropagationDelay;
  1954. }
  1955. private uint GetMaxRecordTtl()
  1956. {
  1957. uint maxTtl = 0;
  1958. foreach (AuthZone zone in _dnsServer.AuthZoneManager.GetApexZoneWithSubDomainZones(_name))
  1959. {
  1960. foreach (KeyValuePair<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>> entry in zone.Entries)
  1961. {
  1962. if (entry.Key == DnsResourceRecordType.RRSIG)
  1963. continue;
  1964. IReadOnlyList<DnsResourceRecord> rrset = entry.Value;
  1965. //find min TTL
  1966. uint rrsetTtl = 0;
  1967. foreach (DnsResourceRecord rr in rrset)
  1968. {
  1969. if ((rrsetTtl == 0) || (rrsetTtl > rr.OriginalTtlValue))
  1970. rrsetTtl = rr.OriginalTtlValue;
  1971. }
  1972. if (rrsetTtl > maxTtl)
  1973. maxTtl = rrsetTtl;
  1974. }
  1975. }
  1976. return maxTtl;
  1977. }
  1978. private uint GetMaxRRSigTtl()
  1979. {
  1980. uint maxTtl = 0;
  1981. foreach (AuthZone zone in _dnsServer.AuthZoneManager.GetApexZoneWithSubDomainZones(_name))
  1982. {
  1983. if (!zone.Entries.TryGetValue(DnsResourceRecordType.RRSIG, out IReadOnlyList<DnsResourceRecord> rrsigRecords))
  1984. continue;
  1985. foreach (DnsResourceRecord rr in rrsigRecords)
  1986. {
  1987. if (rr.OriginalTtlValue > maxTtl)
  1988. maxTtl = rr.OriginalTtlValue;
  1989. }
  1990. }
  1991. return maxTtl;
  1992. }
  1993. private async Task<uint> GetDSTtlAsync()
  1994. {
  1995. uint dsTtl = 24 * 60 * 60;
  1996. try
  1997. {
  1998. DnsDatagram dsResponse = await _dnsServer.DirectQueryAsync(new DnsQuestionRecord(_name, DnsResourceRecordType.DS, DnsClass.IN), 10000);
  1999. if (dsResponse.RCODE == DnsResponseCode.NoError)
  2000. {
  2001. if (dsResponse.Answer.Count > 0)
  2002. {
  2003. //find min TTL
  2004. dsTtl = 0;
  2005. foreach (DnsResourceRecord answer in dsResponse.Answer)
  2006. {
  2007. if (answer.Type == DnsResourceRecordType.DS)
  2008. {
  2009. if ((dsTtl == 0) || (dsTtl > answer.OriginalTtlValue))
  2010. dsTtl = answer.OriginalTtlValue;
  2011. }
  2012. }
  2013. }
  2014. else
  2015. {
  2016. dsTtl = 0; //no DS was found
  2017. }
  2018. }
  2019. }
  2020. catch (Exception ex)
  2021. {
  2022. LogManager log = _dnsServer.LogManager;
  2023. if (log is not null)
  2024. log.Write(ex);
  2025. }
  2026. return dsTtl;
  2027. }
  2028. public uint GetDnsKeyTtl()
  2029. {
  2030. if (_entries.TryGetValue(DnsResourceRecordType.DNSKEY, out IReadOnlyList<DnsResourceRecord> dnsKeyRecords))
  2031. return dnsKeyRecords[0].OriginalTtlValue;
  2032. return 24 * 60 * 60;
  2033. }
  2034. public void UpdateDnsKeyTtl(uint dnsKeyTtl)
  2035. {
  2036. if (_dnssecStatus == AuthZoneDnssecStatus.Unsigned)
  2037. throw new DnsServerException("The zone must be signed.");
  2038. lock (_dnssecPrivateKeys)
  2039. {
  2040. foreach (KeyValuePair<ushort, DnssecPrivateKey> privateKeyEntry in _dnssecPrivateKeys)
  2041. {
  2042. switch (privateKeyEntry.Value.State)
  2043. {
  2044. case DnssecPrivateKeyState.Ready:
  2045. case DnssecPrivateKeyState.Active:
  2046. break;
  2047. default:
  2048. throw new DnsServerException("Cannot update DNSKEY TTL value: one or more private keys have state other than Ready or Active.");
  2049. }
  2050. }
  2051. }
  2052. if (!_entries.TryGetValue(DnsResourceRecordType.DNSKEY, out IReadOnlyList<DnsResourceRecord> dnsKeyRecords))
  2053. throw new InvalidOperationException();
  2054. DnsResourceRecord[] newDnsKeyRecords = new DnsResourceRecord[dnsKeyRecords.Count];
  2055. for (int i = 0; i < dnsKeyRecords.Count; i++)
  2056. {
  2057. DnsResourceRecord dnsKeyRecord = dnsKeyRecords[i];
  2058. newDnsKeyRecords[i] = new DnsResourceRecord(dnsKeyRecord.Name, DnsResourceRecordType.DNSKEY, DnsClass.IN, dnsKeyTtl, dnsKeyRecord.RDATA);
  2059. }
  2060. List<DnsResourceRecord> addedRecords = new List<DnsResourceRecord>();
  2061. List<DnsResourceRecord> deletedRecords = new List<DnsResourceRecord>();
  2062. if (!TrySetRecords(DnsResourceRecordType.DNSKEY, newDnsKeyRecords, out IReadOnlyList<DnsResourceRecord> deletedDnsKeyRecords))
  2063. throw new DnsServerException("Failed to update DNSKEY TTL. Please try again.");
  2064. addedRecords.AddRange(newDnsKeyRecords);
  2065. deletedRecords.AddRange(deletedDnsKeyRecords);
  2066. IReadOnlyList<DnsResourceRecord> newRRSigRecords = SignRRSet(newDnsKeyRecords);
  2067. if (newRRSigRecords.Count > 0)
  2068. {
  2069. AddOrUpdateRRSigRecords(newRRSigRecords, out IReadOnlyList<DnsResourceRecord> deletedRRSigRecords);
  2070. addedRecords.AddRange(newRRSigRecords);
  2071. deletedRecords.AddRange(deletedRRSigRecords);
  2072. }
  2073. CommitAndIncrementSerial(deletedRecords, addedRecords);
  2074. TriggerNotify();
  2075. }
  2076. #endregion
  2077. #region versioning
  2078. internal override void CommitAndIncrementSerial(IReadOnlyList<DnsResourceRecord> deletedRecords = null, IReadOnlyList<DnsResourceRecord> addedRecords = null)
  2079. {
  2080. if (_internal)
  2081. {
  2082. _lastModified = DateTime.UtcNow;
  2083. return;
  2084. }
  2085. base.CommitAndIncrementSerial(deletedRecords, addedRecords);
  2086. }
  2087. #endregion
  2088. #region public
  2089. public override string GetZoneTypeName()
  2090. {
  2091. return "Primary";
  2092. }
  2093. public override void SetRecords(DnsResourceRecordType type, IReadOnlyList<DnsResourceRecord> records)
  2094. {
  2095. if (_dnssecStatus != AuthZoneDnssecStatus.Unsigned)
  2096. {
  2097. switch (type)
  2098. {
  2099. case DnsResourceRecordType.ANAME:
  2100. case DnsResourceRecordType.APP:
  2101. throw new DnsServerException("The record type is not supported by DNSSEC signed primary zones.");
  2102. default:
  2103. foreach (DnsResourceRecord record in records)
  2104. {
  2105. if (record.GetAuthGenericRecordInfo().Disabled)
  2106. throw new DnsServerException("Cannot set records: disabling records in a signed zones is not supported.");
  2107. }
  2108. break;
  2109. }
  2110. }
  2111. switch (type)
  2112. {
  2113. case DnsResourceRecordType.CNAME:
  2114. case DnsResourceRecordType.DS:
  2115. throw new InvalidOperationException("Cannot set " + type.ToString() + " record at zone apex.");
  2116. case DnsResourceRecordType.SOA:
  2117. if ((records.Count != 1) || !records[0].Name.Equals(_name, StringComparison.OrdinalIgnoreCase))
  2118. throw new InvalidOperationException("Invalid SOA record.");
  2119. DnsResourceRecord newSoaRecord = records[0];
  2120. DnsSOARecordData newSoa = newSoaRecord.RDATA as DnsSOARecordData;
  2121. if (newSoaRecord.OriginalTtlValue > newSoa.Expire)
  2122. throw new DnsServerException("Failed to set records: TTL cannot be greater than SOA EXPIRE.");
  2123. if (newSoa.Retry > newSoa.Refresh)
  2124. throw new DnsServerException("Failed to set records: SOA RETRY cannot be greater than SOA REFRESH.");
  2125. if (newSoa.Refresh > newSoa.Expire)
  2126. throw new DnsServerException("Failed to set records: SOA REFRESH cannot be greater than SOA EXPIRE.");
  2127. //remove any record info except serial date scheme and comments
  2128. bool useSoaSerialDateScheme;
  2129. string comments;
  2130. {
  2131. SOARecordInfo recordInfo = newSoaRecord.GetAuthSOARecordInfo();
  2132. useSoaSerialDateScheme = recordInfo.UseSoaSerialDateScheme;
  2133. comments = recordInfo.Comments;
  2134. }
  2135. newSoaRecord.Tag = null; //remove old record info
  2136. {
  2137. SOARecordInfo recordInfo = newSoaRecord.GetAuthSOARecordInfo();
  2138. recordInfo.UseSoaSerialDateScheme = useSoaSerialDateScheme;
  2139. recordInfo.Comments = comments;
  2140. recordInfo.LastModified = DateTime.UtcNow;
  2141. }
  2142. uint oldSoaMinimum = GetZoneSoaMinimum();
  2143. //setting new SOA
  2144. if (_internal)
  2145. _entries[DnsResourceRecordType.SOA] = records; //update SOA directly
  2146. else
  2147. CommitAndIncrementSerial(null, records);
  2148. if (oldSoaMinimum != newSoa.Minimum)
  2149. {
  2150. switch (_dnssecStatus)
  2151. {
  2152. case AuthZoneDnssecStatus.SignedWithNSEC:
  2153. RefreshNSec();
  2154. break;
  2155. case AuthZoneDnssecStatus.SignedWithNSEC3:
  2156. RefreshNSec3();
  2157. break;
  2158. }
  2159. }
  2160. TriggerNotify();
  2161. break;
  2162. case DnsResourceRecordType.DNSKEY:
  2163. case DnsResourceRecordType.RRSIG:
  2164. case DnsResourceRecordType.NSEC:
  2165. case DnsResourceRecordType.NSEC3PARAM:
  2166. case DnsResourceRecordType.NSEC3:
  2167. throw new InvalidOperationException("Cannot set DNSSEC records.");
  2168. case DnsResourceRecordType.FWD:
  2169. throw new DnsServerException("The record type is not supported by primary zones.");
  2170. default:
  2171. if (records[0].OriginalTtlValue > GetZoneSoaExpire())
  2172. throw new DnsServerException("Failed to set records: TTL cannot be greater than SOA EXPIRE.");
  2173. if (!TrySetRecords(type, records, out IReadOnlyList<DnsResourceRecord> deletedRecords))
  2174. throw new DnsServerException("Failed to set records. Please try again.");
  2175. CommitAndIncrementSerial(deletedRecords, records);
  2176. if (_dnssecStatus != AuthZoneDnssecStatus.Unsigned)
  2177. UpdateDnssecRecordsFor(this, type);
  2178. TriggerNotify();
  2179. break;
  2180. }
  2181. }
  2182. public override void AddRecord(DnsResourceRecord record)
  2183. {
  2184. if (_dnssecStatus != AuthZoneDnssecStatus.Unsigned)
  2185. {
  2186. switch (record.Type)
  2187. {
  2188. case DnsResourceRecordType.ANAME:
  2189. case DnsResourceRecordType.APP:
  2190. throw new DnsServerException("The record type is not supported by DNSSEC signed primary zones.");
  2191. default:
  2192. if (record.GetAuthGenericRecordInfo().Disabled)
  2193. throw new DnsServerException("Cannot add record: disabling records in a signed zones is not supported.");
  2194. break;
  2195. }
  2196. }
  2197. switch (record.Type)
  2198. {
  2199. case DnsResourceRecordType.APP:
  2200. throw new InvalidOperationException("Cannot add record: use SetRecords() for " + record.Type.ToString() + " record");
  2201. case DnsResourceRecordType.DS:
  2202. throw new InvalidOperationException("Cannot set DS record at zone apex.");
  2203. case DnsResourceRecordType.DNSKEY:
  2204. case DnsResourceRecordType.RRSIG:
  2205. case DnsResourceRecordType.NSEC:
  2206. case DnsResourceRecordType.NSEC3PARAM:
  2207. case DnsResourceRecordType.NSEC3:
  2208. throw new InvalidOperationException("Cannot add DNSSEC record.");
  2209. case DnsResourceRecordType.FWD:
  2210. throw new DnsServerException("The record type is not supported by primary zones.");
  2211. default:
  2212. if (record.OriginalTtlValue > GetZoneSoaExpire())
  2213. throw new DnsServerException("Failed to add record: TTL cannot be greater than SOA EXPIRE.");
  2214. AddRecord(record, out IReadOnlyList<DnsResourceRecord> addedRecords, out IReadOnlyList<DnsResourceRecord> deletedRecords);
  2215. if (addedRecords.Count > 0)
  2216. {
  2217. CommitAndIncrementSerial(deletedRecords, addedRecords);
  2218. if (_dnssecStatus != AuthZoneDnssecStatus.Unsigned)
  2219. UpdateDnssecRecordsFor(this, record.Type);
  2220. TriggerNotify();
  2221. }
  2222. break;
  2223. }
  2224. }
  2225. public override bool DeleteRecords(DnsResourceRecordType type)
  2226. {
  2227. switch (type)
  2228. {
  2229. case DnsResourceRecordType.SOA:
  2230. throw new InvalidOperationException("Cannot delete SOA record.");
  2231. case DnsResourceRecordType.DNSKEY:
  2232. case DnsResourceRecordType.RRSIG:
  2233. case DnsResourceRecordType.NSEC:
  2234. case DnsResourceRecordType.NSEC3PARAM:
  2235. case DnsResourceRecordType.NSEC3:
  2236. throw new InvalidOperationException("Cannot delete DNSSEC records.");
  2237. default:
  2238. if (_entries.TryRemove(type, out IReadOnlyList<DnsResourceRecord> removedRecords))
  2239. {
  2240. CommitAndIncrementSerial(removedRecords);
  2241. if (_dnssecStatus != AuthZoneDnssecStatus.Unsigned)
  2242. UpdateDnssecRecordsFor(this, type);
  2243. TriggerNotify();
  2244. return true;
  2245. }
  2246. return false;
  2247. }
  2248. }
  2249. public override bool DeleteRecord(DnsResourceRecordType type, DnsResourceRecordData rdata)
  2250. {
  2251. switch (type)
  2252. {
  2253. case DnsResourceRecordType.SOA:
  2254. throw new InvalidOperationException("Cannot delete SOA record.");
  2255. case DnsResourceRecordType.DNSKEY:
  2256. case DnsResourceRecordType.RRSIG:
  2257. case DnsResourceRecordType.NSEC:
  2258. case DnsResourceRecordType.NSEC3PARAM:
  2259. case DnsResourceRecordType.NSEC3:
  2260. throw new InvalidOperationException("Cannot delete DNSSEC records.");
  2261. default:
  2262. if (TryDeleteRecord(type, rdata, out DnsResourceRecord deletedRecord))
  2263. {
  2264. CommitAndIncrementSerial([deletedRecord]);
  2265. if (_dnssecStatus != AuthZoneDnssecStatus.Unsigned)
  2266. UpdateDnssecRecordsFor(this, type);
  2267. TriggerNotify();
  2268. return true;
  2269. }
  2270. return false;
  2271. }
  2272. }
  2273. public override void UpdateRecord(DnsResourceRecord oldRecord, DnsResourceRecord newRecord)
  2274. {
  2275. switch (oldRecord.Type)
  2276. {
  2277. case DnsResourceRecordType.SOA:
  2278. throw new InvalidOperationException("Cannot update record: use SetRecords() for " + oldRecord.Type.ToString() + " record");
  2279. case DnsResourceRecordType.DNSKEY:
  2280. case DnsResourceRecordType.RRSIG:
  2281. case DnsResourceRecordType.NSEC:
  2282. case DnsResourceRecordType.NSEC3PARAM:
  2283. case DnsResourceRecordType.NSEC3:
  2284. throw new InvalidOperationException("Cannot update DNSSEC records.");
  2285. default:
  2286. if (oldRecord.Type != newRecord.Type)
  2287. throw new InvalidOperationException("Old and new record types do not match.");
  2288. if ((_dnssecStatus != AuthZoneDnssecStatus.Unsigned) && newRecord.GetAuthGenericRecordInfo().Disabled)
  2289. throw new DnsServerException("Cannot update record: disabling records in a signed zones is not supported.");
  2290. if (newRecord.OriginalTtlValue > GetZoneSoaExpire())
  2291. throw new DnsServerException("Cannot update record: TTL cannot be greater than SOA EXPIRE.");
  2292. if (!TryDeleteRecord(oldRecord.Type, oldRecord.RDATA, out DnsResourceRecord deletedRecord))
  2293. throw new DnsServerException("Cannot update record: the record does not exists to be updated.");
  2294. AddRecord(newRecord, out IReadOnlyList<DnsResourceRecord> addedRecords, out IReadOnlyList<DnsResourceRecord> deletedRecords);
  2295. List<DnsResourceRecord> allDeletedRecords = new List<DnsResourceRecord>(deletedRecords.Count + 1);
  2296. allDeletedRecords.Add(deletedRecord);
  2297. allDeletedRecords.AddRange(deletedRecords);
  2298. CommitAndIncrementSerial(allDeletedRecords, addedRecords);
  2299. if (_dnssecStatus != AuthZoneDnssecStatus.Unsigned)
  2300. UpdateDnssecRecordsFor(this, oldRecord.Type);
  2301. TriggerNotify();
  2302. break;
  2303. }
  2304. }
  2305. #endregion
  2306. #region properties
  2307. public override bool Disabled
  2308. {
  2309. get { return base.Disabled; }
  2310. set
  2311. {
  2312. if (base.Disabled == value)
  2313. return;
  2314. base.Disabled = value; //set value early to be able to use it for notify
  2315. if (value)
  2316. DisableNotifyTimer();
  2317. else
  2318. TriggerNotify();
  2319. }
  2320. }
  2321. public override AuthZoneTransfer ZoneTransfer
  2322. {
  2323. get { return base.ZoneTransfer; }
  2324. set
  2325. {
  2326. if (_internal)
  2327. throw new InvalidOperationException();
  2328. base.ZoneTransfer = value;
  2329. }
  2330. }
  2331. public override AuthZoneNotify Notify
  2332. {
  2333. get { return base.Notify; }
  2334. set
  2335. {
  2336. if (_internal)
  2337. throw new InvalidOperationException();
  2338. switch (value)
  2339. {
  2340. case AuthZoneNotify.SeparateNameServersForCatalogAndMemberZones:
  2341. throw new ArgumentException("The Notify option is invalid for " + GetZoneTypeName() + " zones: " + value.ToString(), nameof(Notify));
  2342. }
  2343. base.Notify = value;
  2344. }
  2345. }
  2346. public override AuthZoneUpdate Update
  2347. {
  2348. get { return base.Update; }
  2349. set
  2350. {
  2351. if (_internal)
  2352. throw new InvalidOperationException();
  2353. base.Update = value;
  2354. }
  2355. }
  2356. public bool Internal
  2357. { get { return _internal; } }
  2358. public IReadOnlyCollection<DnssecPrivateKey> DnssecPrivateKeys
  2359. {
  2360. get
  2361. {
  2362. if (_dnssecPrivateKeys is null)
  2363. return null;
  2364. lock (_dnssecPrivateKeys)
  2365. {
  2366. return _dnssecPrivateKeys.Values;
  2367. }
  2368. }
  2369. }
  2370. #endregion
  2371. }
  2372. }