DnsServer.cs 222 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2023 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerCore.ApplicationCommon;
  16. using DnsServerCore.Dns.Applications;
  17. using DnsServerCore.Dns.ResourceRecords;
  18. using DnsServerCore.Dns.Trees;
  19. using DnsServerCore.Dns.ZoneManagers;
  20. using DnsServerCore.Dns.Zones;
  21. using Microsoft.AspNetCore.Builder;
  22. using Microsoft.AspNetCore.Connections;
  23. using Microsoft.AspNetCore.Hosting;
  24. using Microsoft.AspNetCore.Http;
  25. using Microsoft.AspNetCore.Server.Kestrel.Core;
  26. using Microsoft.AspNetCore.Server.Kestrel.Https;
  27. using Microsoft.AspNetCore.StaticFiles;
  28. using Microsoft.Extensions.FileProviders;
  29. using Microsoft.Extensions.Logging;
  30. using System;
  31. using System.Collections.Concurrent;
  32. using System.Collections.Generic;
  33. using System.IO;
  34. using System.Net;
  35. using System.Net.Quic;
  36. using System.Net.Security;
  37. using System.Net.Sockets;
  38. using System.Runtime.ExceptionServices;
  39. using System.Security.Cryptography.X509Certificates;
  40. using System.Threading;
  41. using System.Threading.Tasks;
  42. using TechnitiumLibrary;
  43. using TechnitiumLibrary.Net;
  44. using TechnitiumLibrary.Net.Dns;
  45. using TechnitiumLibrary.Net.Dns.ClientConnection;
  46. using TechnitiumLibrary.Net.Dns.EDnsOptions;
  47. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  48. using TechnitiumLibrary.Net.Proxy;
  49. namespace DnsServerCore.Dns
  50. {
  51. #pragma warning disable CA2252 // This API requires opting into preview features
  52. #pragma warning disable CA1416 // Validate platform compatibility
  53. public enum DnsServerRecursion : byte
  54. {
  55. Deny = 0,
  56. Allow = 1,
  57. AllowOnlyForPrivateNetworks = 2,
  58. UseSpecifiedNetworks = 3
  59. }
  60. public enum DnsServerBlockingType : byte
  61. {
  62. AnyAddress = 0,
  63. NxDomain = 1,
  64. CustomAddress = 2
  65. }
  66. public sealed class DnsServer : IAsyncDisposable, IDisposable, IDnsClient
  67. {
  68. #region enum
  69. enum ServiceState
  70. {
  71. Stopped = 0,
  72. Starting = 1,
  73. Running = 2,
  74. Stopping = 3
  75. }
  76. #endregion
  77. #region variables
  78. internal const int MAX_CNAME_HOPS = 16;
  79. const int SERVE_STALE_WAIT_TIME = 1800;
  80. static readonly IPEndPoint IPENDPOINT_ANY_0 = new IPEndPoint(IPAddress.Any, 0);
  81. static readonly IReadOnlyCollection<DnsARecordData> _aRecords = new DnsARecordData[] { new DnsARecordData(IPAddress.Any) };
  82. static readonly IReadOnlyCollection<DnsAAAARecordData> _aaaaRecords = new DnsAAAARecordData[] { new DnsAAAARecordData(IPAddress.IPv6Any) };
  83. string _serverDomain;
  84. readonly string _configFolder;
  85. readonly string _dohwwwFolder;
  86. IReadOnlyList<IPEndPoint> _localEndPoints;
  87. LogManager _log;
  88. NameServerAddress _thisServer;
  89. readonly List<Socket> _udpListeners = new List<Socket>();
  90. readonly List<Socket> _tcpListeners = new List<Socket>();
  91. readonly List<Socket> _tlsListeners = new List<Socket>();
  92. readonly List<QuicListener> _quicListeners = new List<QuicListener>();
  93. WebApplication _dohWebService;
  94. readonly AuthZoneManager _authZoneManager;
  95. readonly AllowedZoneManager _allowedZoneManager;
  96. readonly BlockedZoneManager _blockedZoneManager;
  97. readonly BlockListZoneManager _blockListZoneManager;
  98. readonly CacheZoneManager _cacheZoneManager;
  99. readonly DnsApplicationManager _dnsApplicationManager;
  100. readonly ResolverDnsCache _dnsCache;
  101. readonly StatsManager _stats;
  102. bool _preferIPv6;
  103. ushort _udpPayloadSize = DnsDatagram.EDNS_DEFAULT_UDP_PAYLOAD_SIZE;
  104. bool _dnssecValidation = true;
  105. bool _eDnsClientSubnet;
  106. byte _eDnsClientSubnetIPv4PrefixLength = 24;
  107. byte _eDnsClientSubnetIPv6PrefixLength = 56;
  108. int _qpmLimitRequests = 0;
  109. int _qpmLimitErrors = 0;
  110. int _qpmLimitSampleMinutes = 5;
  111. int _qpmLimitIPv4PrefixLength = 24;
  112. int _qpmLimitIPv6PrefixLength = 56;
  113. int _clientTimeout = 4000;
  114. int _tcpSendTimeout = 10000;
  115. int _tcpReceiveTimeout = 10000;
  116. int _quicIdleTimeout = 60000;
  117. int _quicMaxInboundStreams = 100;
  118. int _listenBacklog = 100;
  119. bool _enableDnsOverHttp;
  120. bool _enableDnsOverTls;
  121. bool _enableDnsOverHttps;
  122. bool _enableDnsOverQuic;
  123. int _dnsOverHttpPort = 80;
  124. int _dnsOverTlsPort = 853;
  125. int _dnsOverHttpsPort = 443;
  126. int _dnsOverQuicPort = 853;
  127. X509Certificate2 _certificate;
  128. IReadOnlyDictionary<string, TsigKey> _tsigKeys;
  129. DnsServerRecursion _recursion;
  130. IReadOnlyCollection<NetworkAddress> _recursionDeniedNetworks;
  131. IReadOnlyCollection<NetworkAddress> _recursionAllowedNetworks;
  132. bool _randomizeName;
  133. bool _qnameMinimization;
  134. bool _nsRevalidation;
  135. int _resolverRetries = 2;
  136. int _resolverTimeout = 2000;
  137. int _resolverMaxStackCount = 16;
  138. bool _serveStale = true;
  139. int _cachePrefetchEligibility = 2;
  140. int _cachePrefetchTrigger = 9;
  141. int _cachePrefetchSampleIntervalInMinutes = 5;
  142. int _cachePrefetchSampleEligibilityHitsPerHour = 30;
  143. bool _enableBlocking = true;
  144. bool _allowTxtBlockingReport = true;
  145. DnsServerBlockingType _blockingType = DnsServerBlockingType.NxDomain;
  146. IReadOnlyCollection<DnsARecordData> _customBlockingARecords = Array.Empty<DnsARecordData>();
  147. IReadOnlyCollection<DnsAAAARecordData> _customBlockingAAAARecords = Array.Empty<DnsAAAARecordData>();
  148. NetProxy _proxy;
  149. IReadOnlyList<NameServerAddress> _forwarders;
  150. int _forwarderRetries = 3;
  151. int _forwarderTimeout = 2000;
  152. int _forwarderConcurrency = 2;
  153. LogManager _queryLog;
  154. Timer _cachePrefetchSamplingTimer;
  155. readonly object _cachePrefetchSamplingTimerLock = new object();
  156. const int CACHE_PREFETCH_SAMPLING_TIMER_INITIAL_INTEVAL = 5000;
  157. Timer _cachePrefetchRefreshTimer;
  158. readonly object _cachePrefetchRefreshTimerLock = new object();
  159. const int CACHE_PREFETCH_REFRESH_TIMER_INITIAL_INTEVAL = 10000;
  160. DateTime _cachePrefetchSamplingTimerTriggersOn;
  161. IList<CacheRefreshSample> _cacheRefreshSampleList;
  162. Timer _cacheMaintenanceTimer;
  163. readonly object _cacheMaintenanceTimerLock = new object();
  164. const int CACHE_MAINTENANCE_TIMER_INITIAL_INTEVAL = 5 * 60 * 1000;
  165. const int CACHE_MAINTENANCE_TIMER_PERIODIC_INTERVAL = 5 * 60 * 1000;
  166. Timer _qpmLimitSamplingTimer;
  167. readonly object _qpmLimitSamplingTimerLock = new object();
  168. const int QPM_LIMIT_SAMPLING_TIMER_INTERVAL = 10000;
  169. IReadOnlyDictionary<IPAddress, long> _qpmLimitClientSubnetStats;
  170. IReadOnlyDictionary<IPAddress, long> _qpmLimitErrorClientSubnetStats;
  171. readonly IndependentTaskScheduler _queryTaskScheduler = new IndependentTaskScheduler();
  172. readonly IndependentTaskScheduler _resolverTaskScheduler = new IndependentTaskScheduler(ThreadPriority.AboveNormal);
  173. readonly ConcurrentDictionary<string, Task<RecursiveResolveResponse>> _resolverTasks = new ConcurrentDictionary<string, Task<RecursiveResolveResponse>>();
  174. volatile ServiceState _state = ServiceState.Stopped;
  175. #endregion
  176. #region constructor
  177. static DnsServer()
  178. {
  179. //set min threads since the default value is too small
  180. {
  181. ThreadPool.GetMinThreads(out int minWorker, out int minIOC);
  182. int minThreads = Environment.ProcessorCount * 16;
  183. if (minWorker < minThreads)
  184. minWorker = minThreads;
  185. if (minIOC < minThreads)
  186. minIOC = minThreads;
  187. ThreadPool.SetMinThreads(minWorker, minIOC);
  188. }
  189. }
  190. public DnsServer(string serverDomain, string configFolder, string dohwwwFolder, LogManager log = null)
  191. : this(serverDomain, configFolder, dohwwwFolder, new IPEndPoint[] { new IPEndPoint(IPAddress.Any, 53), new IPEndPoint(IPAddress.IPv6Any, 53) }, log)
  192. { }
  193. public DnsServer(string serverDomain, string configFolder, string dohwwwFolder, IPEndPoint localEndPoint, LogManager log = null)
  194. : this(serverDomain, configFolder, dohwwwFolder, new IPEndPoint[] { localEndPoint }, log)
  195. { }
  196. public DnsServer(string serverDomain, string configFolder, string dohwwwFolder, IReadOnlyList<IPEndPoint> localEndPoints, LogManager log = null)
  197. {
  198. _serverDomain = serverDomain;
  199. _configFolder = configFolder;
  200. _dohwwwFolder = dohwwwFolder;
  201. _localEndPoints = localEndPoints;
  202. _log = log;
  203. _authZoneManager = new AuthZoneManager(this);
  204. _allowedZoneManager = new AllowedZoneManager(this);
  205. _blockedZoneManager = new BlockedZoneManager(this);
  206. _blockListZoneManager = new BlockListZoneManager(this);
  207. _cacheZoneManager = new CacheZoneManager(this);
  208. _dnsApplicationManager = new DnsApplicationManager(this);
  209. _dnsCache = new ResolverDnsCache(_dnsApplicationManager, _authZoneManager, _cacheZoneManager, _log, false);
  210. //init stats
  211. _stats = new StatsManager(this);
  212. }
  213. #endregion
  214. #region IDisposable
  215. bool _disposed;
  216. public async ValueTask DisposeAsync()
  217. {
  218. if (_disposed)
  219. return;
  220. await StopAsync();
  221. _authZoneManager?.Dispose();
  222. _dnsApplicationManager?.Dispose();
  223. _stats?.Dispose();
  224. _disposed = true;
  225. }
  226. public void Dispose()
  227. {
  228. DisposeAsync().Sync();
  229. }
  230. #endregion
  231. #region private
  232. private async Task ReadUdpRequestAsync(Socket udpListener)
  233. {
  234. byte[] recvBuffer = new byte[DnsDatagram.EDNS_MAX_UDP_PAYLOAD_SIZE];
  235. using MemoryStream recvBufferStream = new MemoryStream(recvBuffer);
  236. try
  237. {
  238. EndPoint epAny;
  239. switch (udpListener.AddressFamily)
  240. {
  241. case AddressFamily.InterNetwork:
  242. epAny = new IPEndPoint(IPAddress.Any, 0);
  243. break;
  244. case AddressFamily.InterNetworkV6:
  245. epAny = new IPEndPoint(IPAddress.IPv6Any, 0);
  246. break;
  247. default:
  248. throw new NotSupportedException("AddressFamily not supported.");
  249. }
  250. SocketReceiveFromResult result;
  251. while (true)
  252. {
  253. recvBufferStream.SetLength(DnsDatagram.EDNS_MAX_UDP_PAYLOAD_SIZE); //resetting length before using buffer
  254. try
  255. {
  256. result = await udpListener.ReceiveFromAsync(recvBuffer, SocketFlags.None, epAny);
  257. }
  258. catch (SocketException ex)
  259. {
  260. switch (ex.SocketErrorCode)
  261. {
  262. case SocketError.ConnectionReset:
  263. case SocketError.HostUnreachable:
  264. case SocketError.MessageSize:
  265. case SocketError.NetworkReset:
  266. result = default;
  267. break;
  268. default:
  269. throw;
  270. }
  271. }
  272. if (result.ReceivedBytes > 0)
  273. {
  274. if (result.RemoteEndPoint is not IPEndPoint remoteEP)
  275. continue;
  276. if (IsQpmLimitCrossed(remoteEP.Address))
  277. continue;
  278. try
  279. {
  280. recvBufferStream.Position = 0;
  281. recvBufferStream.SetLength(result.ReceivedBytes);
  282. DnsDatagram request = DnsDatagram.ReadFrom(recvBufferStream);
  283. _ = ProcessUdpRequestAsync(udpListener, remoteEP, request);
  284. }
  285. catch (EndOfStreamException)
  286. {
  287. //ignore incomplete udp datagrams
  288. }
  289. catch (Exception ex)
  290. {
  291. _log?.Write(remoteEP, DnsTransportProtocol.Udp, ex);
  292. }
  293. }
  294. }
  295. }
  296. catch (ObjectDisposedException)
  297. {
  298. //server stopping
  299. }
  300. catch (SocketException ex)
  301. {
  302. switch (ex.SocketErrorCode)
  303. {
  304. case SocketError.OperationAborted:
  305. case SocketError.Interrupted:
  306. break; //server stopping
  307. default:
  308. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  309. return; //server stopping
  310. _log?.Write(ex);
  311. break;
  312. }
  313. }
  314. catch (Exception ex)
  315. {
  316. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  317. return; //server stopping
  318. _log?.Write(ex);
  319. }
  320. }
  321. private async Task ProcessUdpRequestAsync(Socket udpListener, IPEndPoint remoteEP, DnsDatagram request)
  322. {
  323. try
  324. {
  325. DnsDatagram response = await PreProcessQueryAsync(request, remoteEP, DnsTransportProtocol.Udp, IsRecursionAllowed(remoteEP.Address));
  326. if (response is null)
  327. return; //drop request
  328. //send response
  329. byte[] sendBuffer;
  330. if (request.EDNS is null)
  331. sendBuffer = new byte[512];
  332. else if (request.EDNS.UdpPayloadSize > _udpPayloadSize)
  333. sendBuffer = new byte[_udpPayloadSize];
  334. else
  335. sendBuffer = new byte[request.EDNS.UdpPayloadSize];
  336. using (MemoryStream sendBufferStream = new MemoryStream(sendBuffer))
  337. {
  338. try
  339. {
  340. response.WriteTo(sendBufferStream);
  341. }
  342. catch (NotSupportedException)
  343. {
  344. if (response.IsSigned)
  345. {
  346. //rfc8945 section 5.3
  347. response = new DnsDatagram(response.Identifier, true, response.OPCODE, response.AuthoritativeAnswer, true, response.RecursionDesired, response.RecursionAvailable, response.AuthenticData, response.CheckingDisabled, DnsResponseCode.NoError, response.Question, null, null, new DnsResourceRecord[] { response.Additional[response.Additional.Count - 1] }, request.EDNS is null ? ushort.MinValue : _udpPayloadSize) { Tag = DnsServerResponseType.Authoritative };
  348. }
  349. else
  350. {
  351. switch (response.Question[0].Type)
  352. {
  353. case DnsResourceRecordType.MX:
  354. //removing glue records and trying again since some mail servers fail to fallback to TCP on truncation
  355. response = response.CloneWithoutGlueRecords();
  356. sendBufferStream.Position = 0;
  357. try
  358. {
  359. response.WriteTo(sendBufferStream);
  360. }
  361. catch (NotSupportedException)
  362. {
  363. //send TC since response is still big even after removing glue records
  364. response = new DnsDatagram(response.Identifier, true, response.OPCODE, response.AuthoritativeAnswer, true, response.RecursionDesired, response.RecursionAvailable, response.AuthenticData, response.CheckingDisabled, response.RCODE, response.Question, null, null, null, request.EDNS is null ? ushort.MinValue : _udpPayloadSize) { Tag = DnsServerResponseType.Authoritative };
  365. }
  366. break;
  367. case DnsResourceRecordType.IXFR:
  368. response = new DnsDatagram(response.Identifier, true, response.OPCODE, response.AuthoritativeAnswer, false, response.RecursionDesired, response.RecursionAvailable, response.AuthenticData, response.CheckingDisabled, response.RCODE, response.Question, new DnsResourceRecord[] { response.Answer[0] }, null, null, request.EDNS is null ? ushort.MinValue : _udpPayloadSize) { Tag = DnsServerResponseType.Authoritative }; //truncate response
  369. break;
  370. default:
  371. response = new DnsDatagram(response.Identifier, true, response.OPCODE, response.AuthoritativeAnswer, true, response.RecursionDesired, response.RecursionAvailable, response.AuthenticData, response.CheckingDisabled, response.RCODE, response.Question, null, null, null, request.EDNS is null ? ushort.MinValue : _udpPayloadSize) { Tag = DnsServerResponseType.Authoritative };
  372. break;
  373. }
  374. }
  375. sendBufferStream.Position = 0;
  376. response.WriteTo(sendBufferStream);
  377. }
  378. //send dns datagram async
  379. await udpListener.SendToAsync(new ArraySegment<byte>(sendBuffer, 0, (int)sendBufferStream.Position), SocketFlags.None, remoteEP);
  380. }
  381. _queryLog?.Write(remoteEP, DnsTransportProtocol.Udp, request, response);
  382. _stats.QueueUpdate(request, remoteEP, DnsTransportProtocol.Udp, response);
  383. }
  384. catch (Exception ex)
  385. {
  386. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  387. return; //server stopping
  388. _queryLog?.Write(remoteEP, DnsTransportProtocol.Udp, request, null);
  389. _log?.Write(remoteEP, DnsTransportProtocol.Udp, ex);
  390. }
  391. }
  392. private async Task AcceptConnectionAsync(Socket tcpListener, DnsTransportProtocol protocol)
  393. {
  394. IPEndPoint localEP = tcpListener.LocalEndPoint as IPEndPoint;
  395. try
  396. {
  397. tcpListener.SendTimeout = _tcpSendTimeout;
  398. tcpListener.ReceiveTimeout = _tcpReceiveTimeout;
  399. tcpListener.NoDelay = true;
  400. while (true)
  401. {
  402. Socket socket = await tcpListener.AcceptAsync();
  403. _ = ProcessConnectionAsync(socket, protocol);
  404. }
  405. }
  406. catch (SocketException ex)
  407. {
  408. if (ex.SocketErrorCode == SocketError.OperationAborted)
  409. return; //server stopping
  410. _log?.Write(localEP, protocol, ex);
  411. }
  412. catch (ObjectDisposedException)
  413. {
  414. //server stopped
  415. }
  416. catch (Exception ex)
  417. {
  418. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  419. return; //server stopping
  420. _log?.Write(localEP, protocol, ex);
  421. }
  422. }
  423. private async Task ProcessConnectionAsync(Socket socket, DnsTransportProtocol protocol)
  424. {
  425. IPEndPoint remoteEP = null;
  426. try
  427. {
  428. remoteEP = socket.RemoteEndPoint as IPEndPoint;
  429. switch (protocol)
  430. {
  431. case DnsTransportProtocol.Tcp:
  432. await ReadStreamRequestAsync(new NetworkStream(socket), remoteEP, protocol);
  433. break;
  434. case DnsTransportProtocol.Tls:
  435. SslStream tlsStream = new SslStream(new NetworkStream(socket));
  436. await tlsStream.AuthenticateAsServerAsync(_certificate).WithTimeout(_tcpReceiveTimeout);
  437. await ReadStreamRequestAsync(tlsStream, remoteEP, protocol);
  438. break;
  439. default:
  440. throw new InvalidOperationException();
  441. }
  442. }
  443. catch (TimeoutException)
  444. {
  445. //ignore timeout exception on TLS auth
  446. }
  447. catch (IOException)
  448. {
  449. //ignore IO exceptions
  450. }
  451. catch (Exception ex)
  452. {
  453. _log?.Write(remoteEP, protocol, ex);
  454. }
  455. finally
  456. {
  457. socket.Dispose();
  458. }
  459. }
  460. private async Task ReadStreamRequestAsync(Stream stream, IPEndPoint remoteEP, DnsTransportProtocol protocol)
  461. {
  462. try
  463. {
  464. using MemoryStream readBuffer = new MemoryStream(64);
  465. using MemoryStream writeBuffer = new MemoryStream(2048);
  466. using SemaphoreSlim writeSemaphore = new SemaphoreSlim(1, 1);
  467. while (true)
  468. {
  469. if (IsQpmLimitCrossed(remoteEP.Address))
  470. break;
  471. DnsDatagram request;
  472. //read dns datagram with timeout
  473. using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource())
  474. {
  475. Task<DnsDatagram> task = DnsDatagram.ReadFromTcpAsync(stream, readBuffer, cancellationTokenSource.Token);
  476. if (await Task.WhenAny(task, Task.Delay(_tcpReceiveTimeout, cancellationTokenSource.Token)) != task)
  477. {
  478. //read timed out
  479. await stream.DisposeAsync();
  480. return;
  481. }
  482. cancellationTokenSource.Cancel(); //cancel delay task
  483. request = await task;
  484. }
  485. //process request async
  486. _ = ProcessStreamRequestAsync(stream, writeBuffer, writeSemaphore, remoteEP, request, protocol);
  487. }
  488. }
  489. catch (ObjectDisposedException)
  490. {
  491. //ignore
  492. }
  493. catch (IOException)
  494. {
  495. //ignore IO exceptions
  496. }
  497. catch (Exception ex)
  498. {
  499. _log?.Write(remoteEP, protocol, ex);
  500. }
  501. }
  502. private async Task ProcessStreamRequestAsync(Stream stream, MemoryStream writeBuffer, SemaphoreSlim writeSemaphore, IPEndPoint remoteEP, DnsDatagram request, DnsTransportProtocol protocol)
  503. {
  504. try
  505. {
  506. DnsDatagram response = await PreProcessQueryAsync(request, remoteEP, protocol, IsRecursionAllowed(remoteEP.Address));
  507. if (response is null)
  508. {
  509. await stream.DisposeAsync();
  510. return; //drop request
  511. }
  512. //send response
  513. await writeSemaphore.WaitAsync();
  514. try
  515. {
  516. //send dns datagram
  517. await response.WriteToTcpAsync(stream, writeBuffer);
  518. await stream.FlushAsync();
  519. }
  520. finally
  521. {
  522. writeSemaphore.Release();
  523. }
  524. _queryLog?.Write(remoteEP, protocol, request, response);
  525. _stats.QueueUpdate(request, remoteEP, protocol, response);
  526. }
  527. catch (ObjectDisposedException)
  528. {
  529. //ignore
  530. }
  531. catch (IOException)
  532. {
  533. //ignore IO exceptions
  534. }
  535. catch (Exception ex)
  536. {
  537. if (request is not null)
  538. _queryLog.Write(remoteEP, protocol, request, null);
  539. _log?.Write(remoteEP, protocol, ex);
  540. }
  541. }
  542. private async Task AcceptQuicConnectionAsync(QuicListener quicListener)
  543. {
  544. try
  545. {
  546. while (true)
  547. {
  548. QuicConnection quicConnection = await quicListener.AcceptConnectionAsync();
  549. _ = ProcessQuicConnectionAsync(quicConnection);
  550. }
  551. }
  552. catch (ObjectDisposedException)
  553. {
  554. //server stopped
  555. }
  556. catch (Exception ex)
  557. {
  558. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  559. return; //server stopping
  560. _log?.Write(quicListener.LocalEndPoint, DnsTransportProtocol.Quic, ex);
  561. }
  562. }
  563. private async Task ProcessQuicConnectionAsync(QuicConnection quicConnection)
  564. {
  565. try
  566. {
  567. while (true)
  568. {
  569. if (IsQpmLimitCrossed(quicConnection.RemoteEndPoint.Address))
  570. break;
  571. QuicStream quicStream = await quicConnection.AcceptInboundStreamAsync();
  572. _ = ProcessQuicStreamRequestAsync(quicStream, quicConnection.RemoteEndPoint);
  573. }
  574. }
  575. catch (QuicException ex)
  576. {
  577. switch (ex.QuicError)
  578. {
  579. case QuicError.ConnectionIdle:
  580. case QuicError.ConnectionAborted:
  581. case QuicError.ConnectionTimeout:
  582. break;
  583. default:
  584. _log?.Write(quicConnection.RemoteEndPoint, DnsTransportProtocol.Quic, ex);
  585. break;
  586. }
  587. }
  588. catch (Exception ex)
  589. {
  590. _log?.Write(quicConnection.RemoteEndPoint, DnsTransportProtocol.Quic, ex);
  591. }
  592. finally
  593. {
  594. await quicConnection.DisposeAsync();
  595. }
  596. }
  597. private async Task ProcessQuicStreamRequestAsync(QuicStream quicStream, IPEndPoint remoteEP)
  598. {
  599. MemoryStream sharedBuffer = new MemoryStream(512);
  600. DnsDatagram request = null;
  601. try
  602. {
  603. //read dns datagram with timeout
  604. using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource())
  605. {
  606. Task<DnsDatagram> task = DnsDatagram.ReadFromTcpAsync(quicStream, sharedBuffer, cancellationTokenSource.Token);
  607. if (await Task.WhenAny(task, Task.Delay(_tcpReceiveTimeout, cancellationTokenSource.Token)) != task)
  608. {
  609. //read timed out
  610. quicStream.Abort(QuicAbortDirection.Both, (long)DnsOverQuicErrorCodes.DOQ_UNSPECIFIED_ERROR);
  611. return;
  612. }
  613. cancellationTokenSource.Cancel(); //cancel delay task
  614. request = await task;
  615. }
  616. //process request async
  617. DnsDatagram response = await PreProcessQueryAsync(request, remoteEP, DnsTransportProtocol.Quic, IsRecursionAllowed(remoteEP.Address));
  618. if (response is null)
  619. return; //drop request
  620. //send response
  621. await response.WriteToTcpAsync(quicStream, sharedBuffer);
  622. _queryLog?.Write(remoteEP, DnsTransportProtocol.Quic, request, response);
  623. _stats.QueueUpdate(request, remoteEP, DnsTransportProtocol.Quic, response);
  624. }
  625. catch (IOException)
  626. {
  627. //ignore QuicException / IOException
  628. }
  629. catch (Exception ex)
  630. {
  631. if (request is not null)
  632. _queryLog.Write(remoteEP, DnsTransportProtocol.Quic, request, null);
  633. _log?.Write(remoteEP, DnsTransportProtocol.Quic, ex);
  634. }
  635. finally
  636. {
  637. await sharedBuffer.DisposeAsync();
  638. await quicStream.DisposeAsync();
  639. }
  640. }
  641. private async Task ProcessDoHRequestAsync(HttpContext context)
  642. {
  643. IPEndPoint remoteEP = context.GetRemoteEndPoint();
  644. DnsDatagram dnsRequest = null;
  645. try
  646. {
  647. HttpRequest request = context.Request;
  648. HttpResponse response = context.Response;
  649. if (IsQpmLimitCrossed(remoteEP.Address))
  650. {
  651. response.StatusCode = 429;
  652. await response.WriteAsync("Too Many Requests");
  653. return;
  654. }
  655. if (!request.IsHttps)
  656. {
  657. //get the actual connection remote EP
  658. IPEndPoint connectionEp = context.GetRemoteEndPoint(true);
  659. if (!NetUtilities.IsPrivateIP(connectionEp.Address))
  660. {
  661. //intentionally blocking public IP addresses from using DNS-over-HTTP (without TLS)
  662. //this feature is intended to be used with an SSL terminated reverse proxy like nginx on private network
  663. response.StatusCode = 403;
  664. await response.WriteAsync("DNS-over-HTTPS (DoH) queries are supported only on HTTPS.");
  665. return;
  666. }
  667. }
  668. switch (request.Method)
  669. {
  670. case "GET":
  671. bool acceptsDoH = false;
  672. string requestAccept = request.Headers["Accept"];
  673. if (!string.IsNullOrEmpty(requestAccept))
  674. {
  675. foreach (string mediaType in requestAccept.Split(','))
  676. {
  677. if (mediaType.Equals("application/dns-message", StringComparison.OrdinalIgnoreCase))
  678. {
  679. acceptsDoH = true;
  680. break;
  681. }
  682. }
  683. }
  684. if (!acceptsDoH)
  685. {
  686. response.Redirect((request.IsHttps ? "https://" : "http://") + request.Headers["Host"]);
  687. return;
  688. }
  689. string dnsRequestBase64Url = request.Query["dns"];
  690. if (string.IsNullOrEmpty(dnsRequestBase64Url))
  691. {
  692. response.StatusCode = 400;
  693. await response.WriteAsync("Bad Request");
  694. return;
  695. }
  696. //convert from base64url to base64
  697. dnsRequestBase64Url = dnsRequestBase64Url.Replace('-', '+');
  698. dnsRequestBase64Url = dnsRequestBase64Url.Replace('_', '/');
  699. //add padding
  700. int x = dnsRequestBase64Url.Length % 4;
  701. if (x > 0)
  702. dnsRequestBase64Url = dnsRequestBase64Url.PadRight(dnsRequestBase64Url.Length - x + 4, '=');
  703. using (MemoryStream mS = new MemoryStream(Convert.FromBase64String(dnsRequestBase64Url)))
  704. {
  705. dnsRequest = DnsDatagram.ReadFrom(mS);
  706. }
  707. break;
  708. case "POST":
  709. if (!string.Equals(request.Headers["Content-Type"], "application/dns-message", StringComparison.OrdinalIgnoreCase))
  710. {
  711. response.StatusCode = 415;
  712. await response.WriteAsync("Unsupported Media Type");
  713. return;
  714. }
  715. using (MemoryStream mS = new MemoryStream(32))
  716. {
  717. await request.Body.CopyToAsync(mS, 32);
  718. mS.Position = 0;
  719. dnsRequest = DnsDatagram.ReadFrom(mS);
  720. }
  721. break;
  722. default:
  723. throw new InvalidOperationException();
  724. }
  725. DnsDatagram dnsResponse = await PreProcessQueryAsync(dnsRequest, remoteEP, DnsTransportProtocol.Https, IsRecursionAllowed(remoteEP.Address));
  726. if (dnsResponse is null)
  727. {
  728. //drop request
  729. context.Connection.RequestClose();
  730. return;
  731. }
  732. using (MemoryStream mS = new MemoryStream(512))
  733. {
  734. dnsResponse.WriteTo(mS);
  735. mS.Position = 0;
  736. response.ContentType = "application/dns-message";
  737. response.ContentLength = mS.Length;
  738. using (Stream s = response.Body)
  739. {
  740. await mS.CopyToAsync(s, 512);
  741. }
  742. }
  743. _queryLog?.Write(remoteEP, DnsTransportProtocol.Https, dnsRequest, dnsResponse);
  744. _stats.QueueUpdate(dnsRequest, remoteEP, DnsTransportProtocol.Https, dnsResponse);
  745. }
  746. catch (Exception ex)
  747. {
  748. if (dnsRequest is not null)
  749. _queryLog?.Write(remoteEP, DnsTransportProtocol.Https, dnsRequest, null);
  750. _log?.Write(remoteEP, DnsTransportProtocol.Https, ex);
  751. }
  752. }
  753. private bool IsRecursionAllowed(IPAddress remoteIP)
  754. {
  755. switch (_recursion)
  756. {
  757. case DnsServerRecursion.Allow:
  758. return true;
  759. case DnsServerRecursion.AllowOnlyForPrivateNetworks:
  760. switch (remoteIP.AddressFamily)
  761. {
  762. case AddressFamily.InterNetwork:
  763. case AddressFamily.InterNetworkV6:
  764. return NetUtilities.IsPrivateIP(remoteIP);
  765. default:
  766. return false;
  767. }
  768. case DnsServerRecursion.UseSpecifiedNetworks:
  769. if (_recursionDeniedNetworks is not null)
  770. {
  771. foreach (NetworkAddress deniedNetworkAddress in _recursionDeniedNetworks)
  772. {
  773. if (deniedNetworkAddress.Contains(remoteIP))
  774. return false;
  775. }
  776. }
  777. if (_recursionAllowedNetworks is not null)
  778. {
  779. foreach (NetworkAddress allowedNetworkAddress in _recursionAllowedNetworks)
  780. {
  781. if (allowedNetworkAddress.Contains(remoteIP))
  782. return true;
  783. }
  784. }
  785. if (IPAddress.IsLoopback(remoteIP))
  786. return true;
  787. return false;
  788. default:
  789. return false;
  790. }
  791. }
  792. private async Task<DnsDatagram> PreProcessQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed)
  793. {
  794. foreach (IDnsRequestController requestController in _dnsApplicationManager.DnsRequestControllers)
  795. {
  796. try
  797. {
  798. DnsRequestControllerAction action = await requestController.GetRequestActionAsync(request, remoteEP, protocol);
  799. switch (action)
  800. {
  801. case DnsRequestControllerAction.DropSilently:
  802. return null; //drop request
  803. case DnsRequestControllerAction.DropWithRefused:
  804. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.Refused, request.Question, null, null, null, request.EDNS is null ? ushort.MinValue : _udpPayloadSize, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None) { Tag = DnsServerResponseType.Authoritative }; //drop request with refused
  805. }
  806. }
  807. catch (Exception ex)
  808. {
  809. _log?.Write(remoteEP, protocol, ex);
  810. }
  811. }
  812. if (request.ParsingException is not null)
  813. {
  814. //format error
  815. if (request.ParsingException is not IOException)
  816. _log?.Write(remoteEP, protocol, request.ParsingException);
  817. //format error response
  818. return new DnsDatagram(request.Identifier, true, request.OPCODE, false, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.FormatError, request.Question, null, null, null, request.EDNS is null ? ushort.MinValue : _udpPayloadSize, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None) { Tag = DnsServerResponseType.Authoritative };
  819. }
  820. if (request.IsSigned)
  821. {
  822. if (!request.VerifySignedRequest(_tsigKeys, out DnsDatagram unsignedRequest, out DnsDatagram errorResponse))
  823. {
  824. _log?.Write(remoteEP, protocol, "DNS Server received a request that failed TSIG signature verification (RCODE: " + errorResponse.RCODE + "; TSIG Error: " + errorResponse.TsigError + ")");
  825. errorResponse.Tag = DnsServerResponseType.Authoritative;
  826. return errorResponse;
  827. }
  828. DnsDatagram unsignedResponse = await PostProcessQueryAsync(request, remoteEP, protocol, await ProcessQueryAsync(unsignedRequest, remoteEP, protocol, isRecursionAllowed, false, request.TsigKeyName));
  829. return unsignedResponse.SignResponse(request, _tsigKeys);
  830. }
  831. if (request.EDNS is not null)
  832. {
  833. if (request.EDNS.Version != 0)
  834. return new DnsDatagram(request.Identifier, true, request.OPCODE, false, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.BADVERS, request.Question, null, null, null, _udpPayloadSize, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None) { Tag = DnsServerResponseType.Authoritative };
  835. }
  836. return await PostProcessQueryAsync(request, remoteEP, protocol, await ProcessQueryAsync(request, remoteEP, protocol, isRecursionAllowed, false, null));
  837. }
  838. private async Task<DnsDatagram> PostProcessQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, DnsDatagram response)
  839. {
  840. foreach (IDnsPostProcessor postProcessor in _dnsApplicationManager.DnsPostProcessors)
  841. {
  842. try
  843. {
  844. response = await postProcessor.PostProcessAsync(request, remoteEP, protocol, response);
  845. }
  846. catch (Exception ex)
  847. {
  848. _log?.Write(remoteEP, protocol, ex);
  849. }
  850. }
  851. if (request.EDNS is null)
  852. {
  853. if (response.EDNS is not null)
  854. response = response.CloneWithoutEDns();
  855. return response;
  856. }
  857. if (response.EDNS is not null)
  858. return response;
  859. IReadOnlyList<EDnsOption> options = null;
  860. EDnsClientSubnetOptionData requestECS = request.GetEDnsClientSubnetOption(true);
  861. if ((requestECS is not null) && (request.Question.Count == 1) && CacheZone.IsTypeSupportedForEDnsClientSubnet(request.Question[0].Type))
  862. options = EDnsClientSubnetOptionData.GetEDnsClientSubnetOption(requestECS.SourcePrefixLength, 0, requestECS.Address);
  863. if (response.Additional.Count == 0)
  864. return response.Clone(null, null, new DnsResourceRecord[] { DnsDatagramEdns.GetOPTFor(_udpPayloadSize, response.RCODE, 0, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, options) });
  865. if (response.IsSigned)
  866. return response;
  867. DnsResourceRecord[] newAdditional = new DnsResourceRecord[response.Additional.Count + 1];
  868. for (int i = 0; i < response.Additional.Count; i++)
  869. newAdditional[i] = response.Additional[i];
  870. newAdditional[response.Additional.Count] = DnsDatagramEdns.GetOPTFor(_udpPayloadSize, response.RCODE, 0, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, options);
  871. return response.Clone(null, null, newAdditional);
  872. }
  873. private async Task<DnsDatagram> ProcessQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, bool skipDnsAppAuthoritativeRequestHandlers, string tsigAuthenticatedKeyName)
  874. {
  875. if (request.IsResponse)
  876. return null; //drop response datagram to avoid loops in rare scenarios
  877. switch (request.OPCODE)
  878. {
  879. case DnsOpcode.StandardQuery:
  880. if (request.Question.Count != 1)
  881. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  882. if (request.Question[0].Class != DnsClass.IN)
  883. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  884. try
  885. {
  886. DnsQuestionRecord question = request.Question[0];
  887. switch (question.Type)
  888. {
  889. case DnsResourceRecordType.AXFR:
  890. if (protocol == DnsTransportProtocol.Udp)
  891. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  892. return await ProcessZoneTransferQueryAsync(request, remoteEP, protocol, tsigAuthenticatedKeyName);
  893. case DnsResourceRecordType.IXFR:
  894. return await ProcessZoneTransferQueryAsync(request, remoteEP, protocol, tsigAuthenticatedKeyName);
  895. case DnsResourceRecordType.FWD:
  896. case DnsResourceRecordType.APP:
  897. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  898. }
  899. //query authoritative zone
  900. DnsDatagram response = await ProcessAuthoritativeQueryAsync(request, remoteEP, protocol, isRecursionAllowed, skipDnsAppAuthoritativeRequestHandlers);
  901. if (response is not null)
  902. {
  903. if ((question.Type == DnsResourceRecordType.ANY) && (protocol == DnsTransportProtocol.Udp)) //force TCP for ANY request
  904. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, true, true, request.RecursionDesired, isRecursionAllowed, false, false, response.RCODE, request.Question) { Tag = DnsServerResponseType.Authoritative };
  905. return response;
  906. }
  907. if (!request.RecursionDesired || !isRecursionAllowed)
  908. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  909. //do recursive query
  910. if ((question.Type == DnsResourceRecordType.ANY) && (protocol == DnsTransportProtocol.Udp)) //force TCP for ANY request
  911. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, true, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.NoError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  912. return await ProcessRecursiveQueryAsync(request, remoteEP, protocol, null, _dnssecValidation, false, skipDnsAppAuthoritativeRequestHandlers);
  913. }
  914. catch (InvalidDomainNameException)
  915. {
  916. //format error response
  917. return new DnsDatagram(request.Identifier, true, request.OPCODE, false, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  918. }
  919. catch (Exception ex)
  920. {
  921. _log?.Write(remoteEP, protocol, ex);
  922. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.ServerFailure, request.Question) { Tag = DnsServerResponseType.Authoritative };
  923. }
  924. case DnsOpcode.Notify:
  925. return await ProcessNotifyQueryAsync(request, remoteEP, protocol);
  926. case DnsOpcode.Update:
  927. return await ProcessUpdateQueryAsync(request, remoteEP, protocol, tsigAuthenticatedKeyName);
  928. default:
  929. return new DnsDatagram(request.Identifier, true, request.OPCODE, false, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.NotImplemented, request.Question) { Tag = DnsServerResponseType.Authoritative };
  930. }
  931. }
  932. private async Task<DnsDatagram> ProcessNotifyQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol)
  933. {
  934. AuthZoneInfo authZoneInfo = _authZoneManager.GetAuthZoneInfo(request.Question[0].Name);
  935. if ((authZoneInfo is null) || (authZoneInfo.Type != AuthZoneType.Secondary) || authZoneInfo.Disabled)
  936. return new DnsDatagram(request.Identifier, true, DnsOpcode.Notify, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  937. IPAddress remoteAddress = remoteEP.Address;
  938. bool remoteVerified = false;
  939. IReadOnlyList<NameServerAddress> primaryNameServers = await authZoneInfo.GetPrimaryNameServerAddressesAsync(this);
  940. foreach (NameServerAddress primaryNameServer in primaryNameServers)
  941. {
  942. if (primaryNameServer.IPEndPoint.Address.Equals(remoteAddress))
  943. {
  944. remoteVerified = true;
  945. break;
  946. }
  947. }
  948. if (!remoteVerified)
  949. {
  950. _log?.Write(remoteEP, protocol, "DNS Server refused a NOTIFY request since the request IP address was not recognized by the secondary zone: " + (authZoneInfo.Name == "" ? "<root>" : authZoneInfo.Name));
  951. return new DnsDatagram(request.Identifier, true, DnsOpcode.Notify, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  952. }
  953. _log?.Write(remoteEP, protocol, "DNS Server received a NOTIFY request for secondary zone: " + (authZoneInfo.Name == "" ? "<root>" : authZoneInfo.Name));
  954. if ((request.Answer.Count > 0) && (request.Answer[0].Type == DnsResourceRecordType.SOA))
  955. {
  956. IReadOnlyList<DnsResourceRecord> localSoaRecords = authZoneInfo.GetApexRecords(DnsResourceRecordType.SOA);
  957. if (!DnsSOARecordData.IsZoneUpdateAvailable((localSoaRecords[0].RDATA as DnsSOARecordData).Serial, (request.Answer[0].RDATA as DnsSOARecordData).Serial))
  958. {
  959. //no update was available
  960. return new DnsDatagram(request.Identifier, true, DnsOpcode.Notify, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NoError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  961. }
  962. }
  963. authZoneInfo.TriggerRefresh();
  964. return new DnsDatagram(request.Identifier, true, DnsOpcode.Notify, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NoError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  965. }
  966. private async Task<DnsDatagram> ProcessUpdateQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, string tsigAuthenticatedKeyName)
  967. {
  968. if ((request.Question.Count != 1) || (request.Question[0].Type != DnsResourceRecordType.SOA))
  969. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  970. if (request.Question[0].Class != DnsClass.IN)
  971. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NotAuth, request.Question) { Tag = DnsServerResponseType.Authoritative };
  972. AuthZoneInfo authZoneInfo = _authZoneManager.GetAuthZoneInfo(request.Question[0].Name);
  973. if ((authZoneInfo is null) || authZoneInfo.Disabled)
  974. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NotAuth, request.Question) { Tag = DnsServerResponseType.Authoritative };
  975. _log?.Write(remoteEP, protocol, "DNS Server received a zone UPDATE request for zone: " + (authZoneInfo.Name == "" ? "<root>" : authZoneInfo.Name));
  976. async Task<bool> IsZoneNameServerAllowedAsync()
  977. {
  978. IPAddress remoteAddress = remoteEP.Address;
  979. IReadOnlyList<NameServerAddress> secondaryNameServers = await authZoneInfo.GetSecondaryNameServerAddressesAsync(this);
  980. foreach (NameServerAddress secondaryNameServer in secondaryNameServers)
  981. {
  982. if (secondaryNameServer.IPEndPoint.Address.Equals(remoteAddress))
  983. return true;
  984. }
  985. return false;
  986. }
  987. bool IsSpecifiedIpAddressAllowed()
  988. {
  989. IPAddress remoteAddress = remoteEP.Address;
  990. IReadOnlyCollection<IPAddress> specifiedIpAddresses = authZoneInfo.UpdateIpAddresses;
  991. if (specifiedIpAddresses is not null)
  992. {
  993. foreach (IPAddress specifiedIpAddress in specifiedIpAddresses)
  994. {
  995. if (specifiedIpAddress.Equals(remoteAddress))
  996. return true;
  997. }
  998. }
  999. return false;
  1000. }
  1001. async Task<bool> IsUpdatePermittedAsync()
  1002. {
  1003. bool isUpdateAllowed;
  1004. switch (authZoneInfo.Update)
  1005. {
  1006. case AuthZoneUpdate.Allow:
  1007. isUpdateAllowed = true;
  1008. break;
  1009. case AuthZoneUpdate.AllowOnlyZoneNameServers:
  1010. isUpdateAllowed = await IsZoneNameServerAllowedAsync();
  1011. break;
  1012. case AuthZoneUpdate.AllowOnlySpecifiedIpAddresses:
  1013. isUpdateAllowed = IsSpecifiedIpAddressAllowed();
  1014. break;
  1015. case AuthZoneUpdate.AllowBothZoneNameServersAndSpecifiedIpAddresses:
  1016. isUpdateAllowed = IsSpecifiedIpAddressAllowed() || await IsZoneNameServerAllowedAsync();
  1017. break;
  1018. case AuthZoneUpdate.Deny:
  1019. default:
  1020. isUpdateAllowed = false;
  1021. break;
  1022. }
  1023. if (!isUpdateAllowed)
  1024. {
  1025. _log?.Write(remoteEP, protocol, "DNS Server refused a zone UPDATE request since the request IP address is not allowed by the zone: " + (authZoneInfo.Name == "" ? "<root>" : authZoneInfo.Name));
  1026. return false;
  1027. }
  1028. //check security policies
  1029. if ((authZoneInfo.UpdateSecurityPolicies is not null) && (authZoneInfo.UpdateSecurityPolicies.Count > 0))
  1030. {
  1031. if ((tsigAuthenticatedKeyName is null) || !authZoneInfo.UpdateSecurityPolicies.TryGetValue(tsigAuthenticatedKeyName.ToLower(), out IReadOnlyDictionary<string, IReadOnlyList<DnsResourceRecordType>> policyMap))
  1032. {
  1033. _log?.Write(remoteEP, protocol, "DNS Server refused a zone UPDATE request since the request is missing TSIG auth required by the zone: " + (authZoneInfo.Name == "" ? "<root>" : authZoneInfo.Name));
  1034. return false;
  1035. }
  1036. //check policy
  1037. foreach (DnsResourceRecord uRecord in request.Authority)
  1038. {
  1039. bool isPermitted = false;
  1040. foreach (KeyValuePair<string, IReadOnlyList<DnsResourceRecordType>> policy in policyMap)
  1041. {
  1042. if (
  1043. uRecord.Name.Equals(policy.Key, StringComparison.OrdinalIgnoreCase) ||
  1044. (policy.Key.StartsWith("*.") && uRecord.Name.EndsWith(policy.Key.Substring(1), StringComparison.OrdinalIgnoreCase))
  1045. )
  1046. {
  1047. foreach (DnsResourceRecordType allowedType in policy.Value)
  1048. {
  1049. if ((allowedType == DnsResourceRecordType.ANY) || (allowedType == uRecord.Type))
  1050. {
  1051. isPermitted = true;
  1052. break;
  1053. }
  1054. }
  1055. if (isPermitted)
  1056. break;
  1057. }
  1058. }
  1059. if (!isPermitted)
  1060. return false;
  1061. }
  1062. }
  1063. return true;
  1064. }
  1065. switch (authZoneInfo.Type)
  1066. {
  1067. case AuthZoneType.Primary:
  1068. //update
  1069. {
  1070. //process prerequisite section
  1071. {
  1072. Dictionary<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>> temp = new Dictionary<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>>();
  1073. foreach (DnsResourceRecord prRecord in request.Answer)
  1074. {
  1075. if (prRecord.TTL != 0)
  1076. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1077. AuthZoneInfo prAuthZoneInfo = _authZoneManager.FindAuthZoneInfo(prRecord.Name);
  1078. if ((prAuthZoneInfo is null) || !prAuthZoneInfo.Name.Equals(authZoneInfo.Name, StringComparison.OrdinalIgnoreCase))
  1079. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NotZone, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1080. if (prRecord.Class == DnsClass.ANY)
  1081. {
  1082. if (prRecord.RDATA.RDLENGTH != 0)
  1083. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1084. if (prRecord.Type == DnsResourceRecordType.ANY)
  1085. {
  1086. //check if name is in use
  1087. if (!_authZoneManager.NameExists(authZoneInfo.Name, prRecord.Name))
  1088. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NxDomain, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1089. }
  1090. else
  1091. {
  1092. //check if RRSet exists (value independent)
  1093. IReadOnlyList<DnsResourceRecord> rrset = _authZoneManager.GetRecords(authZoneInfo.Name, prRecord.Name, prRecord.Type);
  1094. if (rrset.Count == 0)
  1095. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NXRRSet, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1096. }
  1097. }
  1098. else if (prRecord.Class == DnsClass.NONE)
  1099. {
  1100. if (prRecord.RDATA.RDLENGTH != 0)
  1101. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1102. if (prRecord.Type == DnsResourceRecordType.ANY)
  1103. {
  1104. //check if name is not in use
  1105. if (_authZoneManager.NameExists(authZoneInfo.Name, prRecord.Name))
  1106. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.YXDomain, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1107. }
  1108. else
  1109. {
  1110. //check if RRSet does not exists
  1111. IReadOnlyList<DnsResourceRecord> rrset = _authZoneManager.GetRecords(authZoneInfo.Name, prRecord.Name, prRecord.Type);
  1112. if (rrset.Count > 0)
  1113. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.YXRRSet, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1114. }
  1115. }
  1116. else if (prRecord.Class == request.Question[0].Class)
  1117. {
  1118. //check if RRSet exists (value dependent)
  1119. //add to temp for later comparison
  1120. string recordName = prRecord.Name.ToLower();
  1121. if (!temp.TryGetValue(recordName, out Dictionary<DnsResourceRecordType, List<DnsResourceRecord>> rrsetEntry))
  1122. {
  1123. rrsetEntry = new Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>();
  1124. temp.Add(recordName, rrsetEntry);
  1125. }
  1126. if (!rrsetEntry.TryGetValue(prRecord.Type, out List<DnsResourceRecord> rrset))
  1127. {
  1128. rrset = new List<DnsResourceRecord>();
  1129. rrsetEntry.Add(prRecord.Type, rrset);
  1130. }
  1131. rrset.Add(prRecord);
  1132. }
  1133. else
  1134. {
  1135. //FORMERR
  1136. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1137. }
  1138. }
  1139. //compare collected RRSets in temp
  1140. foreach (KeyValuePair<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>> zoneEntry in temp)
  1141. {
  1142. foreach (KeyValuePair<DnsResourceRecordType, List<DnsResourceRecord>> rrsetEntry in zoneEntry.Value)
  1143. {
  1144. IReadOnlyList<DnsResourceRecord> prRRSet = rrsetEntry.Value;
  1145. IReadOnlyList<DnsResourceRecord> rrset = _authZoneManager.GetRecords(authZoneInfo.Name, zoneEntry.Key, rrsetEntry.Key);
  1146. //check if RRSet exists (value dependent)
  1147. //compare RRSets
  1148. if (prRRSet.Count != rrset.Count)
  1149. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NXRRSet, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1150. foreach (DnsResourceRecord prRecord in prRRSet)
  1151. {
  1152. bool found = false;
  1153. foreach (DnsResourceRecord record in rrset)
  1154. {
  1155. if (
  1156. prRecord.Name.Equals(record.Name, StringComparison.OrdinalIgnoreCase) &&
  1157. (prRecord.Class == record.Class) &&
  1158. (prRecord.Type == record.Type) &&
  1159. (prRecord.RDATA.RDLENGTH == record.RDATA.RDLENGTH) &&
  1160. prRecord.RDATA.Equals(record.RDATA)
  1161. )
  1162. {
  1163. found = true;
  1164. break;
  1165. }
  1166. }
  1167. if (!found)
  1168. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NXRRSet, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1169. }
  1170. }
  1171. }
  1172. }
  1173. //check for permissions
  1174. if (!await IsUpdatePermittedAsync())
  1175. {
  1176. _log?.Write(remoteEP, protocol, "DNS Server refused a zone UPDATE request due to Dynamic Updates Security Policy for zone: " + (authZoneInfo.Name == "" ? "<root>" : authZoneInfo.Name));
  1177. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1178. }
  1179. //process update section
  1180. {
  1181. //prescan
  1182. foreach (DnsResourceRecord uRecord in request.Authority)
  1183. {
  1184. AuthZoneInfo prAuthZoneInfo = _authZoneManager.FindAuthZoneInfo(uRecord.Name);
  1185. if ((prAuthZoneInfo is null) || !prAuthZoneInfo.Name.Equals(authZoneInfo.Name, StringComparison.OrdinalIgnoreCase))
  1186. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NotZone, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1187. if (uRecord.Class == request.Question[0].Class)
  1188. {
  1189. switch (uRecord.Type)
  1190. {
  1191. case DnsResourceRecordType.ANY:
  1192. case DnsResourceRecordType.AXFR:
  1193. case DnsResourceRecordType.MAILA:
  1194. case DnsResourceRecordType.MAILB:
  1195. case DnsResourceRecordType.IXFR:
  1196. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1197. }
  1198. }
  1199. else if (uRecord.Class == DnsClass.ANY)
  1200. {
  1201. if ((uRecord.TTL != 0) || (uRecord.RDATA.RDLENGTH != 0))
  1202. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1203. switch (uRecord.Type)
  1204. {
  1205. case DnsResourceRecordType.AXFR:
  1206. case DnsResourceRecordType.MAILA:
  1207. case DnsResourceRecordType.MAILB:
  1208. case DnsResourceRecordType.IXFR:
  1209. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1210. }
  1211. }
  1212. else if (uRecord.Class == DnsClass.NONE)
  1213. {
  1214. if (uRecord.TTL != 0)
  1215. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1216. switch (uRecord.Type)
  1217. {
  1218. case DnsResourceRecordType.ANY:
  1219. case DnsResourceRecordType.AXFR:
  1220. case DnsResourceRecordType.MAILA:
  1221. case DnsResourceRecordType.MAILB:
  1222. case DnsResourceRecordType.IXFR:
  1223. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1224. }
  1225. }
  1226. else
  1227. {
  1228. //FORMERR
  1229. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1230. }
  1231. }
  1232. //update
  1233. Dictionary<string, Dictionary<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>>> originalRRSets = new Dictionary<string, Dictionary<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>>>();
  1234. void AddToOriginalRRSets(string domain, DnsResourceRecordType type, IReadOnlyList<DnsResourceRecord> existingRRSet)
  1235. {
  1236. if (!originalRRSets.TryGetValue(domain, out Dictionary<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>> originalRRSetEntries))
  1237. {
  1238. originalRRSetEntries = new Dictionary<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>>();
  1239. originalRRSets.Add(domain, originalRRSetEntries);
  1240. }
  1241. originalRRSetEntries.TryAdd(type, existingRRSet);
  1242. }
  1243. try
  1244. {
  1245. foreach (DnsResourceRecord uRecord in request.Authority)
  1246. {
  1247. if (uRecord.Class == request.Question[0].Class)
  1248. {
  1249. //Add to an RRset
  1250. if (uRecord.Type == DnsResourceRecordType.CNAME)
  1251. {
  1252. if (_authZoneManager.NameExists(authZoneInfo.Name, uRecord.Name) && (_authZoneManager.GetRecords(authZoneInfo.Name, uRecord.Name, DnsResourceRecordType.CNAME).Count == 0))
  1253. continue; //current name exists and has non-CNAME records so cannot add CNAME record
  1254. IReadOnlyList<DnsResourceRecord> existingRRSet = _authZoneManager.GetRecords(authZoneInfo.Name, uRecord.Name, uRecord.Type);
  1255. AddToOriginalRRSets(uRecord.Name, uRecord.Type, existingRRSet);
  1256. _authZoneManager.SetRecord(authZoneInfo.Name, uRecord);
  1257. }
  1258. else if (uRecord.Type == DnsResourceRecordType.DNAME)
  1259. {
  1260. IReadOnlyList<DnsResourceRecord> existingRRSet = _authZoneManager.GetRecords(authZoneInfo.Name, uRecord.Name, uRecord.Type);
  1261. AddToOriginalRRSets(uRecord.Name, uRecord.Type, existingRRSet);
  1262. _authZoneManager.SetRecord(authZoneInfo.Name, uRecord);
  1263. }
  1264. else if (uRecord.Type == DnsResourceRecordType.SOA)
  1265. {
  1266. if (!uRecord.Name.Equals(authZoneInfo.Name, StringComparison.OrdinalIgnoreCase))
  1267. continue; //can add SOA only to apex
  1268. IReadOnlyList<DnsResourceRecord> existingRRSet = _authZoneManager.GetRecords(authZoneInfo.Name, uRecord.Name, uRecord.Type);
  1269. AddToOriginalRRSets(uRecord.Name, uRecord.Type, existingRRSet);
  1270. _authZoneManager.SetRecord(authZoneInfo.Name, uRecord);
  1271. }
  1272. else
  1273. {
  1274. if (_authZoneManager.GetRecords(authZoneInfo.Name, uRecord.Name, DnsResourceRecordType.CNAME).Count > 0)
  1275. continue; //current name contains CNAME so cannot add non-CNAME record
  1276. IReadOnlyList<DnsResourceRecord> existingRRSet = _authZoneManager.GetRecords(authZoneInfo.Name, uRecord.Name, uRecord.Type);
  1277. AddToOriginalRRSets(uRecord.Name, uRecord.Type, existingRRSet);
  1278. if (uRecord.Type == DnsResourceRecordType.NS)
  1279. uRecord.SyncGlueRecords(request.Additional);
  1280. _authZoneManager.AddRecord(authZoneInfo.Name, uRecord);
  1281. }
  1282. }
  1283. else if (uRecord.Class == DnsClass.ANY)
  1284. {
  1285. if (uRecord.Type == DnsResourceRecordType.ANY)
  1286. {
  1287. //Delete all RRsets from a name
  1288. IReadOnlyDictionary<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>> existingRRSets = _authZoneManager.GetAllRecords(authZoneInfo.Name, uRecord.Name);
  1289. if (uRecord.Name.Equals(authZoneInfo.Name, StringComparison.OrdinalIgnoreCase))
  1290. {
  1291. foreach (KeyValuePair<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>> existingRRSet in existingRRSets)
  1292. {
  1293. switch (existingRRSet.Key)
  1294. {
  1295. case DnsResourceRecordType.SOA:
  1296. case DnsResourceRecordType.NS:
  1297. case DnsResourceRecordType.DNSKEY:
  1298. case DnsResourceRecordType.RRSIG:
  1299. case DnsResourceRecordType.NSEC:
  1300. case DnsResourceRecordType.NSEC3PARAM:
  1301. case DnsResourceRecordType.NSEC3:
  1302. continue; //no apex SOA/NS can be deleted; skip DNSSEC rrsets
  1303. }
  1304. AddToOriginalRRSets(uRecord.Name, existingRRSet.Key, existingRRSet.Value);
  1305. _authZoneManager.DeleteRecords(authZoneInfo.Name, uRecord.Name, existingRRSet.Key);
  1306. }
  1307. }
  1308. else
  1309. {
  1310. foreach (KeyValuePair<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>> existingRRSet in existingRRSets)
  1311. {
  1312. switch (existingRRSet.Key)
  1313. {
  1314. case DnsResourceRecordType.DNSKEY:
  1315. case DnsResourceRecordType.RRSIG:
  1316. case DnsResourceRecordType.NSEC:
  1317. case DnsResourceRecordType.NSEC3PARAM:
  1318. case DnsResourceRecordType.NSEC3:
  1319. continue; //skip DNSSEC rrsets
  1320. }
  1321. AddToOriginalRRSets(uRecord.Name, existingRRSet.Key, existingRRSet.Value);
  1322. _authZoneManager.DeleteRecords(authZoneInfo.Name, uRecord.Name, existingRRSet.Key);
  1323. }
  1324. }
  1325. }
  1326. else
  1327. {
  1328. //Delete an RRset
  1329. if (uRecord.Name.Equals(authZoneInfo.Name, StringComparison.OrdinalIgnoreCase))
  1330. {
  1331. switch (uRecord.Type)
  1332. {
  1333. case DnsResourceRecordType.SOA:
  1334. case DnsResourceRecordType.NS:
  1335. case DnsResourceRecordType.DNSKEY:
  1336. case DnsResourceRecordType.RRSIG:
  1337. case DnsResourceRecordType.NSEC:
  1338. case DnsResourceRecordType.NSEC3PARAM:
  1339. case DnsResourceRecordType.NSEC3:
  1340. continue; //no apex SOA/NS can be deleted; skip DNSSEC rrsets
  1341. }
  1342. }
  1343. IReadOnlyList<DnsResourceRecord> existingRRSet = _authZoneManager.GetRecords(authZoneInfo.Name, uRecord.Name, uRecord.Type);
  1344. AddToOriginalRRSets(uRecord.Name, uRecord.Type, existingRRSet);
  1345. _authZoneManager.DeleteRecords(authZoneInfo.Name, uRecord.Name, uRecord.Type);
  1346. }
  1347. }
  1348. else if (uRecord.Class == DnsClass.NONE)
  1349. {
  1350. //Delete an RR from an RRset
  1351. switch (uRecord.Type)
  1352. {
  1353. case DnsResourceRecordType.SOA:
  1354. case DnsResourceRecordType.DNSKEY:
  1355. case DnsResourceRecordType.RRSIG:
  1356. case DnsResourceRecordType.NSEC:
  1357. case DnsResourceRecordType.NSEC3PARAM:
  1358. case DnsResourceRecordType.NSEC3:
  1359. continue; //no SOA can be deleted; skip DNSSEC rrsets
  1360. }
  1361. IReadOnlyList<DnsResourceRecord> existingRRSet = _authZoneManager.GetRecords(authZoneInfo.Name, uRecord.Name, uRecord.Type);
  1362. if ((uRecord.Type == DnsResourceRecordType.NS) && (existingRRSet.Count == 1) && uRecord.Name.Equals(authZoneInfo.Name, StringComparison.OrdinalIgnoreCase))
  1363. continue; //no apex NS can be deleted if only 1 NS exists
  1364. AddToOriginalRRSets(uRecord.Name, uRecord.Type, existingRRSet);
  1365. _authZoneManager.DeleteRecord(authZoneInfo.Name, uRecord.Name, uRecord.Type, uRecord.RDATA);
  1366. }
  1367. }
  1368. }
  1369. catch
  1370. {
  1371. //revert
  1372. foreach (KeyValuePair<string, Dictionary<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>>> originalRRSetEntries in originalRRSets)
  1373. {
  1374. foreach (KeyValuePair<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>> originalRRSet in originalRRSetEntries.Value)
  1375. {
  1376. if (originalRRSet.Value.Count == 0)
  1377. _authZoneManager.DeleteRecords(authZoneInfo.Name, originalRRSetEntries.Key, originalRRSet.Key);
  1378. else
  1379. _authZoneManager.SetRecords(authZoneInfo.Name, originalRRSet.Value);
  1380. }
  1381. }
  1382. throw;
  1383. }
  1384. }
  1385. _authZoneManager.SaveZoneFile(authZoneInfo.Name);
  1386. _log?.Write(remoteEP, protocol, "DNS Server successfully processed a zone UPDATE request for zone: " + (authZoneInfo.Name == "" ? "<root>" : authZoneInfo.Name));
  1387. //NOERROR
  1388. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NoError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1389. }
  1390. case AuthZoneType.Secondary:
  1391. //forward to primary
  1392. {
  1393. IReadOnlyList<NameServerAddress> primaryNameServers = await authZoneInfo.GetPrimaryNameServerAddressesAsync(this);
  1394. DnsResourceRecord soaRecord = authZoneInfo.GetApexRecords(DnsResourceRecordType.SOA)[0];
  1395. AuthRecordInfo recordInfo = soaRecord.GetAuthRecordInfo();
  1396. switch (recordInfo.ZoneTransferProtocol)
  1397. {
  1398. case DnsTransportProtocol.Tls:
  1399. case DnsTransportProtocol.Quic:
  1400. {
  1401. //change name server protocol to TLS/QUIC
  1402. List<NameServerAddress> updatedNameServers = new List<NameServerAddress>(primaryNameServers.Count);
  1403. foreach (NameServerAddress primaryNameServer in primaryNameServers)
  1404. {
  1405. if (primaryNameServer.Protocol == recordInfo.ZoneTransferProtocol)
  1406. updatedNameServers.Add(primaryNameServer);
  1407. else
  1408. updatedNameServers.Add(primaryNameServer.ChangeProtocol(recordInfo.ZoneTransferProtocol));
  1409. }
  1410. primaryNameServers = updatedNameServers;
  1411. }
  1412. break;
  1413. default:
  1414. if (protocol == DnsTransportProtocol.Tcp)
  1415. {
  1416. //change name server protocol to TCP
  1417. List<NameServerAddress> updatedNameServers = new List<NameServerAddress>(primaryNameServers.Count);
  1418. foreach (NameServerAddress primaryNameServer in primaryNameServers)
  1419. {
  1420. if (primaryNameServer.Protocol == DnsTransportProtocol.Tcp)
  1421. updatedNameServers.Add(primaryNameServer);
  1422. else
  1423. updatedNameServers.Add(primaryNameServer.ChangeProtocol(DnsTransportProtocol.Tcp));
  1424. }
  1425. primaryNameServers = updatedNameServers;
  1426. }
  1427. break;
  1428. }
  1429. TsigKey key = null;
  1430. if (!string.IsNullOrEmpty(tsigAuthenticatedKeyName) && ((_tsigKeys is null) || !_tsigKeys.TryGetValue(tsigAuthenticatedKeyName, out key)))
  1431. throw new DnsServerException("DNS Server does not have TSIG key '" + tsigAuthenticatedKeyName + "' configured to authenticate dynamic updates for secondary zone: " + (authZoneInfo.Name == "" ? "<root>" : authZoneInfo.Name));
  1432. DnsClient dnsClient = new DnsClient(primaryNameServers);
  1433. dnsClient.Proxy = _proxy;
  1434. dnsClient.PreferIPv6 = _preferIPv6;
  1435. dnsClient.Retries = _forwarderRetries;
  1436. dnsClient.Timeout = _forwarderTimeout;
  1437. dnsClient.Concurrency = 1;
  1438. DnsDatagram newRequest = request.Clone();
  1439. newRequest.SetRandomIdentifier();
  1440. DnsDatagram newResponse;
  1441. if (key is null)
  1442. newResponse = await dnsClient.ResolveAsync(newRequest);
  1443. else
  1444. newResponse = await dnsClient.ResolveAsync(newRequest, key);
  1445. newResponse.SetIdentifier(request.Identifier);
  1446. return newResponse;
  1447. }
  1448. default:
  1449. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NotAuth, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1450. }
  1451. }
  1452. private async Task<DnsDatagram> ProcessZoneTransferQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, string tsigAuthenticatedKeyName)
  1453. {
  1454. AuthZoneInfo authZoneInfo = _authZoneManager.GetAuthZoneInfo(request.Question[0].Name);
  1455. if ((authZoneInfo is null) || authZoneInfo.Disabled || authZoneInfo.IsExpired)
  1456. {
  1457. _log?.Write(remoteEP, protocol, "DNS Server refused a zone transfer request due to zone not found, zone disabled, or zone expired reasons for zone: " + (authZoneInfo.Name == "" ? "<root>" : authZoneInfo.Name));
  1458. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1459. }
  1460. switch (authZoneInfo.Type)
  1461. {
  1462. case AuthZoneType.Primary:
  1463. case AuthZoneType.Secondary:
  1464. break;
  1465. default:
  1466. _log?.Write(remoteEP, protocol, "DNS Server refused a zone transfer request since the DNS server is not authoritative for zone: " + (authZoneInfo.Name == "" ? "<root>" : authZoneInfo.Name));
  1467. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1468. }
  1469. async Task<bool> IsZoneNameServerAllowedAsync()
  1470. {
  1471. IPAddress remoteAddress = remoteEP.Address;
  1472. IReadOnlyList<NameServerAddress> secondaryNameServers = await authZoneInfo.GetSecondaryNameServerAddressesAsync(this);
  1473. foreach (NameServerAddress secondaryNameServer in secondaryNameServers)
  1474. {
  1475. if (secondaryNameServer.IPEndPoint.Address.Equals(remoteAddress))
  1476. return true;
  1477. }
  1478. return false;
  1479. }
  1480. bool IsSpecifiedNameServerAllowed()
  1481. {
  1482. IPAddress remoteAddress = remoteEP.Address;
  1483. IReadOnlyCollection<IPAddress> specifiedNameServers = authZoneInfo.ZoneTransferNameServers;
  1484. if (specifiedNameServers is not null)
  1485. {
  1486. foreach (IPAddress specifiedNameServer in specifiedNameServers)
  1487. {
  1488. if (specifiedNameServer.Equals(remoteAddress))
  1489. return true;
  1490. }
  1491. }
  1492. return false;
  1493. }
  1494. bool isZoneTransferAllowed = false;
  1495. switch (authZoneInfo.ZoneTransfer)
  1496. {
  1497. case AuthZoneTransfer.Deny:
  1498. break;
  1499. case AuthZoneTransfer.Allow:
  1500. isZoneTransferAllowed = true;
  1501. break;
  1502. case AuthZoneTransfer.AllowOnlyZoneNameServers:
  1503. isZoneTransferAllowed = await IsZoneNameServerAllowedAsync();
  1504. break;
  1505. case AuthZoneTransfer.AllowOnlySpecifiedNameServers:
  1506. isZoneTransferAllowed = IsSpecifiedNameServerAllowed();
  1507. break;
  1508. case AuthZoneTransfer.AllowBothZoneAndSpecifiedNameServers:
  1509. isZoneTransferAllowed = IsSpecifiedNameServerAllowed() || await IsZoneNameServerAllowedAsync();
  1510. break;
  1511. }
  1512. if (!isZoneTransferAllowed)
  1513. {
  1514. _log?.Write(remoteEP, protocol, "DNS Server refused a zone transfer request since the request IP address is not allowed by the zone: " + (authZoneInfo.Name == "" ? "<root>" : authZoneInfo.Name));
  1515. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1516. }
  1517. if ((authZoneInfo.ZoneTransferTsigKeyNames is not null) && (authZoneInfo.ZoneTransferTsigKeyNames.Count > 0))
  1518. {
  1519. if ((tsigAuthenticatedKeyName is null) || !authZoneInfo.ZoneTransferTsigKeyNames.ContainsKey(tsigAuthenticatedKeyName.ToLower()))
  1520. {
  1521. _log?.Write(remoteEP, protocol, "DNS Server refused a zone transfer request since the request is missing TSIG auth required by the zone: " + (authZoneInfo.Name == "" ? "<root>" : authZoneInfo.Name));
  1522. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1523. }
  1524. }
  1525. _log?.Write(remoteEP, protocol, "DNS Server received zone transfer request for zone: " + (authZoneInfo.Name == "" ? "<root>" : authZoneInfo.Name));
  1526. IReadOnlyList<DnsResourceRecord> xfrRecords;
  1527. if (request.Question[0].Type == DnsResourceRecordType.IXFR)
  1528. {
  1529. if ((request.Authority.Count == 1) && (request.Authority[0].Type == DnsResourceRecordType.SOA))
  1530. xfrRecords = _authZoneManager.QueryIncrementalZoneTransferRecords(request.Question[0].Name, request.Authority[0]);
  1531. else
  1532. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1533. }
  1534. else
  1535. {
  1536. xfrRecords = _authZoneManager.QueryZoneTransferRecords(request.Question[0].Name);
  1537. }
  1538. DnsDatagram xfrResponse = new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, true, false, request.RecursionDesired, false, false, false, DnsResponseCode.NoError, request.Question, xfrRecords) { Tag = DnsServerResponseType.Authoritative };
  1539. xfrResponse = xfrResponse.Split();
  1540. return xfrResponse;
  1541. }
  1542. private async Task<DnsDatagram> ProcessAuthoritativeQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, bool skipDnsAppAuthoritativeRequestHandlers)
  1543. {
  1544. DnsDatagram response = await AuthoritativeQueryAsync(request, remoteEP, protocol, isRecursionAllowed, skipDnsAppAuthoritativeRequestHandlers);
  1545. if (response is null)
  1546. return null;
  1547. bool reprocessResponse;
  1548. do
  1549. {
  1550. reprocessResponse = false;
  1551. if (response.RCODE == DnsResponseCode.NoError)
  1552. {
  1553. if (response.Answer.Count > 0)
  1554. {
  1555. DnsResourceRecordType questionType = request.Question[0].Type;
  1556. DnsResourceRecord lastRR = response.GetLastAnswerRecord();
  1557. if ((lastRR.Type != questionType) && (questionType != DnsResourceRecordType.ANY))
  1558. {
  1559. switch (lastRR.Type)
  1560. {
  1561. case DnsResourceRecordType.CNAME:
  1562. return await ProcessCNAMEAsync(request, remoteEP, response, isRecursionAllowed, protocol, false, skipDnsAppAuthoritativeRequestHandlers);
  1563. case DnsResourceRecordType.ANAME:
  1564. return await ProcessANAMEAsync(request, remoteEP, response, isRecursionAllowed, protocol, skipDnsAppAuthoritativeRequestHandlers);
  1565. }
  1566. }
  1567. }
  1568. else if (response.Authority.Count > 0)
  1569. {
  1570. DnsResourceRecord firstAuthority = response.FindFirstAuthorityRecord();
  1571. switch (firstAuthority.Type)
  1572. {
  1573. case DnsResourceRecordType.NS:
  1574. if (request.RecursionDesired && isRecursionAllowed)
  1575. {
  1576. //do forced recursive resolution using empty conditional forwarders; name servers will be provided via ResolverDnsCache
  1577. return await ProcessRecursiveQueryAsync(request, remoteEP, protocol, Array.Empty<DnsResourceRecord>(), _dnssecValidation, false, skipDnsAppAuthoritativeRequestHandlers);
  1578. }
  1579. break;
  1580. case DnsResourceRecordType.FWD:
  1581. if (!request.RecursionDesired || !isRecursionAllowed)
  1582. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1583. //do conditional forwarding
  1584. return await ProcessRecursiveQueryAsync(request, remoteEP, protocol, response.Authority, _dnssecValidation, false, skipDnsAppAuthoritativeRequestHandlers);
  1585. case DnsResourceRecordType.APP:
  1586. response = await ProcessAPPAsync(request, remoteEP, response, isRecursionAllowed, protocol);
  1587. reprocessResponse = true;
  1588. break;
  1589. }
  1590. }
  1591. }
  1592. }
  1593. while (reprocessResponse);
  1594. return response;
  1595. }
  1596. private async Task<DnsDatagram> AuthoritativeQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, bool skipDnsAppAuthoritativeRequestHandlers)
  1597. {
  1598. if (!skipDnsAppAuthoritativeRequestHandlers)
  1599. {
  1600. foreach (IDnsAuthoritativeRequestHandler requestHandler in _dnsApplicationManager.DnsAuthoritativeRequestHandlers)
  1601. {
  1602. try
  1603. {
  1604. DnsDatagram appResponse = await requestHandler.ProcessRequestAsync(request, remoteEP, protocol, isRecursionAllowed);
  1605. if (appResponse is not null)
  1606. {
  1607. if (appResponse.Tag is null)
  1608. appResponse.Tag = DnsServerResponseType.Authoritative;
  1609. return appResponse;
  1610. }
  1611. }
  1612. catch (Exception ex)
  1613. {
  1614. _log?.Write(remoteEP, protocol, ex);
  1615. }
  1616. }
  1617. }
  1618. DnsDatagram response = _authZoneManager.Query(request, isRecursionAllowed);
  1619. if (response is not null)
  1620. {
  1621. response.Tag = DnsServerResponseType.Authoritative;
  1622. return response;
  1623. }
  1624. return null;
  1625. }
  1626. private async Task<DnsDatagram> ProcessAPPAsync(DnsDatagram request, IPEndPoint remoteEP, DnsDatagram response, bool isRecursionAllowed, DnsTransportProtocol protocol)
  1627. {
  1628. DnsResourceRecord appResourceRecord = response.Authority[0];
  1629. DnsApplicationRecordData appRecord = appResourceRecord.RDATA as DnsApplicationRecordData;
  1630. if (_dnsApplicationManager.Applications.TryGetValue(appRecord.AppName, out DnsApplication application))
  1631. {
  1632. if (application.DnsAppRecordRequestHandlers.TryGetValue(appRecord.ClassPath, out IDnsAppRecordRequestHandler appRecordRequestHandler))
  1633. {
  1634. AuthZoneInfo zoneInfo = _authZoneManager.FindAuthZoneInfo(appResourceRecord.Name);
  1635. DnsDatagram appResponse = await appRecordRequestHandler.ProcessRequestAsync(request, remoteEP, protocol, isRecursionAllowed, zoneInfo.Name, appResourceRecord.Name, appResourceRecord.TTL, appRecord.Data);
  1636. if (appResponse is null)
  1637. {
  1638. DnsResponseCode rcode;
  1639. IReadOnlyList<DnsResourceRecord> authority = null;
  1640. if (zoneInfo.Type == AuthZoneType.Forwarder)
  1641. {
  1642. //return FWD response
  1643. rcode = DnsResponseCode.NoError;
  1644. if (!zoneInfo.Name.Equals(appResourceRecord.Name, StringComparison.OrdinalIgnoreCase))
  1645. {
  1646. AuthZone authZone = _authZoneManager.GetAuthZone(zoneInfo.Name, appResourceRecord.Name);
  1647. if (authZone is not null)
  1648. authority = authZone.QueryRecords(DnsResourceRecordType.FWD, false);
  1649. }
  1650. if ((authority is null) || (authority.Count == 0))
  1651. authority = zoneInfo.ApexZone.QueryRecords(DnsResourceRecordType.FWD, false);
  1652. }
  1653. else
  1654. {
  1655. //return NODATA/NXDOMAIN response
  1656. if (request.Question[0].Name.Length > appResourceRecord.Name.Length)
  1657. rcode = DnsResponseCode.NxDomain;
  1658. else
  1659. rcode = DnsResponseCode.NoError;
  1660. authority = zoneInfo.GetApexRecords(DnsResourceRecordType.SOA);
  1661. }
  1662. return new DnsDatagram(request.Identifier, true, request.OPCODE, false, false, request.RecursionDesired, isRecursionAllowed, false, false, rcode, request.Question, null, authority) { Tag = DnsServerResponseType.Authoritative };
  1663. }
  1664. else
  1665. {
  1666. if (appResponse.AuthoritativeAnswer)
  1667. appResponse.Tag = DnsServerResponseType.Authoritative;
  1668. return appResponse; //return app response
  1669. }
  1670. }
  1671. else
  1672. {
  1673. _log?.Write(remoteEP, protocol, "DNS request handler '" + appRecord.ClassPath + "' was not found in the application '" + appRecord.AppName + "': " + appResourceRecord.Name);
  1674. }
  1675. }
  1676. else
  1677. {
  1678. _log?.Write(remoteEP, protocol, "DNS application '" + appRecord.AppName + "' was not found: " + appResourceRecord.Name);
  1679. }
  1680. //return server failure response with SOA
  1681. {
  1682. AuthZoneInfo zoneInfo = _authZoneManager.FindAuthZoneInfo(request.Question[0].Name);
  1683. IReadOnlyList<DnsResourceRecord> authority = zoneInfo.GetApexRecords(DnsResourceRecordType.SOA);
  1684. return new DnsDatagram(request.Identifier, true, request.OPCODE, false, false, request.RecursionDesired, isRecursionAllowed, false, false, DnsResponseCode.ServerFailure, request.Question, null, authority) { Tag = DnsServerResponseType.Authoritative };
  1685. }
  1686. }
  1687. private async Task<DnsDatagram> ProcessCNAMEAsync(DnsDatagram request, IPEndPoint remoteEP, DnsDatagram response, bool isRecursionAllowed, DnsTransportProtocol protocol, bool cacheRefreshOperation, bool skipDnsAppAuthoritativeRequestHandlers)
  1688. {
  1689. List<DnsResourceRecord> newAnswer = new List<DnsResourceRecord>(response.Answer.Count + 4);
  1690. newAnswer.AddRange(response.Answer);
  1691. //copying NSEC/NSEC3 for for wildcard answers
  1692. List<DnsResourceRecord> newAuthority = new List<DnsResourceRecord>(2);
  1693. foreach (DnsResourceRecord record in response.Authority)
  1694. {
  1695. switch (record.Type)
  1696. {
  1697. case DnsResourceRecordType.NSEC:
  1698. case DnsResourceRecordType.NSEC3:
  1699. newAuthority.Add(record);
  1700. break;
  1701. case DnsResourceRecordType.RRSIG:
  1702. switch ((record.RDATA as DnsRRSIGRecordData).TypeCovered)
  1703. {
  1704. case DnsResourceRecordType.NSEC:
  1705. case DnsResourceRecordType.NSEC3:
  1706. newAuthority.Add(record);
  1707. break;
  1708. }
  1709. break;
  1710. }
  1711. }
  1712. DnsDatagram lastResponse = response;
  1713. bool isAuthoritativeAnswer = response.AuthoritativeAnswer;
  1714. DnsResourceRecord lastRR = response.GetLastAnswerRecord();
  1715. EDnsOption[] eDnsClientSubnetOption = null;
  1716. DnsDatagram newResponse = null;
  1717. if (_eDnsClientSubnet)
  1718. {
  1719. EDnsClientSubnetOptionData requestECS = request.GetEDnsClientSubnetOption();
  1720. if (requestECS is not null)
  1721. eDnsClientSubnetOption = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EDNS_CLIENT_SUBNET, requestECS) };
  1722. }
  1723. int queryCount = 0;
  1724. do
  1725. {
  1726. string cnameDomain = (lastRR.RDATA as DnsCNAMERecordData).Domain;
  1727. if (lastRR.Name.Equals(cnameDomain, StringComparison.OrdinalIgnoreCase))
  1728. break; //loop detected
  1729. DnsDatagram newRequest = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { new DnsQuestionRecord(cnameDomain, request.Question[0].Type, request.Question[0].Class) }, null, null, null, _udpPayloadSize, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, eDnsClientSubnetOption);
  1730. //query authoritative zone first
  1731. newResponse = await AuthoritativeQueryAsync(newRequest, remoteEP, protocol, isRecursionAllowed, skipDnsAppAuthoritativeRequestHandlers);
  1732. if (newResponse is null)
  1733. {
  1734. //not found in auth zone
  1735. if (newRequest.RecursionDesired && isRecursionAllowed)
  1736. {
  1737. //do recursion
  1738. newResponse = await RecursiveResolveAsync(newRequest, remoteEP, null, _dnssecValidation, false, cacheRefreshOperation, skipDnsAppAuthoritativeRequestHandlers);
  1739. isAuthoritativeAnswer = false;
  1740. }
  1741. else
  1742. {
  1743. //break since no recursion allowed/desired
  1744. break;
  1745. }
  1746. }
  1747. else if ((newResponse.Answer.Count > 0) && (newResponse.GetLastAnswerRecord().Type == DnsResourceRecordType.ANAME))
  1748. {
  1749. newResponse = await ProcessANAMEAsync(request, remoteEP, newResponse, isRecursionAllowed, protocol, skipDnsAppAuthoritativeRequestHandlers);
  1750. }
  1751. else if ((newResponse.Answer.Count == 0) && (newResponse.Authority.Count > 0))
  1752. {
  1753. //found delegated/forwarded zone
  1754. DnsResourceRecord firstAuthority = newResponse.FindFirstAuthorityRecord();
  1755. switch (firstAuthority.Type)
  1756. {
  1757. case DnsResourceRecordType.NS:
  1758. if (newRequest.RecursionDesired && isRecursionAllowed)
  1759. {
  1760. //do forced recursive resolution using empty conditional forwarders; name servers will be provided via ResolveDnsCache
  1761. newResponse = await RecursiveResolveAsync(newRequest, remoteEP, Array.Empty<DnsResourceRecord>(), _dnssecValidation, false, false, skipDnsAppAuthoritativeRequestHandlers);
  1762. isAuthoritativeAnswer = false;
  1763. }
  1764. break;
  1765. case DnsResourceRecordType.FWD:
  1766. //do conditional forwarding
  1767. newResponse = await RecursiveResolveAsync(newRequest, remoteEP, newResponse.Authority, _dnssecValidation, false, false, skipDnsAppAuthoritativeRequestHandlers);
  1768. isAuthoritativeAnswer = false;
  1769. break;
  1770. case DnsResourceRecordType.APP:
  1771. newResponse = await ProcessAPPAsync(newRequest, remoteEP, newResponse, isRecursionAllowed, protocol);
  1772. break;
  1773. }
  1774. }
  1775. //check last response
  1776. if (newResponse.Answer.Count == 0)
  1777. break; //cannot proceed to resolve further
  1778. lastRR = newResponse.GetLastAnswerRecord();
  1779. if (lastRR.Type != DnsResourceRecordType.CNAME)
  1780. {
  1781. newAnswer.AddRange(newResponse.Answer);
  1782. break; //cname was resolved
  1783. }
  1784. bool foundRepeat = false;
  1785. foreach (DnsResourceRecord answerRecord in newAnswer)
  1786. {
  1787. if (answerRecord.Type != DnsResourceRecordType.CNAME)
  1788. continue;
  1789. if (answerRecord.RDATA.Equals(lastRR.RDATA))
  1790. {
  1791. foundRepeat = true;
  1792. break;
  1793. }
  1794. }
  1795. if (foundRepeat)
  1796. break; //loop detected
  1797. newAnswer.AddRange(newResponse.Answer);
  1798. lastResponse = newResponse;
  1799. }
  1800. while (++queryCount < MAX_CNAME_HOPS);
  1801. DnsResponseCode rcode;
  1802. IReadOnlyList<DnsResourceRecord> authority;
  1803. IReadOnlyList<DnsResourceRecord> additional;
  1804. if (newResponse is null)
  1805. {
  1806. //no recursion available
  1807. rcode = DnsResponseCode.NoError;
  1808. if (newAuthority.Count == 0)
  1809. {
  1810. authority = lastResponse.Authority;
  1811. }
  1812. else
  1813. {
  1814. newAuthority.AddRange(lastResponse.Authority);
  1815. authority = newAuthority;
  1816. }
  1817. additional = lastResponse.Additional;
  1818. }
  1819. else
  1820. {
  1821. rcode = newResponse.RCODE;
  1822. if (newAuthority.Count == 0)
  1823. {
  1824. authority = newResponse.Authority;
  1825. }
  1826. else
  1827. {
  1828. newAuthority.AddRange(newResponse.Authority);
  1829. authority = newAuthority;
  1830. }
  1831. additional = newResponse.Additional;
  1832. }
  1833. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, isAuthoritativeAnswer, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, rcode, request.Question, newAnswer, authority, additional) { Tag = response.Tag };
  1834. }
  1835. private async Task<DnsDatagram> ProcessANAMEAsync(DnsDatagram request, IPEndPoint remoteEP, DnsDatagram response, bool isRecursionAllowed, DnsTransportProtocol protocol, bool skipDnsAppAuthoritativeRequestHandlers)
  1836. {
  1837. EDnsOption[] eDnsClientSubnetOption = null;
  1838. if (_eDnsClientSubnet)
  1839. {
  1840. EDnsClientSubnetOptionData requestECS = request.GetEDnsClientSubnetOption();
  1841. if (requestECS is not null)
  1842. eDnsClientSubnetOption = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EDNS_CLIENT_SUBNET, requestECS) };
  1843. }
  1844. Queue<Task<IReadOnlyList<DnsResourceRecord>>> resolveQueue = new Queue<Task<IReadOnlyList<DnsResourceRecord>>>();
  1845. async Task<IReadOnlyList<DnsResourceRecord>> ResolveANAMEAsync(DnsResourceRecord anameRR, int queryCount = 0)
  1846. {
  1847. string lastDomain = (anameRR.RDATA as DnsANAMERecordData).Domain;
  1848. if (anameRR.Name.Equals(lastDomain, StringComparison.OrdinalIgnoreCase))
  1849. return null; //loop detected
  1850. do
  1851. {
  1852. DnsDatagram newRequest = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { new DnsQuestionRecord(lastDomain, request.Question[0].Type, request.Question[0].Class) }, null, null, null, _udpPayloadSize, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, eDnsClientSubnetOption);
  1853. //query authoritative zone first
  1854. DnsDatagram newResponse = await AuthoritativeQueryAsync(newRequest, remoteEP, protocol, isRecursionAllowed, skipDnsAppAuthoritativeRequestHandlers);
  1855. if (newResponse is null)
  1856. {
  1857. //not found in auth zone; do recursion
  1858. newResponse = await RecursiveResolveAsync(newRequest, remoteEP, null, _dnssecValidation, false, false, skipDnsAppAuthoritativeRequestHandlers);
  1859. }
  1860. else if ((newResponse.Answer.Count == 0) && (newResponse.Authority.Count > 0))
  1861. {
  1862. //found delegated/forwarded zone
  1863. DnsResourceRecord firstAuthority = newResponse.FindFirstAuthorityRecord();
  1864. switch (firstAuthority.Type)
  1865. {
  1866. case DnsResourceRecordType.NS:
  1867. //do forced recursive resolution using empty conditional forwarders; name servers will be provided via ResolverDnsCache
  1868. newResponse = await RecursiveResolveAsync(newRequest, remoteEP, Array.Empty<DnsResourceRecord>(), _dnssecValidation, false, false, skipDnsAppAuthoritativeRequestHandlers);
  1869. break;
  1870. case DnsResourceRecordType.FWD:
  1871. //do conditional forwarding
  1872. newResponse = await RecursiveResolveAsync(newRequest, remoteEP, newResponse.Authority, _dnssecValidation, false, false, skipDnsAppAuthoritativeRequestHandlers);
  1873. break;
  1874. case DnsResourceRecordType.APP:
  1875. newResponse = await ProcessAPPAsync(newRequest, remoteEP, newResponse, isRecursionAllowed, protocol);
  1876. break;
  1877. }
  1878. }
  1879. //check new response
  1880. if (newResponse.RCODE != DnsResponseCode.NoError)
  1881. return null; //cannot proceed to resolve further
  1882. if (newResponse.Answer.Count == 0)
  1883. return Array.Empty<DnsResourceRecord>(); //NO DATA
  1884. DnsResourceRecordType questionType = request.Question[0].Type;
  1885. DnsResourceRecord lastRR = newResponse.GetLastAnswerRecord();
  1886. if (lastRR.Type == questionType)
  1887. {
  1888. //found final answer
  1889. List<DnsResourceRecord> answers = new List<DnsResourceRecord>();
  1890. foreach (DnsResourceRecord answer in newResponse.Answer)
  1891. {
  1892. if (answer.Type != questionType)
  1893. continue;
  1894. if (anameRR.TTL < answer.TTL)
  1895. answers.Add(new DnsResourceRecord(anameRR.Name, answer.Type, answer.Class, anameRR.TTL, answer.RDATA));
  1896. else
  1897. answers.Add(new DnsResourceRecord(anameRR.Name, answer.Type, answer.Class, answer.TTL, answer.RDATA));
  1898. }
  1899. return answers;
  1900. }
  1901. if (lastRR.Type == DnsResourceRecordType.ANAME)
  1902. {
  1903. if (newResponse.Answer.Count == 1)
  1904. {
  1905. lastDomain = (lastRR.RDATA as DnsANAMERecordData).Domain;
  1906. }
  1907. else
  1908. {
  1909. //resolve multiple ANAME records async
  1910. queryCount++; //increment since one query was done already
  1911. foreach (DnsResourceRecord newAnswer in newResponse.Answer)
  1912. resolveQueue.Enqueue(ResolveANAMEAsync(newAnswer, queryCount));
  1913. return Array.Empty<DnsResourceRecord>();
  1914. }
  1915. }
  1916. else if (lastRR.Type == DnsResourceRecordType.CNAME)
  1917. {
  1918. lastDomain = (lastRR.RDATA as DnsCNAMERecordData).Domain;
  1919. }
  1920. else
  1921. {
  1922. //aname/cname was resolved, but no answer found
  1923. return Array.Empty<DnsResourceRecord>();
  1924. }
  1925. }
  1926. while (++queryCount < MAX_CNAME_HOPS);
  1927. //max hops limit crossed
  1928. return null;
  1929. }
  1930. List<DnsResourceRecord> responseAnswer = new List<DnsResourceRecord>();
  1931. foreach (DnsResourceRecord answer in response.Answer)
  1932. {
  1933. if (answer.Type == DnsResourceRecordType.ANAME)
  1934. {
  1935. resolveQueue.Enqueue(ResolveANAMEAsync(answer));
  1936. }
  1937. else
  1938. {
  1939. if (resolveQueue.Count == 0)
  1940. responseAnswer.Add(answer);
  1941. }
  1942. }
  1943. bool foundErrors = false;
  1944. while (resolveQueue.Count > 0)
  1945. {
  1946. IReadOnlyList<DnsResourceRecord> records = await resolveQueue.Dequeue();
  1947. if (records is null)
  1948. foundErrors = true;
  1949. else if (records.Count > 0)
  1950. responseAnswer.AddRange(records);
  1951. }
  1952. DnsResponseCode rcode = DnsResponseCode.NoError;
  1953. IReadOnlyList<DnsResourceRecord> authority = null;
  1954. if (responseAnswer.Count == 0)
  1955. {
  1956. if (foundErrors)
  1957. {
  1958. rcode = DnsResponseCode.ServerFailure;
  1959. }
  1960. else
  1961. {
  1962. authority = response.Authority;
  1963. //update last used on
  1964. DateTime utcNow = DateTime.UtcNow;
  1965. foreach (DnsResourceRecord record in authority)
  1966. record.GetAuthRecordInfo().LastUsedOn = utcNow;
  1967. }
  1968. }
  1969. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, true, false, request.RecursionDesired, isRecursionAllowed, false, false, rcode, request.Question, responseAnswer, authority, null) { Tag = response.Tag };
  1970. }
  1971. private DnsDatagram ProcessBlockedQuery(DnsDatagram request)
  1972. {
  1973. DnsDatagram response = _blockedZoneManager.Query(request);
  1974. if (response is null)
  1975. {
  1976. //domain not blocked in blocked zone
  1977. response = _blockListZoneManager.Query(request); //check in block list zone
  1978. if (response is null)
  1979. return null; //domain not blocked in block list zone
  1980. //domain is blocked in block list zone
  1981. response.Tag = DnsServerResponseType.Blocked;
  1982. return response;
  1983. }
  1984. else
  1985. {
  1986. //domain is blocked in blocked zone
  1987. DnsQuestionRecord question = request.Question[0];
  1988. string GetBlockedDomain()
  1989. {
  1990. DnsResourceRecord firstAuthority = response.FindFirstAuthorityRecord();
  1991. if ((firstAuthority is not null) && (firstAuthority.Type == DnsResourceRecordType.SOA))
  1992. return firstAuthority.Name;
  1993. else
  1994. return question.Name;
  1995. }
  1996. if (_allowTxtBlockingReport && (question.Type == DnsResourceRecordType.TXT))
  1997. {
  1998. //return meta data
  1999. string blockedDomain = GetBlockedDomain();
  2000. IReadOnlyList<DnsResourceRecord> answer = new DnsResourceRecord[] { new DnsResourceRecord(question.Name, DnsResourceRecordType.TXT, question.Class, 60, new DnsTXTRecordData("source=blocked-zone; domain=" + blockedDomain)) };
  2001. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NoError, request.Question, answer) { Tag = DnsServerResponseType.Blocked };
  2002. }
  2003. else
  2004. {
  2005. string blockedDomain = null;
  2006. EDnsOption[] options = null;
  2007. if (_allowTxtBlockingReport && (request.EDNS is not null))
  2008. {
  2009. blockedDomain = GetBlockedDomain();
  2010. options = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.Blocked, "source=blocked-zone; domain=" + blockedDomain)) };
  2011. }
  2012. IReadOnlyCollection<DnsARecordData> aRecords;
  2013. IReadOnlyCollection<DnsAAAARecordData> aaaaRecords;
  2014. switch (_blockingType)
  2015. {
  2016. case DnsServerBlockingType.AnyAddress:
  2017. aRecords = _aRecords;
  2018. aaaaRecords = _aaaaRecords;
  2019. break;
  2020. case DnsServerBlockingType.CustomAddress:
  2021. aRecords = _customBlockingARecords;
  2022. aaaaRecords = _customBlockingAAAARecords;
  2023. break;
  2024. case DnsServerBlockingType.NxDomain:
  2025. if (blockedDomain is null)
  2026. blockedDomain = GetBlockedDomain();
  2027. string parentDomain = AuthZoneManager.GetParentZone(blockedDomain);
  2028. if (parentDomain is null)
  2029. parentDomain = string.Empty;
  2030. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NxDomain, request.Question, null, new DnsResourceRecord[] { new DnsResourceRecord(parentDomain, DnsResourceRecordType.SOA, question.Class, 60, _blockedZoneManager.DnsSOARecord) }, null, request.EDNS is null ? ushort.MinValue : _udpPayloadSize, EDnsHeaderFlags.None, options) { Tag = DnsServerResponseType.Blocked };
  2031. default:
  2032. throw new InvalidOperationException();
  2033. }
  2034. IReadOnlyList<DnsResourceRecord> answer;
  2035. IReadOnlyList<DnsResourceRecord> authority = null;
  2036. switch (question.Type)
  2037. {
  2038. case DnsResourceRecordType.A:
  2039. {
  2040. List<DnsResourceRecord> rrList = new List<DnsResourceRecord>(aRecords.Count);
  2041. foreach (DnsARecordData record in aRecords)
  2042. rrList.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.A, question.Class, 60, record));
  2043. answer = rrList;
  2044. }
  2045. break;
  2046. case DnsResourceRecordType.AAAA:
  2047. {
  2048. List<DnsResourceRecord> rrList = new List<DnsResourceRecord>(aaaaRecords.Count);
  2049. foreach (DnsAAAARecordData record in aaaaRecords)
  2050. rrList.Add(new DnsResourceRecord(question.Name, DnsResourceRecordType.AAAA, question.Class, 60, record));
  2051. answer = rrList;
  2052. }
  2053. break;
  2054. default:
  2055. answer = response.Answer;
  2056. authority = response.Authority;
  2057. break;
  2058. }
  2059. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NoError, request.Question, answer, authority, null, request.EDNS is null ? ushort.MinValue : _udpPayloadSize, EDnsHeaderFlags.None, options) { Tag = DnsServerResponseType.Blocked };
  2060. }
  2061. }
  2062. }
  2063. private async Task<DnsDatagram> ProcessRecursiveQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, IReadOnlyList<DnsResourceRecord> conditionalForwarders, bool dnssecValidation, bool cacheRefreshOperation, bool skipDnsAppAuthoritativeRequestHandlers)
  2064. {
  2065. bool inAllowedZone;
  2066. if (cacheRefreshOperation)
  2067. {
  2068. //cache refresh operation should be able to refresh all the records in cache
  2069. //this is since a blocked CNAME record could still be used by an allowed domain name and so must resolve
  2070. inAllowedZone = true;
  2071. }
  2072. else if (!_enableBlocking)
  2073. {
  2074. inAllowedZone = true;
  2075. }
  2076. else
  2077. {
  2078. inAllowedZone = _allowedZoneManager.IsAllowed(request) || _blockListZoneManager.IsAllowed(request);
  2079. if (!inAllowedZone)
  2080. {
  2081. //check in blocked zone and block list zone
  2082. DnsDatagram blockedResponse = ProcessBlockedQuery(request);
  2083. if (blockedResponse is not null)
  2084. return blockedResponse;
  2085. }
  2086. }
  2087. DnsDatagram response = await RecursiveResolveAsync(request, remoteEP, conditionalForwarders, dnssecValidation, false, cacheRefreshOperation, skipDnsAppAuthoritativeRequestHandlers);
  2088. if (response.Answer.Count > 0)
  2089. {
  2090. DnsResourceRecordType questionType = request.Question[0].Type;
  2091. DnsResourceRecord lastRR = response.GetLastAnswerRecord();
  2092. if ((lastRR.Type != questionType) && (lastRR.Type == DnsResourceRecordType.CNAME) && (questionType != DnsResourceRecordType.ANY))
  2093. response = await ProcessCNAMEAsync(request, remoteEP, response, true, protocol, cacheRefreshOperation, skipDnsAppAuthoritativeRequestHandlers);
  2094. if (!inAllowedZone)
  2095. {
  2096. //check for CNAME cloaking
  2097. for (int i = 0; i < response.Answer.Count; i++)
  2098. {
  2099. DnsResourceRecord record = response.Answer[i];
  2100. if (record.Type != DnsResourceRecordType.CNAME)
  2101. break; //no further CNAME records exists
  2102. DnsDatagram newRequest = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, true, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { new DnsQuestionRecord((record.RDATA as DnsCNAMERecordData).Domain, request.Question[0].Type, request.Question[0].Class) }, null, null, null, _udpPayloadSize);
  2103. //check allowed zone
  2104. inAllowedZone = _allowedZoneManager.IsAllowed(newRequest) || _blockListZoneManager.IsAllowed(newRequest);
  2105. if (inAllowedZone)
  2106. break; //CNAME is in allowed zone
  2107. //check blocked zone and block list zone
  2108. DnsDatagram blockedResponse = ProcessBlockedQuery(newRequest);
  2109. if (blockedResponse is not null)
  2110. {
  2111. //found cname cloaking
  2112. List<DnsResourceRecord> answer = new List<DnsResourceRecord>();
  2113. //copy current and previous CNAME records
  2114. for (int j = 0; j <= i; j++)
  2115. answer.Add(response.Answer[j]);
  2116. //copy last response answers
  2117. answer.AddRange(blockedResponse.Answer);
  2118. //include blocked response additional section to pass on Extended DNS Errors
  2119. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, true, true, false, false, DnsResponseCode.NoError, request.Question, answer, blockedResponse.Authority, blockedResponse.Additional) { Tag = blockedResponse.Tag };
  2120. }
  2121. }
  2122. }
  2123. }
  2124. if (response.Tag is null)
  2125. {
  2126. if (response.IsBlockedResponse())
  2127. response.Tag = DnsServerResponseType.UpstreamBlocked;
  2128. }
  2129. else if ((DnsServerResponseType)response.Tag == DnsServerResponseType.Cached)
  2130. {
  2131. if (response.IsBlockedResponse())
  2132. response.Tag = DnsServerResponseType.CacheBlocked;
  2133. }
  2134. return response;
  2135. }
  2136. private async Task<DnsDatagram> RecursiveResolveAsync(DnsDatagram request, IPEndPoint remoteEP, IReadOnlyList<DnsResourceRecord> conditionalForwarders, bool dnssecValidation, bool cachePrefetchOperation, bool cacheRefreshOperation, bool skipDnsAppAuthoritativeRequestHandlers)
  2137. {
  2138. DnsQuestionRecord question = request.Question[0];
  2139. NetworkAddress eDnsClientSubnet = null;
  2140. if (_eDnsClientSubnet && CacheZone.IsTypeSupportedForEDnsClientSubnet(question.Type))
  2141. {
  2142. EDnsClientSubnetOptionData requestECS = request.GetEDnsClientSubnetOption();
  2143. if (requestECS is null)
  2144. {
  2145. if (!NetUtilities.IsPrivateIP(remoteEP.Address))
  2146. {
  2147. //set shadow ECS option
  2148. switch (remoteEP.AddressFamily)
  2149. {
  2150. case AddressFamily.InterNetwork:
  2151. eDnsClientSubnet = new NetworkAddress(remoteEP.Address, _eDnsClientSubnetIPv4PrefixLength);
  2152. request.SetShadowEDnsClientSubnetOption(eDnsClientSubnet);
  2153. break;
  2154. case AddressFamily.InterNetworkV6:
  2155. eDnsClientSubnet = new NetworkAddress(remoteEP.Address, _eDnsClientSubnetIPv6PrefixLength);
  2156. request.SetShadowEDnsClientSubnetOption(eDnsClientSubnet);
  2157. break;
  2158. default:
  2159. request.ShadowHideEDnsClientSubnetOption();
  2160. break;
  2161. }
  2162. }
  2163. }
  2164. else if ((requestECS.Family != EDnsClientSubnetAddressFamily.IPv4) && (requestECS.Family != EDnsClientSubnetAddressFamily.IPv6))
  2165. {
  2166. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, true, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  2167. }
  2168. else if ((requestECS.SourcePrefixLength == 0) || NetUtilities.IsPrivateIP(requestECS.Address))
  2169. {
  2170. //disable ECS option
  2171. request.ShadowHideEDnsClientSubnetOption();
  2172. }
  2173. else
  2174. {
  2175. //use ECS from client request
  2176. switch (requestECS.Family)
  2177. {
  2178. case EDnsClientSubnetAddressFamily.IPv4:
  2179. eDnsClientSubnet = new NetworkAddress(requestECS.Address, Math.Min(requestECS.SourcePrefixLength, _eDnsClientSubnetIPv4PrefixLength));
  2180. request.SetShadowEDnsClientSubnetOption(eDnsClientSubnet);
  2181. break;
  2182. case EDnsClientSubnetAddressFamily.IPv6:
  2183. eDnsClientSubnet = new NetworkAddress(requestECS.Address, Math.Min(requestECS.SourcePrefixLength, _eDnsClientSubnetIPv6PrefixLength));
  2184. request.SetShadowEDnsClientSubnetOption(eDnsClientSubnet);
  2185. break;
  2186. }
  2187. }
  2188. }
  2189. else
  2190. {
  2191. //hide ECS option
  2192. request.ShadowHideEDnsClientSubnetOption();
  2193. }
  2194. if (!cachePrefetchOperation && !cacheRefreshOperation)
  2195. {
  2196. //query cache zone to see if answer available
  2197. DnsDatagram cacheResponse = QueryCache(request, false);
  2198. if (cacheResponse is not null)
  2199. {
  2200. if (_cachePrefetchTrigger > 0)
  2201. {
  2202. //inspect response TTL values to decide if prefetch trigger is needed
  2203. foreach (DnsResourceRecord answer in cacheResponse.Answer)
  2204. {
  2205. if ((answer.OriginalTtlValue >= _cachePrefetchEligibility) && (answer.TTL <= _cachePrefetchTrigger))
  2206. {
  2207. //trigger prefetch async
  2208. _ = PrefetchCacheAsync(request, remoteEP, conditionalForwarders);
  2209. break;
  2210. }
  2211. }
  2212. }
  2213. return cacheResponse;
  2214. }
  2215. }
  2216. //recursion with locking
  2217. TaskCompletionSource<RecursiveResolveResponse> resolverTaskCompletionSource = new TaskCompletionSource<RecursiveResolveResponse>();
  2218. Task<RecursiveResolveResponse> resolverTask = _resolverTasks.GetOrAdd(GetResolverQueryKey(question, eDnsClientSubnet), resolverTaskCompletionSource.Task);
  2219. if (resolverTask.Equals(resolverTaskCompletionSource.Task))
  2220. {
  2221. //got new resolver task added so question is not being resolved; do recursive resolution in another task on resolver thread pool
  2222. _ = Task.Factory.StartNew(delegate ()
  2223. {
  2224. return RecursiveResolveAsync(question, eDnsClientSubnet, conditionalForwarders, dnssecValidation, cachePrefetchOperation, cacheRefreshOperation, skipDnsAppAuthoritativeRequestHandlers, resolverTaskCompletionSource);
  2225. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _resolverTaskScheduler);
  2226. }
  2227. //request is being recursively resolved by another thread
  2228. if (cachePrefetchOperation)
  2229. return null; //return null as prefetch worker thread does not need valid response and thus does not need to wait
  2230. DateTime resolverWaitStartTime = DateTime.UtcNow;
  2231. //wait till short timeout for response
  2232. if (await Task.WhenAny(resolverTask, Task.Delay(SERVE_STALE_WAIT_TIME)) == resolverTask) //1.8 sec wait as per draft-ietf-dnsop-serve-stale-04
  2233. {
  2234. //resolver signaled
  2235. RecursiveResolveResponse response = await resolverTask;
  2236. if (response is not null)
  2237. return PrepareRecursiveResolveResponse(request, response);
  2238. //resolver had exception and no stale record was found
  2239. }
  2240. else
  2241. {
  2242. //wait timed out
  2243. if (_serveStale)
  2244. {
  2245. //query cache zone to return stale answer (if available) as per draft-ietf-dnsop-serve-stale-04
  2246. DnsDatagram staleResponse = QueryCache(request, true);
  2247. if (staleResponse is not null)
  2248. return staleResponse;
  2249. }
  2250. //wait till full timeout before responding as ServerFailure
  2251. int timeout = Convert.ToInt32(_clientTimeout - (DateTime.UtcNow - resolverWaitStartTime).TotalMilliseconds);
  2252. if (timeout > 0)
  2253. {
  2254. if (await Task.WhenAny(resolverTask, Task.Delay(timeout)) == resolverTask)
  2255. {
  2256. //resolver signaled
  2257. RecursiveResolveResponse response = await resolverTask;
  2258. if (response is not null)
  2259. return PrepareRecursiveResolveResponse(request, response);
  2260. }
  2261. //no response available from resolver or resolver had exception and no stale record was found
  2262. }
  2263. }
  2264. //no response available; respond with ServerFailure
  2265. EDnsOption[] options = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.Other, "Waiting for resolver")) };
  2266. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, true, false, false, DnsResponseCode.ServerFailure, request.Question, null, null, null, _udpPayloadSize, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, options);
  2267. }
  2268. private async Task RecursiveResolveAsync(DnsQuestionRecord question, NetworkAddress eDnsClientSubnet, IReadOnlyList<DnsResourceRecord> conditionalForwarders, bool dnssecValidation, bool cachePrefetchOperation, bool cacheRefreshOperation, bool skipDnsAppAuthoritativeRequestHandlers, TaskCompletionSource<RecursiveResolveResponse> taskCompletionSource)
  2269. {
  2270. try
  2271. {
  2272. //recursive resolve and update cache
  2273. IDnsCache dnsCache;
  2274. if (cachePrefetchOperation || cacheRefreshOperation)
  2275. dnsCache = new ResolverPrefetchDnsCache(_dnsApplicationManager, _authZoneManager, _cacheZoneManager, _log, skipDnsAppAuthoritativeRequestHandlers, question);
  2276. else if (skipDnsAppAuthoritativeRequestHandlers)
  2277. dnsCache = new ResolverDnsCache(_dnsApplicationManager, _authZoneManager, _cacheZoneManager, _log, true);
  2278. else
  2279. dnsCache = _dnsCache;
  2280. //check for this-server
  2281. if ((conditionalForwarders is not null) && (conditionalForwarders.Count == 1) && (conditionalForwarders[0].RDATA is DnsForwarderRecordData fwd) && fwd.Forwarder.Equals("this-server", StringComparison.OrdinalIgnoreCase))
  2282. {
  2283. //resolve directly with DNSSEC validation preference
  2284. conditionalForwarders = null;
  2285. dnssecValidation = fwd.DnssecValidation;
  2286. }
  2287. DnsDatagram response;
  2288. if ((conditionalForwarders is not null) && (conditionalForwarders.Count > 0))
  2289. {
  2290. //check for forwarder name server resolution
  2291. foreach (DnsResourceRecord conditionalForwarder in conditionalForwarders)
  2292. {
  2293. if (conditionalForwarder.Type != DnsResourceRecordType.FWD)
  2294. continue;
  2295. DnsForwarderRecordData forwarder = conditionalForwarder.RDATA as DnsForwarderRecordData;
  2296. if (forwarder.Forwarder.Equals("this-server", StringComparison.OrdinalIgnoreCase))
  2297. continue;
  2298. NetProxy proxy = forwarder.Proxy;
  2299. if (proxy is null)
  2300. proxy = _proxy;
  2301. if (proxy is null)
  2302. {
  2303. //recursive resolve name server when proxy is null else let proxy resolve it
  2304. if (forwarder.NameServer.IsIPEndPointStale) //refresh forwarder IPEndPoint if stale
  2305. await forwarder.NameServer.RecursiveResolveIPAddressAsync(dnsCache, null, _preferIPv6, _udpPayloadSize, _randomizeName, _resolverRetries, _resolverTimeout);
  2306. }
  2307. }
  2308. if (conditionalForwarders.Count == 1)
  2309. {
  2310. DnsResourceRecord conditionalForwarder = conditionalForwarders[0];
  2311. response = await ConditionalForwarderResolveAsync(question, eDnsClientSubnet, dnsCache, conditionalForwarder.RDATA as DnsForwarderRecordData, conditionalForwarder.Name);
  2312. }
  2313. else
  2314. {
  2315. using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource())
  2316. {
  2317. List<Task<DnsDatagram>> tasks = new List<Task<DnsDatagram>>(conditionalForwarders.Count);
  2318. //start worker tasks
  2319. foreach (DnsResourceRecord conditionalForwarder in conditionalForwarders)
  2320. {
  2321. if (conditionalForwarder.Type != DnsResourceRecordType.FWD)
  2322. continue;
  2323. DnsForwarderRecordData forwarder = conditionalForwarder.RDATA as DnsForwarderRecordData;
  2324. if (forwarder.Forwarder.Equals("this-server", StringComparison.OrdinalIgnoreCase))
  2325. continue;
  2326. tasks.Add(Task.Factory.StartNew(delegate ()
  2327. {
  2328. return ConditionalForwarderResolveAsync(question, eDnsClientSubnet, dnsCache, forwarder, conditionalForwarder.Name, cancellationTokenSource.Token);
  2329. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Current).Unwrap());
  2330. }
  2331. //wait for first positive response, or for all tasks to fault
  2332. response = null;
  2333. DnsDatagram lastResponse = null;
  2334. Exception lastException = null;
  2335. while (tasks.Count > 0)
  2336. {
  2337. Task<DnsDatagram> completedTask = await Task.WhenAny(tasks);
  2338. if (completedTask.Status == TaskStatus.RanToCompletion)
  2339. {
  2340. //resolver task complete
  2341. DnsDatagram taskResponse = await completedTask; //await to get response
  2342. bool foundResponse = false;
  2343. switch (taskResponse.RCODE)
  2344. {
  2345. case DnsResponseCode.NoError:
  2346. case DnsResponseCode.NxDomain:
  2347. case DnsResponseCode.YXDomain:
  2348. cancellationTokenSource.Cancel(); //to stop other resolver tasks
  2349. response = taskResponse;
  2350. foundResponse = true;
  2351. break;
  2352. default:
  2353. //keep response
  2354. lastResponse = taskResponse;
  2355. break;
  2356. }
  2357. if (foundResponse)
  2358. break;
  2359. }
  2360. tasks.Remove(completedTask);
  2361. lastException = completedTask.Exception;
  2362. if (lastException is AggregateException)
  2363. lastException = lastException.InnerException;
  2364. }
  2365. if (response is null)
  2366. {
  2367. if (lastResponse is not null)
  2368. response = lastResponse;
  2369. else if (lastException is not null)
  2370. ExceptionDispatchInfo.Capture(lastException).Throw();
  2371. else
  2372. throw new InvalidOperationException();
  2373. }
  2374. }
  2375. }
  2376. }
  2377. else if ((conditionalForwarders is null) && (_forwarders is not null) && (_forwarders.Count > 0))
  2378. {
  2379. //use forwarders
  2380. if (_proxy is null)
  2381. {
  2382. //recursive resolve name server when proxy is null else let proxy resolve it
  2383. foreach (NameServerAddress nameServerAddress in _forwarders)
  2384. {
  2385. if (nameServerAddress.IsIPEndPointStale) //refresh forwarder IPEndPoint if stale
  2386. await nameServerAddress.RecursiveResolveIPAddressAsync(dnsCache, null, _preferIPv6, _udpPayloadSize, _randomizeName, _resolverRetries, _resolverTimeout);
  2387. }
  2388. }
  2389. //query forwarders and update cache
  2390. DnsClient dnsClient = new DnsClient(_forwarders);
  2391. dnsClient.Cache = dnsCache;
  2392. dnsClient.Proxy = _proxy;
  2393. dnsClient.PreferIPv6 = _preferIPv6;
  2394. dnsClient.RandomizeName = _randomizeName;
  2395. dnsClient.Retries = _forwarderRetries;
  2396. dnsClient.Timeout = _forwarderTimeout;
  2397. dnsClient.Concurrency = _forwarderConcurrency;
  2398. dnsClient.UdpPayloadSize = _udpPayloadSize;
  2399. dnsClient.DnssecValidation = dnssecValidation;
  2400. dnsClient.EDnsClientSubnet = eDnsClientSubnet;
  2401. dnsClient.ConditionalForwardingZoneCut = question.Name; //adding zone cut to allow CNAME domains to be resolved independently to handle cases when private/forwarder zone is configured for them
  2402. response = await dnsClient.ResolveAsync(question);
  2403. }
  2404. else
  2405. {
  2406. //do recursive resolution
  2407. response = await DnsClient.RecursiveResolveAsync(question, dnsCache, _proxy, _preferIPv6, _udpPayloadSize, _randomizeName, _qnameMinimization, _nsRevalidation, dnssecValidation, eDnsClientSubnet, _resolverRetries, _resolverTimeout, _resolverMaxStackCount, true, true);
  2408. }
  2409. switch (response.RCODE)
  2410. {
  2411. case DnsResponseCode.NoError:
  2412. case DnsResponseCode.NxDomain:
  2413. case DnsResponseCode.YXDomain:
  2414. taskCompletionSource.SetResult(new RecursiveResolveResponse(response, response));
  2415. break;
  2416. default:
  2417. throw new DnsServerException("DNS Server received a response with RCODE=" + response.RCODE.ToString() + " from: " + (response.Metadata is null ? "unknown" : response.Metadata.NameServer));
  2418. }
  2419. }
  2420. catch (Exception ex)
  2421. {
  2422. if (_log is not null)
  2423. {
  2424. string strForwarders = null;
  2425. if ((conditionalForwarders is not null) && (conditionalForwarders.Count > 0))
  2426. {
  2427. foreach (DnsResourceRecord conditionalForwarder in conditionalForwarders)
  2428. {
  2429. NameServerAddress nameServer = (conditionalForwarder.RDATA as DnsForwarderRecordData).NameServer;
  2430. if (strForwarders is null)
  2431. strForwarders = nameServer.ToString();
  2432. else
  2433. strForwarders += ", " + nameServer.ToString();
  2434. }
  2435. }
  2436. else if ((_forwarders is not null) && (_forwarders.Count > 0))
  2437. {
  2438. foreach (NameServerAddress nameServer in _forwarders)
  2439. {
  2440. if (strForwarders is null)
  2441. strForwarders = nameServer.ToString();
  2442. else
  2443. strForwarders += ", " + nameServer.ToString();
  2444. }
  2445. }
  2446. _log.Write("DNS Server failed to resolve the request with QNAME: " + question.Name + "; QTYPE: " + question.Type.ToString() + "; QCLASS: " + question.Class.ToString() + (strForwarders is null ? "" : "; Forwarders: " + strForwarders) + ";\r\n" + ex.ToString());
  2447. }
  2448. if (_serveStale)
  2449. {
  2450. //fetch stale record
  2451. DnsDatagram cacheRequest = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, true, false, false, dnssecValidation, DnsResponseCode.NoError, new DnsQuestionRecord[] { question }, null, null, null, _udpPayloadSize, dnssecValidation ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, EDnsClientSubnetOptionData.GetEDnsClientSubnetOption(eDnsClientSubnet));
  2452. DnsDatagram staleResponse = QueryCache(cacheRequest, true);
  2453. if (staleResponse is not null)
  2454. {
  2455. //signal stale response
  2456. if (!dnssecValidation || staleResponse.AuthenticData)
  2457. {
  2458. taskCompletionSource.SetResult(new RecursiveResolveResponse(staleResponse, staleResponse));
  2459. }
  2460. else
  2461. {
  2462. DnsDatagram failureResponse = new DnsDatagram(0, true, DnsOpcode.StandardQuery, false, false, true, true, false, dnssecValidation, DnsResponseCode.ServerFailure, new DnsQuestionRecord[] { question });
  2463. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, staleResponse));
  2464. }
  2465. return;
  2466. }
  2467. }
  2468. //signal failure response to release waiting tasks
  2469. if (ex is DnsClientResponseDnssecValidationException ex2)
  2470. {
  2471. List<EDnsOption> options;
  2472. if (ex2.Response.DnsClientExtendedErrors.Count > 0)
  2473. {
  2474. options = new List<EDnsOption>(ex2.Response.DnsClientExtendedErrors.Count);
  2475. foreach (EDnsExtendedDnsErrorOptionData dnsError in ex2.Response.DnsClientExtendedErrors)
  2476. options.Add(new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, dnsError));
  2477. }
  2478. else
  2479. {
  2480. options = null;
  2481. }
  2482. DnsDatagram failureResponse = new DnsDatagram(0, true, DnsOpcode.StandardQuery, false, false, true, true, false, dnssecValidation, DnsResponseCode.ServerFailure, new DnsQuestionRecord[] { question }, null, null, null, _udpPayloadSize, EDnsHeaderFlags.DNSSEC_OK, options);
  2483. if ((ex2.Response.Question.Count > 0) && ex2.Response.Question[0].Equals(question))
  2484. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, ex2.Response));
  2485. else
  2486. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, failureResponse));
  2487. }
  2488. else if (ex is DnsClientNoResponseException ex3)
  2489. {
  2490. IReadOnlyList<EDnsOption> options;
  2491. if (ex.InnerException is SocketException ex3a)
  2492. {
  2493. if (ex3a.SocketErrorCode == SocketError.TimedOut)
  2494. options = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NoReachableAuthority, "Request timed out")) };
  2495. else
  2496. options = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NetworkError, "Socket error: " + ex3a.SocketErrorCode.ToString())) };
  2497. }
  2498. else
  2499. {
  2500. options = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NoReachableAuthority, "No response from name servers for " + question.ToString())) };
  2501. }
  2502. DnsDatagram failureResponse = new DnsDatagram(0, true, DnsOpcode.StandardQuery, false, false, true, true, false, dnssecValidation, DnsResponseCode.ServerFailure, new DnsQuestionRecord[] { question }, null, null, null, _udpPayloadSize, dnssecValidation ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, options);
  2503. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, failureResponse));
  2504. }
  2505. else if (ex is SocketException ex4)
  2506. {
  2507. IReadOnlyList<EDnsOption> options;
  2508. if (ex4.SocketErrorCode == SocketError.TimedOut)
  2509. options = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NoReachableAuthority, "Request timed out")) };
  2510. else
  2511. options = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NetworkError, "Socket error: " + ex4.SocketErrorCode.ToString())) };
  2512. DnsDatagram failureResponse = new DnsDatagram(0, true, DnsOpcode.StandardQuery, false, false, true, true, false, dnssecValidation, DnsResponseCode.ServerFailure, new DnsQuestionRecord[] { question }, null, null, null, _udpPayloadSize, dnssecValidation ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, options);
  2513. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, failureResponse));
  2514. }
  2515. else if (ex is IOException ex5)
  2516. {
  2517. IReadOnlyList<EDnsOption> options;
  2518. if (ex5.InnerException is SocketException ex5a)
  2519. {
  2520. if (ex5a.SocketErrorCode == SocketError.TimedOut)
  2521. options = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NoReachableAuthority, "Request timed out")) };
  2522. else
  2523. options = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NetworkError, "Socket error: " + ex5a.SocketErrorCode.ToString())) };
  2524. }
  2525. else
  2526. {
  2527. options = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NetworkError, "IO error: " + ex5.Message)) };
  2528. }
  2529. DnsDatagram failureResponse = new DnsDatagram(0, true, DnsOpcode.StandardQuery, false, false, true, true, false, dnssecValidation, DnsResponseCode.ServerFailure, new DnsQuestionRecord[] { question }, null, null, null, _udpPayloadSize, dnssecValidation ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, options);
  2530. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, failureResponse));
  2531. }
  2532. else
  2533. {
  2534. IReadOnlyList<EDnsOption> options = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.Other, "Server exception")) };
  2535. DnsDatagram failureResponse = new DnsDatagram(0, true, DnsOpcode.StandardQuery, false, false, true, true, false, dnssecValidation, DnsResponseCode.ServerFailure, new DnsQuestionRecord[] { question }, null, null, null, _udpPayloadSize, dnssecValidation ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, options);
  2536. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, failureResponse));
  2537. }
  2538. }
  2539. finally
  2540. {
  2541. _resolverTasks.TryRemove(GetResolverQueryKey(question, eDnsClientSubnet), out _);
  2542. }
  2543. }
  2544. private Task<DnsDatagram> ConditionalForwarderResolveAsync(DnsQuestionRecord question, NetworkAddress eDnsClientSubnet, IDnsCache dnsCache, DnsForwarderRecordData forwarder, string conditionalForwardingZoneCut, CancellationToken cancellationToken = default)
  2545. {
  2546. NetProxy proxy = forwarder.Proxy;
  2547. if (proxy is null)
  2548. proxy = _proxy;
  2549. DnsClient dnsClient = new DnsClient(forwarder.NameServer);
  2550. dnsClient.Cache = dnsCache;
  2551. dnsClient.Proxy = proxy;
  2552. dnsClient.PreferIPv6 = _preferIPv6;
  2553. dnsClient.RandomizeName = _randomizeName;
  2554. dnsClient.Retries = _forwarderRetries;
  2555. dnsClient.Timeout = _forwarderTimeout;
  2556. dnsClient.Concurrency = _forwarderConcurrency;
  2557. dnsClient.UdpPayloadSize = _udpPayloadSize;
  2558. dnsClient.DnssecValidation = forwarder.DnssecValidation;
  2559. dnsClient.EDnsClientSubnet = eDnsClientSubnet;
  2560. dnsClient.ConditionalForwardingZoneCut = conditionalForwardingZoneCut;
  2561. return dnsClient.ResolveAsync(question, cancellationToken);
  2562. }
  2563. private DnsDatagram PrepareRecursiveResolveResponse(DnsDatagram request, RecursiveResolveResponse resolveResponse)
  2564. {
  2565. //get a tailored response for the request
  2566. bool dnssecOk = request.DnssecOk;
  2567. if (dnssecOk && request.CheckingDisabled)
  2568. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, true, true, resolveResponse.CheckingDisabledResponse.AuthenticData, resolveResponse.CheckingDisabledResponse.CheckingDisabled, resolveResponse.CheckingDisabledResponse.RCODE, request.Question, resolveResponse.CheckingDisabledResponse.Answer, resolveResponse.CheckingDisabledResponse.Authority, RemoveOPTFromAdditional(resolveResponse.CheckingDisabledResponse.Additional, true), _udpPayloadSize, EDnsHeaderFlags.DNSSEC_OK, resolveResponse.CheckingDisabledResponse.EDNS?.Options);
  2569. DnsDatagram response = resolveResponse.Response;
  2570. IReadOnlyList<DnsResourceRecord> answer = response.Answer;
  2571. IReadOnlyList<DnsResourceRecord> authority = response.Authority;
  2572. IReadOnlyList<DnsResourceRecord> additional = response.Additional;
  2573. //answer section checks
  2574. if (!dnssecOk && (answer.Count > 0) && (response.Question[0].Type != DnsResourceRecordType.ANY))
  2575. {
  2576. //remove RRSIGs from answer
  2577. bool foundRRSIG = false;
  2578. foreach (DnsResourceRecord record in answer)
  2579. {
  2580. if (record.Type == DnsResourceRecordType.RRSIG)
  2581. {
  2582. foundRRSIG = true;
  2583. break;
  2584. }
  2585. }
  2586. if (foundRRSIG)
  2587. {
  2588. List<DnsResourceRecord> newAnswer = new List<DnsResourceRecord>(answer.Count);
  2589. foreach (DnsResourceRecord record in answer)
  2590. {
  2591. if (record.Type == DnsResourceRecordType.RRSIG)
  2592. continue;
  2593. newAnswer.Add(record);
  2594. }
  2595. answer = newAnswer;
  2596. }
  2597. }
  2598. //authority section checks
  2599. if (!dnssecOk && (authority.Count > 0))
  2600. {
  2601. //remove DNSSEC records
  2602. bool foundDnssecRecords = false;
  2603. bool foundOther = false;
  2604. foreach (DnsResourceRecord record in authority)
  2605. {
  2606. switch (record.Type)
  2607. {
  2608. case DnsResourceRecordType.DS:
  2609. case DnsResourceRecordType.DNSKEY:
  2610. case DnsResourceRecordType.RRSIG:
  2611. case DnsResourceRecordType.NSEC:
  2612. case DnsResourceRecordType.NSEC3:
  2613. foundDnssecRecords = true;
  2614. break;
  2615. default:
  2616. foundOther = true;
  2617. break;
  2618. }
  2619. }
  2620. if (foundDnssecRecords)
  2621. {
  2622. if (foundOther)
  2623. {
  2624. List<DnsResourceRecord> newAuthority = new List<DnsResourceRecord>(2);
  2625. foreach (DnsResourceRecord record in authority)
  2626. {
  2627. switch (record.Type)
  2628. {
  2629. case DnsResourceRecordType.DS:
  2630. case DnsResourceRecordType.DNSKEY:
  2631. case DnsResourceRecordType.RRSIG:
  2632. case DnsResourceRecordType.NSEC:
  2633. case DnsResourceRecordType.NSEC3:
  2634. break;
  2635. default:
  2636. newAuthority.Add(record);
  2637. break;
  2638. }
  2639. }
  2640. authority = newAuthority;
  2641. }
  2642. else
  2643. {
  2644. authority = Array.Empty<DnsResourceRecord>();
  2645. }
  2646. }
  2647. }
  2648. //additional section checks
  2649. if (additional.Count > 0)
  2650. {
  2651. if ((request.EDNS is not null) && (response.EDNS is not null) && ((response.EDNS.Options.Count > 0) || (response.DnsClientExtendedErrors.Count > 0)))
  2652. {
  2653. //copy options as new OPT and keep other records
  2654. List<DnsResourceRecord> newAdditional = new List<DnsResourceRecord>(additional.Count);
  2655. foreach (DnsResourceRecord record in additional)
  2656. {
  2657. switch (record.Type)
  2658. {
  2659. case DnsResourceRecordType.OPT:
  2660. continue;
  2661. case DnsResourceRecordType.RRSIG:
  2662. case DnsResourceRecordType.DNSKEY:
  2663. if (dnssecOk)
  2664. break;
  2665. continue;
  2666. }
  2667. newAdditional.Add(record);
  2668. }
  2669. IReadOnlyList<EDnsOption> options;
  2670. if (response.GetEDnsClientSubnetOption(true) is not null)
  2671. {
  2672. //response contains ECS
  2673. if ((request.GetEDnsClientSubnetOption(true) is not null) && CacheZone.IsTypeSupportedForEDnsClientSubnet(request.Question[0].Type))
  2674. {
  2675. //request has ECS and type is supported; keep ECS in response
  2676. options = response.EDNS.Options;
  2677. }
  2678. else
  2679. {
  2680. //cache does not support the qtype so remove ECS from response
  2681. if (response.EDNS.Options.Count == 1)
  2682. {
  2683. options = Array.Empty<EDnsOption>();
  2684. }
  2685. else
  2686. {
  2687. List<EDnsOption> newOptions = new List<EDnsOption>(response.EDNS.Options.Count);
  2688. foreach (EDnsOption option in response.EDNS.Options)
  2689. {
  2690. if (option.Code != EDnsOptionCode.EDNS_CLIENT_SUBNET)
  2691. newOptions.Add(option);
  2692. }
  2693. options = newOptions;
  2694. }
  2695. }
  2696. }
  2697. else
  2698. {
  2699. options = response.EDNS.Options;
  2700. }
  2701. if (response.DnsClientExtendedErrors.Count > 0)
  2702. {
  2703. //add dns client extended errors
  2704. List<EDnsOption> newOptions = new List<EDnsOption>(options.Count + response.DnsClientExtendedErrors.Count);
  2705. newOptions.AddRange(options);
  2706. foreach (EDnsExtendedDnsErrorOptionData ee in response.DnsClientExtendedErrors)
  2707. newOptions.Add(new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, ee));
  2708. options = newOptions;
  2709. }
  2710. newAdditional.Add(DnsDatagramEdns.GetOPTFor(_udpPayloadSize, response.RCODE, 0, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, options));
  2711. additional = newAdditional;
  2712. }
  2713. else if (response.EDNS is not null)
  2714. {
  2715. //remove OPT from additional
  2716. additional = RemoveOPTFromAdditional(additional, dnssecOk);
  2717. }
  2718. }
  2719. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, true, true, response.AuthenticData, response.CheckingDisabled, response.RCODE, request.Question, answer, authority, additional);
  2720. }
  2721. private static IReadOnlyList<DnsResourceRecord> RemoveOPTFromAdditional(IReadOnlyList<DnsResourceRecord> additional, bool dnssecOk)
  2722. {
  2723. if (additional.Count == 0)
  2724. return additional;
  2725. if ((additional.Count == 1) && (additional[0].Type == DnsResourceRecordType.OPT))
  2726. return Array.Empty<DnsResourceRecord>();
  2727. List<DnsResourceRecord> newAdditional = new List<DnsResourceRecord>(additional.Count - 1);
  2728. foreach (DnsResourceRecord record in additional)
  2729. {
  2730. switch (record.Type)
  2731. {
  2732. case DnsResourceRecordType.OPT:
  2733. continue;
  2734. case DnsResourceRecordType.RRSIG:
  2735. case DnsResourceRecordType.DNSKEY:
  2736. if (dnssecOk)
  2737. break;
  2738. continue;
  2739. }
  2740. newAdditional.Add(record);
  2741. }
  2742. return newAdditional;
  2743. }
  2744. private static string GetResolverQueryKey(DnsQuestionRecord question, NetworkAddress eDnsClientSubnet)
  2745. {
  2746. if (eDnsClientSubnet is null)
  2747. return question.ToString();
  2748. return question.ToString() + " " + eDnsClientSubnet.ToString();
  2749. }
  2750. private DnsDatagram QueryCache(DnsDatagram request, bool serveStaleAndResetExpiry)
  2751. {
  2752. DnsDatagram cacheResponse = _cacheZoneManager.Query(request, serveStaleAndResetExpiry);
  2753. if (cacheResponse is not null)
  2754. {
  2755. if ((cacheResponse.RCODE != DnsResponseCode.NoError) || (cacheResponse.Answer.Count > 0) || (cacheResponse.Authority.Count == 0) || cacheResponse.IsFirstAuthoritySOA())
  2756. {
  2757. cacheResponse.Tag = DnsServerResponseType.Cached;
  2758. return cacheResponse;
  2759. }
  2760. }
  2761. return null;
  2762. }
  2763. private async Task PrefetchCacheAsync(DnsDatagram request, IPEndPoint remoteEP, IReadOnlyList<DnsResourceRecord> conditionalForwarders)
  2764. {
  2765. try
  2766. {
  2767. await RecursiveResolveAsync(request, remoteEP, conditionalForwarders, _dnssecValidation, true, false, false);
  2768. }
  2769. catch (Exception ex)
  2770. {
  2771. _log?.Write(ex);
  2772. }
  2773. }
  2774. private async Task RefreshCacheAsync(IList<CacheRefreshSample> cacheRefreshSampleList, CacheRefreshSample sample, int sampleQuestionIndex)
  2775. {
  2776. try
  2777. {
  2778. //refresh cache
  2779. DnsDatagram request = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, true, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { sample.SampleQuestion });
  2780. DnsDatagram response = await ProcessRecursiveQueryAsync(request, IPENDPOINT_ANY_0, DnsTransportProtocol.Udp, sample.ConditionalForwarders, _dnssecValidation, true, false);
  2781. bool addBackToSampleList = false;
  2782. DateTime utcNow = DateTime.UtcNow;
  2783. foreach (DnsResourceRecord answer in response.Answer)
  2784. {
  2785. if ((answer.OriginalTtlValue >= _cachePrefetchEligibility) && (utcNow.AddSeconds(answer.TTL) < _cachePrefetchSamplingTimerTriggersOn))
  2786. {
  2787. //answer expires before next sampling so add back to the list to allow refreshing it
  2788. addBackToSampleList = true;
  2789. break;
  2790. }
  2791. }
  2792. if (addBackToSampleList)
  2793. cacheRefreshSampleList[sampleQuestionIndex] = sample; //put back into sample list to allow refreshing it again
  2794. }
  2795. catch (Exception ex)
  2796. {
  2797. _log?.Write(ex);
  2798. cacheRefreshSampleList[sampleQuestionIndex] = sample; //put back into sample list to allow refreshing it again
  2799. }
  2800. }
  2801. private DnsQuestionRecord GetCacheRefreshNeededQuery(DnsQuestionRecord question, int trigger)
  2802. {
  2803. int queryCount = 0;
  2804. while (true)
  2805. {
  2806. DnsDatagram cacheResponse = QueryCache(new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, true, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { question }), false);
  2807. if (cacheResponse is null)
  2808. return question; //cache expired so refresh question
  2809. if (cacheResponse.Answer.Count == 0)
  2810. return null; //dont refresh empty responses
  2811. //inspect response TTL values to decide if refresh is needed
  2812. foreach (DnsResourceRecord answer in cacheResponse.Answer)
  2813. {
  2814. if ((answer.OriginalTtlValue >= _cachePrefetchEligibility) && (answer.TTL <= trigger))
  2815. return question; //TTL eligible and less than trigger so refresh question
  2816. }
  2817. DnsResourceRecord lastRR = cacheResponse.GetLastAnswerRecord();
  2818. if (lastRR.Type == question.Type)
  2819. return null; //answer was resolved
  2820. if (lastRR.Type != DnsResourceRecordType.CNAME)
  2821. return null; //invalid response so ignore question
  2822. queryCount++;
  2823. if (queryCount >= MAX_CNAME_HOPS)
  2824. return null; //too many hops so ignore question
  2825. //follow CNAME chain to inspect TTL further
  2826. question = new DnsQuestionRecord((lastRR.RDATA as DnsCNAMERecordData).Domain, question.Type, question.Class);
  2827. }
  2828. }
  2829. private bool IsCacheRefreshNeeded(DnsQuestionRecord question, int trigger)
  2830. {
  2831. DnsDatagram cacheResponse = QueryCache(new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, true, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { question }), false);
  2832. if (cacheResponse is null)
  2833. return true; //cache expired so refresh needed
  2834. if (cacheResponse.Answer.Count == 0)
  2835. return false; //dont refresh empty responses
  2836. //inspect response TTL values to decide if refresh is needed
  2837. foreach (DnsResourceRecord answer in cacheResponse.Answer)
  2838. {
  2839. if ((answer.OriginalTtlValue >= _cachePrefetchEligibility) && (answer.TTL <= trigger))
  2840. return true; //TTL eligible less than trigger so refresh
  2841. }
  2842. return false; //no need to refresh for this query
  2843. }
  2844. private async void CachePrefetchSamplingTimerCallback(object state)
  2845. {
  2846. try
  2847. {
  2848. List<KeyValuePair<DnsQuestionRecord, long>> eligibleQueries = _stats.GetLastHourEligibleQueries(_cachePrefetchSampleEligibilityHitsPerHour);
  2849. List<CacheRefreshSample> cacheRefreshSampleList = new List<CacheRefreshSample>(eligibleQueries.Count);
  2850. int cacheRefreshTrigger = (_cachePrefetchSampleIntervalInMinutes + 1) * 60;
  2851. foreach (KeyValuePair<DnsQuestionRecord, long> eligibleQuery in eligibleQueries)
  2852. {
  2853. DnsQuestionRecord eligibleQuerySample = eligibleQuery.Key;
  2854. if (eligibleQuerySample.Type == DnsResourceRecordType.ANY)
  2855. continue; //dont refresh type ANY queries
  2856. DnsQuestionRecord refreshQuery = null;
  2857. IReadOnlyList<DnsResourceRecord> conditionalForwarders = null;
  2858. //query auth zone for refresh query
  2859. int queryCount = 0;
  2860. bool reQueryAuthZone;
  2861. do
  2862. {
  2863. reQueryAuthZone = false;
  2864. DnsDatagram request = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, false, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { eligibleQuerySample });
  2865. DnsDatagram response = await AuthoritativeQueryAsync(request, IPENDPOINT_ANY_0, DnsTransportProtocol.Tcp, true, false);
  2866. if (response is null)
  2867. {
  2868. //zone not hosted; do refresh
  2869. refreshQuery = GetCacheRefreshNeededQuery(eligibleQuerySample, cacheRefreshTrigger);
  2870. }
  2871. else
  2872. {
  2873. //zone is hosted; check further
  2874. if (response.Answer.Count > 0)
  2875. {
  2876. DnsResourceRecord lastRR = response.GetLastAnswerRecord();
  2877. if ((lastRR.Type == DnsResourceRecordType.CNAME) && (eligibleQuerySample.Type != DnsResourceRecordType.CNAME))
  2878. {
  2879. eligibleQuerySample = new DnsQuestionRecord((lastRR.RDATA as DnsCNAMERecordData).Domain, eligibleQuerySample.Type, eligibleQuerySample.Class);
  2880. reQueryAuthZone = true;
  2881. }
  2882. }
  2883. else if (response.Authority.Count > 0)
  2884. {
  2885. DnsResourceRecord firstAuthority = response.FindFirstAuthorityRecord();
  2886. switch (firstAuthority.Type)
  2887. {
  2888. case DnsResourceRecordType.NS: //zone is delegated
  2889. refreshQuery = GetCacheRefreshNeededQuery(eligibleQuerySample, cacheRefreshTrigger);
  2890. conditionalForwarders = Array.Empty<DnsResourceRecord>(); //do forced recursive resolution using empty conditional forwarders
  2891. break;
  2892. case DnsResourceRecordType.FWD: //zone is conditional forwarder
  2893. refreshQuery = GetCacheRefreshNeededQuery(eligibleQuerySample, cacheRefreshTrigger);
  2894. conditionalForwarders = response.Authority; //do conditional forwarding
  2895. break;
  2896. }
  2897. }
  2898. }
  2899. }
  2900. while (reQueryAuthZone && (++queryCount < MAX_CNAME_HOPS));
  2901. if (refreshQuery is not null)
  2902. cacheRefreshSampleList.Add(new CacheRefreshSample(refreshQuery, conditionalForwarders));
  2903. }
  2904. _cacheRefreshSampleList = cacheRefreshSampleList;
  2905. }
  2906. catch (Exception ex)
  2907. {
  2908. _log?.Write(ex);
  2909. }
  2910. finally
  2911. {
  2912. lock (_cachePrefetchSamplingTimerLock)
  2913. {
  2914. if (_cachePrefetchSamplingTimer is not null)
  2915. {
  2916. _cachePrefetchSamplingTimer.Change(_cachePrefetchSampleIntervalInMinutes * 60 * 1000, Timeout.Infinite);
  2917. _cachePrefetchSamplingTimerTriggersOn = DateTime.UtcNow.AddMinutes(_cachePrefetchSampleIntervalInMinutes);
  2918. }
  2919. }
  2920. }
  2921. }
  2922. private void CachePrefetchRefreshTimerCallback(object state)
  2923. {
  2924. try
  2925. {
  2926. IList<CacheRefreshSample> cacheRefreshSampleList = _cacheRefreshSampleList;
  2927. if (cacheRefreshSampleList is not null)
  2928. {
  2929. for (int i = 0; i < cacheRefreshSampleList.Count; i++)
  2930. {
  2931. CacheRefreshSample sample = cacheRefreshSampleList[i];
  2932. if (sample is null)
  2933. continue;
  2934. if (!IsCacheRefreshNeeded(sample.SampleQuestion, _cachePrefetchTrigger + 1))
  2935. continue;
  2936. cacheRefreshSampleList[i] = null; //remove from sample list to avoid concurrent refresh attempt
  2937. int sampleQuestionIndex = i;
  2938. _ = Task.Run(delegate () { return RefreshCacheAsync(cacheRefreshSampleList, sample, sampleQuestionIndex); }); //run task in threadpool since its long running
  2939. }
  2940. }
  2941. }
  2942. catch (Exception ex)
  2943. {
  2944. _log?.Write(ex);
  2945. }
  2946. finally
  2947. {
  2948. lock (_cachePrefetchRefreshTimerLock)
  2949. {
  2950. _cachePrefetchRefreshTimer?.Change((_cachePrefetchTrigger + 1) * 1000, Timeout.Infinite);
  2951. }
  2952. }
  2953. }
  2954. private void CacheMaintenanceTimerCallback(object state)
  2955. {
  2956. try
  2957. {
  2958. _cacheZoneManager.RemoveExpiredRecords();
  2959. //force GC collection to remove old cache data from memory quickly
  2960. GC.Collect();
  2961. }
  2962. catch (Exception ex)
  2963. {
  2964. _log?.Write(ex);
  2965. }
  2966. finally
  2967. {
  2968. lock (_cacheMaintenanceTimerLock)
  2969. {
  2970. _cacheMaintenanceTimer?.Change(CACHE_MAINTENANCE_TIMER_PERIODIC_INTERVAL, Timeout.Infinite);
  2971. }
  2972. }
  2973. }
  2974. private void ResetPrefetchTimers()
  2975. {
  2976. if ((_cachePrefetchTrigger == 0) || (_recursion == DnsServerRecursion.Deny))
  2977. {
  2978. lock (_cachePrefetchSamplingTimerLock)
  2979. {
  2980. _cachePrefetchSamplingTimer?.Change(Timeout.Infinite, Timeout.Infinite);
  2981. }
  2982. lock (_cachePrefetchRefreshTimerLock)
  2983. {
  2984. _cachePrefetchRefreshTimer?.Change(Timeout.Infinite, Timeout.Infinite);
  2985. }
  2986. }
  2987. else if (_state == ServiceState.Running)
  2988. {
  2989. lock (_cachePrefetchSamplingTimerLock)
  2990. {
  2991. if (_cachePrefetchSamplingTimer is not null)
  2992. {
  2993. _cachePrefetchSamplingTimer.Change(CACHE_PREFETCH_SAMPLING_TIMER_INITIAL_INTEVAL, Timeout.Infinite);
  2994. _cachePrefetchSamplingTimerTriggersOn = DateTime.UtcNow.AddMilliseconds(CACHE_PREFETCH_SAMPLING_TIMER_INITIAL_INTEVAL);
  2995. }
  2996. }
  2997. lock (_cachePrefetchRefreshTimerLock)
  2998. {
  2999. _cachePrefetchRefreshTimer?.Change(CACHE_PREFETCH_REFRESH_TIMER_INITIAL_INTEVAL, Timeout.Infinite);
  3000. }
  3001. }
  3002. }
  3003. private bool IsQpmLimitCrossed(IPAddress remoteIP)
  3004. {
  3005. if ((_qpmLimitRequests < 1) && (_qpmLimitErrors < 1))
  3006. return false;
  3007. if (IPAddress.IsLoopback(remoteIP))
  3008. return false;
  3009. IPAddress remoteSubnet;
  3010. switch (remoteIP.AddressFamily)
  3011. {
  3012. case AddressFamily.InterNetwork:
  3013. remoteSubnet = remoteIP.GetNetworkAddress(_qpmLimitIPv4PrefixLength);
  3014. break;
  3015. case AddressFamily.InterNetworkV6:
  3016. remoteSubnet = remoteIP.GetNetworkAddress(_qpmLimitIPv6PrefixLength);
  3017. break;
  3018. default:
  3019. throw new NotSupportedException("AddressFamily not supported.");
  3020. }
  3021. if ((_qpmLimitErrors > 0) && (_qpmLimitErrorClientSubnetStats is not null) && _qpmLimitErrorClientSubnetStats.TryGetValue(remoteSubnet, out long errorCountPerSample))
  3022. {
  3023. long averageErrorCountPerMinute = errorCountPerSample / _qpmLimitSampleMinutes;
  3024. if (averageErrorCountPerMinute >= _qpmLimitErrors)
  3025. return true;
  3026. }
  3027. if ((_qpmLimitRequests > 0) && (_qpmLimitClientSubnetStats is not null) && _qpmLimitClientSubnetStats.TryGetValue(remoteSubnet, out long countPerSample))
  3028. {
  3029. long averageCountPerMinute = countPerSample / _qpmLimitSampleMinutes;
  3030. if (averageCountPerMinute >= _qpmLimitRequests)
  3031. return true;
  3032. }
  3033. return false;
  3034. }
  3035. private void QpmLimitSamplingTimerCallback(object state)
  3036. {
  3037. try
  3038. {
  3039. _stats.GetLatestClientSubnetStats(_qpmLimitSampleMinutes, _qpmLimitIPv4PrefixLength, _qpmLimitIPv6PrefixLength, out _qpmLimitClientSubnetStats, out _qpmLimitErrorClientSubnetStats);
  3040. }
  3041. catch (Exception ex)
  3042. {
  3043. _log?.Write(ex);
  3044. }
  3045. finally
  3046. {
  3047. lock (_qpmLimitSamplingTimerLock)
  3048. {
  3049. _qpmLimitSamplingTimer?.Change(QPM_LIMIT_SAMPLING_TIMER_INTERVAL, Timeout.Infinite);
  3050. }
  3051. }
  3052. }
  3053. private void ResetQpsLimitTimer()
  3054. {
  3055. if ((_qpmLimitRequests < 1) && (_qpmLimitErrors < 1))
  3056. {
  3057. lock (_qpmLimitSamplingTimerLock)
  3058. {
  3059. _qpmLimitSamplingTimer?.Change(Timeout.Infinite, Timeout.Infinite);
  3060. _qpmLimitClientSubnetStats = null;
  3061. _qpmLimitErrorClientSubnetStats = null;
  3062. }
  3063. }
  3064. else if (_state == ServiceState.Running)
  3065. {
  3066. lock (_qpmLimitSamplingTimerLock)
  3067. {
  3068. _qpmLimitSamplingTimer?.Change(0, Timeout.Infinite);
  3069. }
  3070. }
  3071. }
  3072. private void UpdateThisServer()
  3073. {
  3074. if ((_localEndPoints is null) || (_localEndPoints.Count == 0))
  3075. {
  3076. _thisServer = new NameServerAddress(_serverDomain, IPAddress.Loopback);
  3077. }
  3078. else
  3079. {
  3080. foreach (IPEndPoint localEndPoint in _localEndPoints)
  3081. {
  3082. if (localEndPoint.Address.Equals(IPAddress.Any))
  3083. {
  3084. _thisServer = new NameServerAddress(_serverDomain, new IPEndPoint(IPAddress.Loopback, localEndPoint.Port));
  3085. return;
  3086. }
  3087. if (localEndPoint.Address.Equals(IPAddress.IPv6Any))
  3088. {
  3089. _thisServer = new NameServerAddress(_serverDomain, new IPEndPoint(IPAddress.IPv6Loopback, localEndPoint.Port));
  3090. return;
  3091. }
  3092. }
  3093. _thisServer = new NameServerAddress(_serverDomain, _localEndPoints[0]);
  3094. }
  3095. }
  3096. #endregion
  3097. #region doh web service
  3098. private async Task StartDoHAsync()
  3099. {
  3100. WebApplicationBuilder builder = WebApplication.CreateBuilder();
  3101. builder.Environment.ContentRootFileProvider = new PhysicalFileProvider(Path.GetDirectoryName(_dohwwwFolder))
  3102. {
  3103. UseActivePolling = true,
  3104. UsePollingFileWatcher = true
  3105. };
  3106. builder.Environment.WebRootFileProvider = new PhysicalFileProvider(_dohwwwFolder)
  3107. {
  3108. UseActivePolling = true,
  3109. UsePollingFileWatcher = true
  3110. };
  3111. IReadOnlyList<IPAddress> localAddresses = GetValidKestralLocalAddresses(_localEndPoints.Convert(delegate (IPEndPoint ep) { return ep.Address; }));
  3112. builder.WebHost.ConfigureKestrel(delegate (WebHostBuilderContext context, KestrelServerOptions serverOptions)
  3113. {
  3114. //bind to http port
  3115. if (_enableDnsOverHttp)
  3116. {
  3117. foreach (IPAddress localAddress in localAddresses)
  3118. serverOptions.Listen(localAddress, _dnsOverHttpPort);
  3119. }
  3120. //bind to https port
  3121. if (_enableDnsOverHttps && (_certificate is not null))
  3122. {
  3123. serverOptions.ConfigureHttpsDefaults(delegate (HttpsConnectionAdapterOptions configureOptions)
  3124. {
  3125. configureOptions.ServerCertificateSelector = delegate (ConnectionContext context, string dnsName)
  3126. {
  3127. return _certificate;
  3128. };
  3129. });
  3130. foreach (IPAddress localAddress in localAddresses)
  3131. {
  3132. serverOptions.Listen(localAddress, _dnsOverHttpsPort, delegate (ListenOptions listenOptions)
  3133. {
  3134. listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
  3135. listenOptions.UseHttps();
  3136. });
  3137. }
  3138. }
  3139. serverOptions.AddServerHeader = false;
  3140. serverOptions.Limits.RequestHeadersTimeout = TimeSpan.FromMilliseconds(_tcpReceiveTimeout);
  3141. serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMilliseconds(_tcpReceiveTimeout);
  3142. serverOptions.Limits.MaxRequestHeadersTotalSize = 4096;
  3143. serverOptions.Limits.MaxRequestLineSize = serverOptions.Limits.MaxRequestHeadersTotalSize;
  3144. serverOptions.Limits.MaxRequestBufferSize = serverOptions.Limits.MaxRequestLineSize;
  3145. serverOptions.Limits.MaxRequestBodySize = 64 * 1024;
  3146. serverOptions.Limits.MaxResponseBufferSize = 4096;
  3147. });
  3148. builder.Logging.ClearProviders();
  3149. _dohWebService = builder.Build();
  3150. _dohWebService.UseDefaultFiles();
  3151. _dohWebService.UseStaticFiles(new StaticFileOptions()
  3152. {
  3153. OnPrepareResponse = delegate (StaticFileResponseContext ctx)
  3154. {
  3155. ctx.Context.Response.Headers.Add("X-Robots-Tag", "noindex, nofollow");
  3156. ctx.Context.Response.Headers.Add("Cache-Control", "private, max-age=300");
  3157. }
  3158. });
  3159. _dohWebService.UseRouting();
  3160. _dohWebService.MapGet("/dns-query", ProcessDoHRequestAsync);
  3161. _dohWebService.MapPost("/dns-query", ProcessDoHRequestAsync);
  3162. try
  3163. {
  3164. await _dohWebService.StartAsync();
  3165. if (_log is not null)
  3166. {
  3167. foreach (IPAddress localAddress in localAddresses)
  3168. {
  3169. if (_enableDnsOverHttp)
  3170. _log?.Write(new IPEndPoint(localAddress, _dnsOverHttpPort), "Http", "DNS Server was bound successfully.");
  3171. if (_enableDnsOverHttps && (_certificate is not null))
  3172. _log?.Write(new IPEndPoint(localAddress, _dnsOverHttpsPort), "Https", "DNS Server was bound successfully.");
  3173. }
  3174. }
  3175. }
  3176. catch (Exception ex)
  3177. {
  3178. await StopDoHAsync();
  3179. if (_log is not null)
  3180. {
  3181. foreach (IPAddress localAddress in localAddresses)
  3182. {
  3183. if (_enableDnsOverHttp)
  3184. _log?.Write(new IPEndPoint(localAddress, _dnsOverHttpPort), "Http", "DNS Server failed to bind.");
  3185. if (_enableDnsOverHttps && (_certificate is not null))
  3186. _log?.Write(new IPEndPoint(localAddress, _dnsOverHttpsPort), "Https", "DNS Server failed to bind.");
  3187. }
  3188. _log?.Write(ex);
  3189. }
  3190. }
  3191. }
  3192. private async Task StopDoHAsync()
  3193. {
  3194. if (_dohWebService is not null)
  3195. {
  3196. await _dohWebService.DisposeAsync();
  3197. _dohWebService = null;
  3198. }
  3199. }
  3200. internal static IReadOnlyList<IPAddress> GetValidKestralLocalAddresses(IReadOnlyList<IPAddress> localAddresses)
  3201. {
  3202. List<IPAddress> supportedLocalAddresses = new List<IPAddress>(localAddresses.Count);
  3203. foreach (IPAddress localAddress in localAddresses)
  3204. {
  3205. switch (localAddress.AddressFamily)
  3206. {
  3207. case AddressFamily.InterNetwork:
  3208. if (Socket.OSSupportsIPv4)
  3209. {
  3210. if (!supportedLocalAddresses.Contains(localAddress))
  3211. supportedLocalAddresses.Add(localAddress);
  3212. }
  3213. break;
  3214. case AddressFamily.InterNetworkV6:
  3215. if (Socket.OSSupportsIPv6)
  3216. {
  3217. if (!supportedLocalAddresses.Contains(localAddress))
  3218. supportedLocalAddresses.Add(localAddress);
  3219. }
  3220. break;
  3221. }
  3222. }
  3223. bool containsUnicastAddress = false;
  3224. foreach (IPAddress localAddress in supportedLocalAddresses)
  3225. {
  3226. if (!localAddress.Equals(IPAddress.Any) && !localAddress.Equals(IPAddress.IPv6Any))
  3227. {
  3228. containsUnicastAddress = true;
  3229. break;
  3230. }
  3231. }
  3232. List<IPAddress> newLocalAddresses = new List<IPAddress>(supportedLocalAddresses.Count);
  3233. if (containsUnicastAddress)
  3234. {
  3235. //replace any with loopback address
  3236. foreach (IPAddress localAddress in supportedLocalAddresses)
  3237. {
  3238. if (localAddress.Equals(IPAddress.Any))
  3239. {
  3240. if (!newLocalAddresses.Contains(IPAddress.Loopback))
  3241. newLocalAddresses.Add(IPAddress.Loopback);
  3242. }
  3243. else if (localAddress.Equals(IPAddress.IPv6Any))
  3244. {
  3245. if (!newLocalAddresses.Contains(IPAddress.IPv6Loopback))
  3246. newLocalAddresses.Add(IPAddress.IPv6Loopback);
  3247. }
  3248. else
  3249. {
  3250. if (!newLocalAddresses.Contains(localAddress))
  3251. newLocalAddresses.Add(localAddress);
  3252. }
  3253. }
  3254. }
  3255. else
  3256. {
  3257. //remove "0.0.0.0" if [::] exists
  3258. foreach (IPAddress localAddress in supportedLocalAddresses)
  3259. {
  3260. if (localAddress.Equals(IPAddress.Any))
  3261. {
  3262. if (!supportedLocalAddresses.Contains(IPAddress.IPv6Any))
  3263. newLocalAddresses.Add(localAddress);
  3264. }
  3265. else
  3266. {
  3267. newLocalAddresses.Add(localAddress);
  3268. }
  3269. }
  3270. }
  3271. return newLocalAddresses;
  3272. }
  3273. #endregion
  3274. #region public
  3275. public async Task StartAsync()
  3276. {
  3277. if (_disposed)
  3278. throw new ObjectDisposedException("DnsServer");
  3279. if (_state != ServiceState.Stopped)
  3280. throw new InvalidOperationException("DNS Server is already running.");
  3281. _state = ServiceState.Starting;
  3282. //bind on all local end points
  3283. foreach (IPEndPoint localEP in _localEndPoints)
  3284. {
  3285. Socket udpListener = null;
  3286. try
  3287. {
  3288. udpListener = new Socket(localEP.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
  3289. #region this code ignores ICMP port unreachable responses which creates SocketException in ReceiveFrom()
  3290. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  3291. {
  3292. const uint IOC_IN = 0x80000000;
  3293. const uint IOC_VENDOR = 0x18000000;
  3294. const uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
  3295. udpListener.IOControl((IOControlCode)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
  3296. }
  3297. #endregion
  3298. udpListener.ReceiveBufferSize = 512 * 1024;
  3299. udpListener.SendBufferSize = 512 * 1024;
  3300. udpListener.Bind(localEP);
  3301. _udpListeners.Add(udpListener);
  3302. _log?.Write(localEP, DnsTransportProtocol.Udp, "DNS Server was bound successfully.");
  3303. }
  3304. catch (Exception ex)
  3305. {
  3306. _log?.Write(localEP, DnsTransportProtocol.Udp, "DNS Server failed to bind.\r\n" + ex.ToString());
  3307. udpListener?.Dispose();
  3308. }
  3309. Socket tcpListener = null;
  3310. try
  3311. {
  3312. tcpListener = new Socket(localEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  3313. tcpListener.Bind(localEP);
  3314. tcpListener.Listen(_listenBacklog);
  3315. _tcpListeners.Add(tcpListener);
  3316. _log?.Write(localEP, DnsTransportProtocol.Tcp, "DNS Server was bound successfully.");
  3317. }
  3318. catch (Exception ex)
  3319. {
  3320. _log?.Write(localEP, DnsTransportProtocol.Tcp, "DNS Server failed to bind.\r\n" + ex.ToString());
  3321. tcpListener?.Dispose();
  3322. }
  3323. if (_enableDnsOverTls && (_certificate is not null))
  3324. {
  3325. IPEndPoint tlsEP = new IPEndPoint(localEP.Address, _dnsOverTlsPort);
  3326. Socket tlsListener = null;
  3327. try
  3328. {
  3329. tlsListener = new Socket(tlsEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  3330. tlsListener.Bind(tlsEP);
  3331. tlsListener.Listen(_listenBacklog);
  3332. _tlsListeners.Add(tlsListener);
  3333. _log?.Write(tlsEP, DnsTransportProtocol.Tls, "DNS Server was bound successfully.");
  3334. }
  3335. catch (Exception ex)
  3336. {
  3337. _log?.Write(tlsEP, DnsTransportProtocol.Tls, "DNS Server failed to bind.\r\n" + ex.ToString());
  3338. tlsListener?.Dispose();
  3339. }
  3340. }
  3341. if (_enableDnsOverQuic && (_certificate is not null))
  3342. {
  3343. IPEndPoint quicEP = new IPEndPoint(localEP.Address, _dnsOverQuicPort);
  3344. QuicListener quicListener = null;
  3345. try
  3346. {
  3347. QuicListenerOptions listenerOptions = new QuicListenerOptions()
  3348. {
  3349. ListenEndPoint = quicEP,
  3350. ListenBacklog = _listenBacklog,
  3351. ApplicationProtocols = new List<SslApplicationProtocol>() { new SslApplicationProtocol("doq") },
  3352. ConnectionOptionsCallback = delegate (QuicConnection quicConnection, SslClientHelloInfo sslClientHello, CancellationToken cancellationToken)
  3353. {
  3354. QuicServerConnectionOptions serverConnectionOptions = new QuicServerConnectionOptions()
  3355. {
  3356. DefaultCloseErrorCode = (long)DnsOverQuicErrorCodes.DOQ_NO_ERROR,
  3357. DefaultStreamErrorCode = (long)DnsOverQuicErrorCodes.DOQ_UNSPECIFIED_ERROR,
  3358. MaxInboundUnidirectionalStreams = 0,
  3359. MaxInboundBidirectionalStreams = _quicMaxInboundStreams,
  3360. IdleTimeout = TimeSpan.FromMilliseconds(_quicIdleTimeout),
  3361. ServerAuthenticationOptions = new SslServerAuthenticationOptions
  3362. {
  3363. ApplicationProtocols = new List<SslApplicationProtocol>() { new SslApplicationProtocol("doq") },
  3364. ServerCertificate = _certificate
  3365. }
  3366. };
  3367. return ValueTask.FromResult(serverConnectionOptions);
  3368. }
  3369. };
  3370. quicListener = await QuicListener.ListenAsync(listenerOptions);
  3371. _quicListeners.Add(quicListener);
  3372. _log?.Write(quicEP, DnsTransportProtocol.Quic, "DNS Server was bound successfully.");
  3373. }
  3374. catch (Exception ex)
  3375. {
  3376. _log?.Write(quicEP, DnsTransportProtocol.Quic, "DNS Server failed to bind.\r\n" + ex.ToString());
  3377. if (quicListener is not null)
  3378. await quicListener.DisposeAsync();
  3379. }
  3380. }
  3381. }
  3382. //start reading query packets
  3383. int listenerTaskCount = Math.Max(1, Environment.ProcessorCount);
  3384. foreach (Socket udpListener in _udpListeners)
  3385. {
  3386. for (int i = 0; i < listenerTaskCount; i++)
  3387. {
  3388. _ = Task.Factory.StartNew(delegate ()
  3389. {
  3390. return ReadUdpRequestAsync(udpListener);
  3391. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _queryTaskScheduler);
  3392. }
  3393. }
  3394. foreach (Socket tcpListener in _tcpListeners)
  3395. {
  3396. for (int i = 0; i < listenerTaskCount; i++)
  3397. {
  3398. _ = Task.Factory.StartNew(delegate ()
  3399. {
  3400. return AcceptConnectionAsync(tcpListener, DnsTransportProtocol.Tcp);
  3401. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _queryTaskScheduler);
  3402. }
  3403. }
  3404. foreach (Socket tlsListener in _tlsListeners)
  3405. {
  3406. for (int i = 0; i < listenerTaskCount; i++)
  3407. {
  3408. _ = Task.Factory.StartNew(delegate ()
  3409. {
  3410. return AcceptConnectionAsync(tlsListener, DnsTransportProtocol.Tls);
  3411. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _queryTaskScheduler);
  3412. }
  3413. }
  3414. foreach (QuicListener quicListener in _quicListeners)
  3415. {
  3416. for (int i = 0; i < listenerTaskCount; i++)
  3417. {
  3418. _ = Task.Factory.StartNew(delegate ()
  3419. {
  3420. return AcceptQuicConnectionAsync(quicListener);
  3421. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _queryTaskScheduler);
  3422. }
  3423. }
  3424. if (_enableDnsOverHttp || (_enableDnsOverHttps && (_certificate is not null)))
  3425. await StartDoHAsync();
  3426. _cachePrefetchSamplingTimer = new Timer(CachePrefetchSamplingTimerCallback, null, Timeout.Infinite, Timeout.Infinite);
  3427. _cachePrefetchRefreshTimer = new Timer(CachePrefetchRefreshTimerCallback, null, Timeout.Infinite, Timeout.Infinite);
  3428. _cacheMaintenanceTimer = new Timer(CacheMaintenanceTimerCallback, null, CACHE_MAINTENANCE_TIMER_INITIAL_INTEVAL, Timeout.Infinite);
  3429. _qpmLimitSamplingTimer = new Timer(QpmLimitSamplingTimerCallback, null, Timeout.Infinite, Timeout.Infinite);
  3430. _state = ServiceState.Running;
  3431. UpdateThisServer();
  3432. ResetPrefetchTimers();
  3433. ResetQpsLimitTimer();
  3434. }
  3435. public async Task StopAsync()
  3436. {
  3437. if (_state != ServiceState.Running)
  3438. return;
  3439. _state = ServiceState.Stopping;
  3440. lock (_cachePrefetchSamplingTimerLock)
  3441. {
  3442. if (_cachePrefetchSamplingTimer is not null)
  3443. {
  3444. _cachePrefetchSamplingTimer.Dispose();
  3445. _cachePrefetchSamplingTimer = null;
  3446. }
  3447. }
  3448. lock (_cachePrefetchRefreshTimerLock)
  3449. {
  3450. if (_cachePrefetchRefreshTimer is not null)
  3451. {
  3452. _cachePrefetchRefreshTimer.Dispose();
  3453. _cachePrefetchRefreshTimer = null;
  3454. }
  3455. }
  3456. lock (_cacheMaintenanceTimerLock)
  3457. {
  3458. if (_cacheMaintenanceTimer is not null)
  3459. {
  3460. _cacheMaintenanceTimer.Dispose();
  3461. _cacheMaintenanceTimer = null;
  3462. }
  3463. }
  3464. lock (_qpmLimitSamplingTimerLock)
  3465. {
  3466. if (_qpmLimitSamplingTimer is not null)
  3467. {
  3468. _qpmLimitSamplingTimer.Dispose();
  3469. _qpmLimitSamplingTimer = null;
  3470. }
  3471. }
  3472. foreach (Socket udpListener in _udpListeners)
  3473. udpListener.Dispose();
  3474. foreach (Socket tcpListener in _tcpListeners)
  3475. tcpListener.Dispose();
  3476. foreach (Socket tlsListener in _tlsListeners)
  3477. tlsListener.Dispose();
  3478. foreach (QuicListener quicListener in _quicListeners)
  3479. await quicListener.DisposeAsync();
  3480. _udpListeners.Clear();
  3481. _tcpListeners.Clear();
  3482. _tlsListeners.Clear();
  3483. _quicListeners.Clear();
  3484. await StopDoHAsync();
  3485. _state = ServiceState.Stopped;
  3486. }
  3487. public Task<DnsDatagram> DirectQueryAsync(DnsQuestionRecord question, int timeout = 4000, bool skipDnsAppAuthoritativeRequestHandlers = false)
  3488. {
  3489. return DirectQueryAsync(new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, true, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { question }), timeout, skipDnsAppAuthoritativeRequestHandlers);
  3490. }
  3491. public Task<DnsDatagram> DirectQueryAsync(DnsDatagram request, int timeout = 4000, bool skipDnsAppAuthoritativeRequestHandlers = false)
  3492. {
  3493. return ProcessQueryAsync(request, IPENDPOINT_ANY_0, DnsTransportProtocol.Tcp, true, skipDnsAppAuthoritativeRequestHandlers, null).WithTimeout(timeout);
  3494. }
  3495. Task<DnsDatagram> IDnsClient.ResolveAsync(DnsQuestionRecord question, CancellationToken cancellationToken)
  3496. {
  3497. return DirectQueryAsync(question);
  3498. }
  3499. #endregion
  3500. #region properties
  3501. public string ServerDomain
  3502. {
  3503. get { return _serverDomain; }
  3504. set
  3505. {
  3506. if (!_serverDomain.Equals(value))
  3507. {
  3508. _serverDomain = value.ToLower();
  3509. _authZoneManager.ServerDomain = _serverDomain;
  3510. _allowedZoneManager.ServerDomain = _serverDomain;
  3511. _blockedZoneManager.ServerDomain = _serverDomain;
  3512. _blockListZoneManager.ServerDomain = _serverDomain;
  3513. UpdateThisServer();
  3514. }
  3515. }
  3516. }
  3517. public string ConfigFolder
  3518. { get { return _configFolder; } }
  3519. public IReadOnlyList<IPEndPoint> LocalEndPoints
  3520. {
  3521. get { return _localEndPoints; }
  3522. set { _localEndPoints = value; }
  3523. }
  3524. public LogManager LogManager
  3525. {
  3526. get { return _log; }
  3527. set { _log = value; }
  3528. }
  3529. public NameServerAddress ThisServer
  3530. { get { return _thisServer; } }
  3531. public AuthZoneManager AuthZoneManager
  3532. { get { return _authZoneManager; } }
  3533. public AllowedZoneManager AllowedZoneManager
  3534. { get { return _allowedZoneManager; } }
  3535. public BlockedZoneManager BlockedZoneManager
  3536. { get { return _blockedZoneManager; } }
  3537. public BlockListZoneManager BlockListZoneManager
  3538. { get { return _blockListZoneManager; } }
  3539. public CacheZoneManager CacheZoneManager
  3540. { get { return _cacheZoneManager; } }
  3541. public DnsApplicationManager DnsApplicationManager
  3542. { get { return _dnsApplicationManager; } }
  3543. public IDnsCache DnsCache
  3544. { get { return _dnsCache; } }
  3545. public StatsManager StatsManager
  3546. { get { return _stats; } }
  3547. public bool PreferIPv6
  3548. {
  3549. get { return _preferIPv6; }
  3550. set { _preferIPv6 = value; }
  3551. }
  3552. public ushort UdpPayloadSize
  3553. {
  3554. get { return _udpPayloadSize; }
  3555. set
  3556. {
  3557. if ((value < 512) || (value > 4096))
  3558. throw new ArgumentOutOfRangeException(nameof(UdpPayloadSize), "Invalid EDNS UDP payload size: valid range is 512-4096 bytes.");
  3559. _udpPayloadSize = value;
  3560. }
  3561. }
  3562. public bool DnssecValidation
  3563. {
  3564. get { return _dnssecValidation; }
  3565. set
  3566. {
  3567. if (_dnssecValidation != value)
  3568. {
  3569. if (!_dnssecValidation)
  3570. _cacheZoneManager.Flush(); //flush cache to remove non validated data
  3571. _dnssecValidation = value;
  3572. }
  3573. }
  3574. }
  3575. public bool EDnsClientSubnet
  3576. {
  3577. get { return _eDnsClientSubnet; }
  3578. set
  3579. {
  3580. _eDnsClientSubnet = value;
  3581. if (!_eDnsClientSubnet)
  3582. {
  3583. ThreadPool.QueueUserWorkItem(delegate (object state)
  3584. {
  3585. _cacheZoneManager.DeleteEDnsClientSubnetData();
  3586. });
  3587. }
  3588. }
  3589. }
  3590. public byte EDnsClientSubnetIPv4PrefixLength
  3591. {
  3592. get { return _eDnsClientSubnetIPv4PrefixLength; }
  3593. set
  3594. {
  3595. if (value > 32)
  3596. throw new ArgumentOutOfRangeException(nameof(EDnsClientSubnetIPv4PrefixLength), "EDNS Client Subnet IPv4 prefix length cannot be greater than 32.");
  3597. _eDnsClientSubnetIPv4PrefixLength = value;
  3598. }
  3599. }
  3600. public byte EDnsClientSubnetIPv6PrefixLength
  3601. {
  3602. get { return _eDnsClientSubnetIPv6PrefixLength; }
  3603. set
  3604. {
  3605. if (value > 64)
  3606. throw new ArgumentOutOfRangeException(nameof(EDnsClientSubnetIPv6PrefixLength), "EDNS Client Subnet IPv6 prefix length cannot be greater than 64.");
  3607. _eDnsClientSubnetIPv6PrefixLength = value;
  3608. }
  3609. }
  3610. public int QpmLimitRequests
  3611. {
  3612. get { return _qpmLimitRequests; }
  3613. set
  3614. {
  3615. if (value < 0)
  3616. throw new ArgumentOutOfRangeException(nameof(QpmLimitRequests), "Value cannot be less than 0.");
  3617. if (_qpmLimitRequests != value)
  3618. {
  3619. if ((_qpmLimitRequests == 0) || (value == 0))
  3620. {
  3621. _qpmLimitRequests = value;
  3622. ResetQpsLimitTimer();
  3623. }
  3624. else
  3625. {
  3626. _qpmLimitRequests = value;
  3627. }
  3628. }
  3629. }
  3630. }
  3631. public int QpmLimitErrors
  3632. {
  3633. get { return _qpmLimitErrors; }
  3634. set
  3635. {
  3636. if (value < 0)
  3637. throw new ArgumentOutOfRangeException(nameof(QpmLimitErrors), "Value cannot be less than 0.");
  3638. if (_qpmLimitErrors != value)
  3639. {
  3640. if ((_qpmLimitErrors == 0) || (value == 0))
  3641. {
  3642. _qpmLimitErrors = value;
  3643. ResetQpsLimitTimer();
  3644. }
  3645. else
  3646. {
  3647. _qpmLimitErrors = value;
  3648. }
  3649. }
  3650. }
  3651. }
  3652. public int QpmLimitSampleMinutes
  3653. {
  3654. get { return _qpmLimitSampleMinutes; }
  3655. set
  3656. {
  3657. if ((value < 1) || (value > 60))
  3658. throw new ArgumentOutOfRangeException(nameof(QpmLimitSampleMinutes), "Valid range is between 1 and 60 minutes.");
  3659. _qpmLimitSampleMinutes = value;
  3660. }
  3661. }
  3662. public int QpmLimitIPv4PrefixLength
  3663. {
  3664. get { return _qpmLimitIPv4PrefixLength; }
  3665. set
  3666. {
  3667. if ((value < 0) || (value > 32))
  3668. throw new ArgumentOutOfRangeException(nameof(QpmLimitIPv4PrefixLength), "Valid range is between 0 and 32.");
  3669. _qpmLimitIPv4PrefixLength = value;
  3670. }
  3671. }
  3672. public int QpmLimitIPv6PrefixLength
  3673. {
  3674. get { return _qpmLimitIPv6PrefixLength; }
  3675. set
  3676. {
  3677. if ((value < 0) || (value > 64))
  3678. throw new ArgumentOutOfRangeException(nameof(QpmLimitIPv6PrefixLength), "Valid range is between 0 and 64.");
  3679. _qpmLimitIPv6PrefixLength = value;
  3680. }
  3681. }
  3682. public int ClientTimeout
  3683. {
  3684. get { return _clientTimeout; }
  3685. set
  3686. {
  3687. if ((value < 1000) || (value > 10000))
  3688. throw new ArgumentOutOfRangeException(nameof(ClientTimeout), "Valid range is from 1000 to 10000.");
  3689. _clientTimeout = value;
  3690. }
  3691. }
  3692. public int TcpSendTimeout
  3693. {
  3694. get { return _tcpSendTimeout; }
  3695. set
  3696. {
  3697. if ((value < 1000) || (value > 90000))
  3698. throw new ArgumentOutOfRangeException(nameof(TcpSendTimeout), "Valid range is from 1000 to 90000.");
  3699. _tcpSendTimeout = value;
  3700. }
  3701. }
  3702. public int TcpReceiveTimeout
  3703. {
  3704. get { return _tcpReceiveTimeout; }
  3705. set
  3706. {
  3707. if ((value < 1000) || (value > 90000))
  3708. throw new ArgumentOutOfRangeException(nameof(TcpReceiveTimeout), "Valid range is from 1000 to 90000.");
  3709. _tcpReceiveTimeout = value;
  3710. }
  3711. }
  3712. public int QuicIdleTimeout
  3713. {
  3714. get { return _quicIdleTimeout; }
  3715. set
  3716. {
  3717. if ((value < 1000) || (value > 90000))
  3718. throw new ArgumentOutOfRangeException(nameof(QuicIdleTimeout), "Valid range is from 1000 to 90000.");
  3719. _quicIdleTimeout = value;
  3720. }
  3721. }
  3722. public int QuicMaxInboundStreams
  3723. {
  3724. get { return _quicMaxInboundStreams; }
  3725. set
  3726. {
  3727. if ((value < 0) || (value > 1000))
  3728. throw new ArgumentOutOfRangeException(nameof(QuicMaxInboundStreams), "Valid range is from 1 to 1000.");
  3729. _quicMaxInboundStreams = value;
  3730. }
  3731. }
  3732. public int ListenBacklog
  3733. {
  3734. get { return _listenBacklog; }
  3735. set { _listenBacklog = value; }
  3736. }
  3737. public bool EnableDnsOverHttp
  3738. {
  3739. get { return _enableDnsOverHttp; }
  3740. set { _enableDnsOverHttp = value; }
  3741. }
  3742. public bool EnableDnsOverTls
  3743. {
  3744. get { return _enableDnsOverTls; }
  3745. set { _enableDnsOverTls = value; }
  3746. }
  3747. public bool EnableDnsOverHttps
  3748. {
  3749. get { return _enableDnsOverHttps; }
  3750. set { _enableDnsOverHttps = value; }
  3751. }
  3752. public bool EnableDnsOverQuic
  3753. {
  3754. get { return _enableDnsOverQuic; }
  3755. set { _enableDnsOverQuic = value; }
  3756. }
  3757. public int DnsOverHttpPort
  3758. {
  3759. get { return _dnsOverHttpPort; }
  3760. set { _dnsOverHttpPort = value; }
  3761. }
  3762. public int DnsOverTlsPort
  3763. {
  3764. get { return _dnsOverTlsPort; }
  3765. set { _dnsOverTlsPort = value; }
  3766. }
  3767. public int DnsOverHttpsPort
  3768. {
  3769. get { return _dnsOverHttpsPort; }
  3770. set { _dnsOverHttpsPort = value; }
  3771. }
  3772. public int DnsOverQuicPort
  3773. {
  3774. get { return _dnsOverQuicPort; }
  3775. set { _dnsOverQuicPort = value; }
  3776. }
  3777. public X509Certificate2 Certificate
  3778. {
  3779. get { return _certificate; }
  3780. set
  3781. {
  3782. if ((value is not null) && !value.HasPrivateKey)
  3783. throw new ArgumentException("Tls certificate does not contain private key.");
  3784. _certificate = value;
  3785. }
  3786. }
  3787. public IReadOnlyDictionary<string, TsigKey> TsigKeys
  3788. {
  3789. get { return _tsigKeys; }
  3790. set { _tsigKeys = value; }
  3791. }
  3792. public DnsServerRecursion Recursion
  3793. {
  3794. get { return _recursion; }
  3795. set
  3796. {
  3797. if (_recursion != value)
  3798. {
  3799. if ((_recursion == DnsServerRecursion.Deny) || (value == DnsServerRecursion.Deny))
  3800. {
  3801. _recursion = value;
  3802. ResetPrefetchTimers();
  3803. }
  3804. else
  3805. {
  3806. _recursion = value;
  3807. }
  3808. }
  3809. }
  3810. }
  3811. public IReadOnlyCollection<NetworkAddress> RecursionDeniedNetworks
  3812. {
  3813. get { return _recursionDeniedNetworks; }
  3814. set
  3815. {
  3816. if ((value is not null) && (value.Count > byte.MaxValue))
  3817. throw new ArgumentOutOfRangeException(nameof(RecursionDeniedNetworks), "Networks cannot be more than 255.");
  3818. _recursionDeniedNetworks = value;
  3819. }
  3820. }
  3821. public IReadOnlyCollection<NetworkAddress> RecursionAllowedNetworks
  3822. {
  3823. get { return _recursionAllowedNetworks; }
  3824. set
  3825. {
  3826. if ((value is not null) && (value.Count > byte.MaxValue))
  3827. throw new ArgumentOutOfRangeException(nameof(RecursionAllowedNetworks), "Networks cannot be more than 255.");
  3828. _recursionAllowedNetworks = value;
  3829. }
  3830. }
  3831. public bool RandomizeName
  3832. {
  3833. get { return _randomizeName; }
  3834. set { _randomizeName = value; }
  3835. }
  3836. public bool QnameMinimization
  3837. {
  3838. get { return _qnameMinimization; }
  3839. set { _qnameMinimization = value; }
  3840. }
  3841. public bool NsRevalidation
  3842. {
  3843. get { return _nsRevalidation; }
  3844. set { _nsRevalidation = value; }
  3845. }
  3846. public int ResolverRetries
  3847. {
  3848. get { return _resolverRetries; }
  3849. set
  3850. {
  3851. if ((value < 1) || (value > 10))
  3852. throw new ArgumentOutOfRangeException(nameof(ResolverRetries), "Valid range is from 1 to 10.");
  3853. _resolverRetries = value;
  3854. }
  3855. }
  3856. public int ResolverTimeout
  3857. {
  3858. get { return _resolverTimeout; }
  3859. set
  3860. {
  3861. if ((value < 1000) || (value > 10000))
  3862. throw new ArgumentOutOfRangeException(nameof(ResolverTimeout), "Valid range is from 1000 to 10000.");
  3863. _resolverTimeout = value;
  3864. }
  3865. }
  3866. public int ResolverMaxStackCount
  3867. {
  3868. get { return _resolverMaxStackCount; }
  3869. set
  3870. {
  3871. if ((value < 10) || (value > 30))
  3872. throw new ArgumentOutOfRangeException(nameof(ResolverMaxStackCount), "Valid range is from 10 to 30.");
  3873. _resolverMaxStackCount = value;
  3874. }
  3875. }
  3876. public bool ServeStale
  3877. {
  3878. get { return _serveStale; }
  3879. set { _serveStale = value; }
  3880. }
  3881. public int CachePrefetchEligibility
  3882. {
  3883. get { return _cachePrefetchEligibility; }
  3884. set
  3885. {
  3886. if (value < 2)
  3887. throw new ArgumentOutOfRangeException(nameof(CachePrefetchEligibility), "Valid value is greater that or equal to 2.");
  3888. _cachePrefetchEligibility = value;
  3889. }
  3890. }
  3891. public int CachePrefetchTrigger
  3892. {
  3893. get { return _cachePrefetchTrigger; }
  3894. set
  3895. {
  3896. if (value < 0)
  3897. throw new ArgumentOutOfRangeException(nameof(CachePrefetchTrigger), "Valid value is greater that or equal to 0.");
  3898. if (_cachePrefetchTrigger != value)
  3899. {
  3900. if ((_cachePrefetchTrigger == 0) || (value == 0))
  3901. {
  3902. _cachePrefetchTrigger = value;
  3903. ResetPrefetchTimers();
  3904. }
  3905. else
  3906. {
  3907. _cachePrefetchTrigger = value;
  3908. }
  3909. }
  3910. }
  3911. }
  3912. public int CachePrefetchSampleIntervalInMinutes
  3913. {
  3914. get { return _cachePrefetchSampleIntervalInMinutes; }
  3915. set
  3916. {
  3917. if ((value < 1) || (value > 60))
  3918. throw new ArgumentOutOfRangeException(nameof(CachePrefetchSampleIntervalInMinutes), "Valid range is between 1 and 60 minutes.");
  3919. _cachePrefetchSampleIntervalInMinutes = value;
  3920. }
  3921. }
  3922. public int CachePrefetchSampleEligibilityHitsPerHour
  3923. {
  3924. get { return _cachePrefetchSampleEligibilityHitsPerHour; }
  3925. set
  3926. {
  3927. if (value < 1)
  3928. throw new ArgumentOutOfRangeException(nameof(CachePrefetchSampleEligibilityHitsPerHour), "Valid value is greater than or equal to 1.");
  3929. _cachePrefetchSampleEligibilityHitsPerHour = value;
  3930. }
  3931. }
  3932. public bool EnableBlocking
  3933. {
  3934. get { return _enableBlocking; }
  3935. set { _enableBlocking = value; }
  3936. }
  3937. public bool AllowTxtBlockingReport
  3938. {
  3939. get { return _allowTxtBlockingReport; }
  3940. set { _allowTxtBlockingReport = value; }
  3941. }
  3942. public DnsServerBlockingType BlockingType
  3943. {
  3944. get { return _blockingType; }
  3945. set { _blockingType = value; }
  3946. }
  3947. public IReadOnlyCollection<DnsARecordData> CustomBlockingARecords
  3948. {
  3949. get { return _customBlockingARecords; }
  3950. set
  3951. {
  3952. if (value is null)
  3953. value = Array.Empty<DnsARecordData>();
  3954. _customBlockingARecords = value;
  3955. }
  3956. }
  3957. public IReadOnlyCollection<DnsAAAARecordData> CustomBlockingAAAARecords
  3958. {
  3959. get { return _customBlockingAAAARecords; }
  3960. set
  3961. {
  3962. if (value is null)
  3963. value = Array.Empty<DnsAAAARecordData>();
  3964. _customBlockingAAAARecords = value;
  3965. }
  3966. }
  3967. public NetProxy Proxy
  3968. {
  3969. get { return _proxy; }
  3970. set { _proxy = value; }
  3971. }
  3972. public IReadOnlyList<NameServerAddress> Forwarders
  3973. {
  3974. get { return _forwarders; }
  3975. set { _forwarders = value; }
  3976. }
  3977. public int ForwarderRetries
  3978. {
  3979. get { return _forwarderRetries; }
  3980. set
  3981. {
  3982. if ((value < 1) || (value > 10))
  3983. throw new ArgumentOutOfRangeException(nameof(ForwarderRetries), "Valid range is from 1 to 10.");
  3984. _forwarderRetries = value;
  3985. }
  3986. }
  3987. public int ForwarderTimeout
  3988. {
  3989. get { return _forwarderTimeout; }
  3990. set
  3991. {
  3992. if ((value < 1000) || (value > 10000))
  3993. throw new ArgumentOutOfRangeException(nameof(ForwarderTimeout), "Valid range is from 1000 to 10000.");
  3994. _forwarderTimeout = value;
  3995. }
  3996. }
  3997. public int ForwarderConcurrency
  3998. {
  3999. get { return _forwarderConcurrency; }
  4000. set
  4001. {
  4002. if ((value < 1) || (value > 10))
  4003. throw new ArgumentOutOfRangeException(nameof(ForwarderConcurrency), "Valid range is from 1 to 10.");
  4004. _forwarderConcurrency = value;
  4005. }
  4006. }
  4007. public LogManager QueryLogManager
  4008. {
  4009. get { return _queryLog; }
  4010. set { _queryLog = value; }
  4011. }
  4012. #endregion
  4013. class CacheRefreshSample
  4014. {
  4015. public CacheRefreshSample(DnsQuestionRecord sampleQuestion, IReadOnlyList<DnsResourceRecord> conditionalForwarders)
  4016. {
  4017. SampleQuestion = sampleQuestion;
  4018. ConditionalForwarders = conditionalForwarders;
  4019. }
  4020. public DnsQuestionRecord SampleQuestion { get; }
  4021. public IReadOnlyList<DnsResourceRecord> ConditionalForwarders { get; }
  4022. }
  4023. class RecursiveResolveResponse
  4024. {
  4025. public RecursiveResolveResponse(DnsDatagram response, DnsDatagram checkingDisabledResponse)
  4026. {
  4027. Response = response;
  4028. CheckingDisabledResponse = checkingDisabledResponse;
  4029. }
  4030. public DnsDatagram Response { get; }
  4031. public DnsDatagram CheckingDisabledResponse { get; }
  4032. }
  4033. }
  4034. #pragma warning restore CA2252 // This API requires opting into preview features
  4035. #pragma warning restore CA1416 // Validate platform compatibility
  4036. }