DnsServer.cs 275 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2024 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerCore.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.Hosting;
  23. using Microsoft.AspNetCore.Http;
  24. using Microsoft.AspNetCore.Http.Extensions;
  25. using Microsoft.AspNetCore.Server.Kestrel.Core;
  26. using Microsoft.AspNetCore.StaticFiles;
  27. using Microsoft.Extensions.FileProviders;
  28. using Microsoft.Extensions.Logging;
  29. using System;
  30. using System.Buffers;
  31. using System.Collections.Concurrent;
  32. using System.Collections.Generic;
  33. using System.IO;
  34. using System.Net;
  35. using System.Net.Mail;
  36. using System.Net.Quic;
  37. using System.Net.Security;
  38. using System.Net.Sockets;
  39. using System.Runtime.ExceptionServices;
  40. using System.Security.Authentication;
  41. using System.Security.Cryptography.X509Certificates;
  42. using System.Threading;
  43. using System.Threading.Tasks;
  44. using TechnitiumLibrary;
  45. using TechnitiumLibrary.Net;
  46. using TechnitiumLibrary.Net.Dns;
  47. using TechnitiumLibrary.Net.Dns.ClientConnection;
  48. using TechnitiumLibrary.Net.Dns.EDnsOptions;
  49. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  50. using TechnitiumLibrary.Net.Proxy;
  51. using TechnitiumLibrary.Net.ProxyProtocol;
  52. namespace DnsServerCore.Dns
  53. {
  54. #pragma warning disable CA2252 // This API requires opting into preview features
  55. #pragma warning disable CA1416 // Validate platform compatibility
  56. public enum DnsServerRecursion : byte
  57. {
  58. Deny = 0,
  59. Allow = 1,
  60. AllowOnlyForPrivateNetworks = 2,
  61. UseSpecifiedNetworkACL = 3
  62. }
  63. public enum DnsServerBlockingType : byte
  64. {
  65. AnyAddress = 0,
  66. NxDomain = 1,
  67. CustomAddress = 2
  68. }
  69. public sealed class DnsServer : IAsyncDisposable, IDisposable, IDnsClient
  70. {
  71. #region enum
  72. enum ServiceState
  73. {
  74. Stopped = 0,
  75. Starting = 1,
  76. Running = 2,
  77. Stopping = 3
  78. }
  79. #endregion
  80. #region variables
  81. internal const int MAX_CNAME_HOPS = 16;
  82. internal const int SERVE_STALE_MAX_WAIT_TIME = 1800; //max time to wait before serve stale [RFC 8767]
  83. const int SERVE_STALE_TIME_DIFFERENCE = 200; //200ms before client timeout [RFC 8767]
  84. internal const int RECURSIVE_RESOLUTION_TIMEOUT = 60000; //max time that can be spent per recursive resolution task
  85. static readonly IPEndPoint IPENDPOINT_ANY_0 = new IPEndPoint(IPAddress.Any, 0);
  86. static readonly IReadOnlyCollection<DnsARecordData> _aRecords = [new DnsARecordData(IPAddress.Any)];
  87. static readonly IReadOnlyCollection<DnsAAAARecordData> _aaaaRecords = [new DnsAAAARecordData(IPAddress.IPv6Any)];
  88. static readonly List<SslApplicationProtocol> quicApplicationProtocols = new List<SslApplicationProtocol>() { new SslApplicationProtocol("doq") };
  89. string _serverDomain;
  90. readonly string _configFolder;
  91. readonly string _dohwwwFolder;
  92. IReadOnlyList<IPEndPoint> _localEndPoints;
  93. LogManager _log;
  94. MailAddress _responsiblePerson;
  95. MailAddress _defaultResponsiblePerson;
  96. NameServerAddress _thisServer;
  97. readonly List<Socket> _udpListeners = new List<Socket>();
  98. readonly List<Socket> _udpProxyListeners = new List<Socket>();
  99. readonly List<Socket> _tcpListeners = new List<Socket>();
  100. readonly List<Socket> _tcpProxyListeners = new List<Socket>();
  101. readonly List<Socket> _tlsListeners = new List<Socket>();
  102. readonly List<QuicListener> _quicListeners = new List<QuicListener>();
  103. WebApplication _dohWebService;
  104. readonly AuthZoneManager _authZoneManager;
  105. readonly AllowedZoneManager _allowedZoneManager;
  106. readonly BlockedZoneManager _blockedZoneManager;
  107. readonly BlockListZoneManager _blockListZoneManager;
  108. readonly CacheZoneManager _cacheZoneManager;
  109. readonly DnsApplicationManager _dnsApplicationManager;
  110. readonly ResolverDnsCache _dnsCache;
  111. readonly ResolverDnsCache _dnsCacheSkipDnsApps; //to prevent request reaching apps again
  112. readonly StatsManager _stats;
  113. IReadOnlyCollection<NetworkAddress> _zoneTransferAllowedNetworks;
  114. IReadOnlyCollection<NetworkAddress> _notifyAllowedNetworks;
  115. bool _preferIPv6;
  116. ushort _udpPayloadSize = DnsDatagram.EDNS_DEFAULT_UDP_PAYLOAD_SIZE;
  117. bool _dnssecValidation = true;
  118. bool _eDnsClientSubnet;
  119. byte _eDnsClientSubnetIPv4PrefixLength = 24;
  120. byte _eDnsClientSubnetIPv6PrefixLength = 56;
  121. NetworkAddress _eDnsClientSubnetIpv4Override;
  122. NetworkAddress _eDnsClientSubnetIpv6Override;
  123. int _qpmLimitRequests = 6000; //100qps
  124. int _qpmLimitErrors = 600; //10qps
  125. int _qpmLimitSampleMinutes = 5;
  126. int _qpmLimitIPv4PrefixLength = 24;
  127. int _qpmLimitIPv6PrefixLength = 56;
  128. IReadOnlyCollection<NetworkAddress> _qpmLimitBypassList;
  129. int _clientTimeout = 2000;
  130. int _tcpSendTimeout = 10000;
  131. int _tcpReceiveTimeout = 10000;
  132. int _quicIdleTimeout = 60000;
  133. int _quicMaxInboundStreams = 100;
  134. int _listenBacklog = 100;
  135. bool _enableDnsOverUdpProxy;
  136. bool _enableDnsOverTcpProxy;
  137. bool _enableDnsOverHttp;
  138. bool _enableDnsOverTls;
  139. bool _enableDnsOverHttps;
  140. bool _enableDnsOverHttp3;
  141. bool _enableDnsOverQuic;
  142. int _dnsOverUdpProxyPort = 538;
  143. int _dnsOverTcpProxyPort = 538;
  144. int _dnsOverHttpPort = 80;
  145. int _dnsOverTlsPort = 853;
  146. int _dnsOverHttpsPort = 443;
  147. int _dnsOverQuicPort = 853;
  148. X509Certificate2Collection _certificateCollection;
  149. SslServerAuthenticationOptions _sslServerAuthenticationOptions;
  150. SslServerAuthenticationOptions _quicSslServerAuthenticationOptions;
  151. string _dnsOverHttpRealIpHeader = "X-Real-IP";
  152. IReadOnlyDictionary<string, TsigKey> _tsigKeys;
  153. DnsServerRecursion _recursion;
  154. IReadOnlyCollection<NetworkAccessControl> _recursionNetworkACL;
  155. bool _randomizeName;
  156. bool _qnameMinimization;
  157. bool _nsRevalidation;
  158. int _resolverRetries = 2;
  159. int _resolverTimeout = 1500;
  160. int _resolverConcurrency = 2;
  161. int _resolverMaxStackCount = 16;
  162. bool _serveStale = true;
  163. int _serveStaleMaxWaitTime = SERVE_STALE_MAX_WAIT_TIME;
  164. int _cachePrefetchEligibility = 2;
  165. int _cachePrefetchTrigger = 9;
  166. int _cachePrefetchSampleIntervalInMinutes = 5;
  167. int _cachePrefetchSampleEligibilityHitsPerHour = 30;
  168. bool _enableBlocking = true;
  169. bool _allowTxtBlockingReport = true;
  170. IReadOnlyCollection<NetworkAddress> _blockingBypassList;
  171. DnsServerBlockingType _blockingType = DnsServerBlockingType.NxDomain;
  172. uint _blockingAnswerTtl = 30;
  173. IReadOnlyCollection<DnsARecordData> _customBlockingARecords = Array.Empty<DnsARecordData>();
  174. IReadOnlyCollection<DnsAAAARecordData> _customBlockingAAAARecords = Array.Empty<DnsAAAARecordData>();
  175. NetProxy _proxy;
  176. IReadOnlyList<NameServerAddress> _forwarders;
  177. bool _concurrentForwarding = true;
  178. int _forwarderRetries = 3;
  179. int _forwarderTimeout = 2000;
  180. int _forwarderConcurrency = 2;
  181. LogManager _resolverLog;
  182. LogManager _queryLog;
  183. Timer _cachePrefetchSamplingTimer;
  184. readonly object _cachePrefetchSamplingTimerLock = new object();
  185. const int CACHE_PREFETCH_SAMPLING_TIMER_INITIAL_INTEVAL = 5000;
  186. Timer _cachePrefetchRefreshTimer;
  187. readonly object _cachePrefetchRefreshTimerLock = new object();
  188. const int CACHE_PREFETCH_REFRESH_TIMER_INITIAL_INTEVAL = 10000;
  189. DateTime _cachePrefetchSamplingTimerTriggersOn;
  190. IList<CacheRefreshSample> _cacheRefreshSampleList;
  191. Timer _cacheMaintenanceTimer;
  192. readonly object _cacheMaintenanceTimerLock = new object();
  193. const int CACHE_MAINTENANCE_TIMER_INITIAL_INTEVAL = 5 * 60 * 1000;
  194. const int CACHE_MAINTENANCE_TIMER_PERIODIC_INTERVAL = 5 * 60 * 1000;
  195. Timer _qpmLimitSamplingTimer;
  196. readonly object _qpmLimitSamplingTimerLock = new object();
  197. const int QPM_LIMIT_SAMPLING_TIMER_INTERVAL = 10000;
  198. IReadOnlyDictionary<IPAddress, long> _qpmLimitClientSubnetStats;
  199. IReadOnlyDictionary<IPAddress, long> _qpmLimitErrorClientSubnetStats;
  200. readonly IndependentTaskScheduler _queryTaskScheduler = new IndependentTaskScheduler();
  201. readonly IndependentTaskScheduler _resolverTaskScheduler = new IndependentTaskScheduler(ThreadPriority.AboveNormal);
  202. readonly ConcurrentDictionary<string, Task<RecursiveResolveResponse>> _resolverTasks = new ConcurrentDictionary<string, Task<RecursiveResolveResponse>>();
  203. volatile ServiceState _state = ServiceState.Stopped;
  204. #endregion
  205. #region constructor
  206. static DnsServer()
  207. {
  208. //set min threads since the default value is too small
  209. {
  210. ThreadPool.GetMinThreads(out int minWorker, out int minIOC);
  211. int minThreads = Environment.ProcessorCount * 16;
  212. if (minWorker < minThreads)
  213. minWorker = minThreads;
  214. if (minIOC < minThreads)
  215. minIOC = minThreads;
  216. ThreadPool.SetMinThreads(minWorker, minIOC);
  217. }
  218. }
  219. public DnsServer(string serverDomain, string configFolder, string dohwwwFolder, LogManager log = null)
  220. : this(serverDomain, configFolder, dohwwwFolder, new IPEndPoint[] { new IPEndPoint(IPAddress.Any, 53), new IPEndPoint(IPAddress.IPv6Any, 53) }, log)
  221. { }
  222. public DnsServer(string serverDomain, string configFolder, string dohwwwFolder, IPEndPoint localEndPoint, LogManager log = null)
  223. : this(serverDomain, configFolder, dohwwwFolder, new IPEndPoint[] { localEndPoint }, log)
  224. { }
  225. public DnsServer(string serverDomain, string configFolder, string dohwwwFolder, IReadOnlyList<IPEndPoint> localEndPoints, LogManager log = null)
  226. {
  227. _serverDomain = serverDomain;
  228. _configFolder = configFolder;
  229. _dohwwwFolder = dohwwwFolder;
  230. _localEndPoints = localEndPoints;
  231. _log = log;
  232. _authZoneManager = new AuthZoneManager(this);
  233. _allowedZoneManager = new AllowedZoneManager(this);
  234. _blockedZoneManager = new BlockedZoneManager(this);
  235. _blockListZoneManager = new BlockListZoneManager(this);
  236. _cacheZoneManager = new CacheZoneManager(this);
  237. _dnsApplicationManager = new DnsApplicationManager(this);
  238. _dnsCache = new ResolverDnsCache(this, false);
  239. _dnsCacheSkipDnsApps = new ResolverDnsCache(this, true); //to prevent request reaching apps again
  240. //init stats
  241. _stats = new StatsManager(this);
  242. }
  243. #endregion
  244. #region IDisposable
  245. bool _disposed;
  246. public async ValueTask DisposeAsync()
  247. {
  248. if (_disposed)
  249. return;
  250. await StopAsync();
  251. _authZoneManager?.Dispose();
  252. _allowedZoneManager?.Dispose();
  253. _blockedZoneManager?.Dispose();
  254. _dnsApplicationManager?.Dispose();
  255. _stats?.Dispose();
  256. _disposed = true;
  257. }
  258. public void Dispose()
  259. {
  260. DisposeAsync().Sync();
  261. }
  262. #endregion
  263. #region private
  264. private async Task ReadUdpRequestAsync(Socket udpListener, DnsTransportProtocol protocol)
  265. {
  266. byte[] recvBuffer;
  267. if (protocol == DnsTransportProtocol.UdpProxy)
  268. recvBuffer = new byte[DnsDatagram.EDNS_MAX_UDP_PAYLOAD_SIZE + 256];
  269. else
  270. recvBuffer = new byte[DnsDatagram.EDNS_MAX_UDP_PAYLOAD_SIZE];
  271. using MemoryStream recvBufferStream = new MemoryStream(recvBuffer);
  272. try
  273. {
  274. int localPort = (udpListener.LocalEndPoint as IPEndPoint).Port;
  275. EndPoint epAny;
  276. switch (udpListener.AddressFamily)
  277. {
  278. case AddressFamily.InterNetwork:
  279. epAny = new IPEndPoint(IPAddress.Any, 0);
  280. break;
  281. case AddressFamily.InterNetworkV6:
  282. epAny = new IPEndPoint(IPAddress.IPv6Any, 0);
  283. break;
  284. default:
  285. throw new NotSupportedException("AddressFamily not supported.");
  286. }
  287. SocketReceiveMessageFromResult result;
  288. while (true)
  289. {
  290. recvBufferStream.SetLength(DnsDatagram.EDNS_MAX_UDP_PAYLOAD_SIZE); //resetting length before using buffer
  291. try
  292. {
  293. result = await udpListener.ReceiveMessageFromAsync(recvBuffer, SocketFlags.None, epAny);
  294. }
  295. catch (SocketException ex)
  296. {
  297. switch (ex.SocketErrorCode)
  298. {
  299. case SocketError.ConnectionReset:
  300. case SocketError.HostUnreachable:
  301. case SocketError.MessageSize:
  302. case SocketError.NetworkReset:
  303. result = default;
  304. break;
  305. default:
  306. throw;
  307. }
  308. }
  309. if (result.ReceivedBytes > 0)
  310. {
  311. if (result.RemoteEndPoint is not IPEndPoint remoteEP)
  312. continue;
  313. try
  314. {
  315. recvBufferStream.Position = 0;
  316. recvBufferStream.SetLength(result.ReceivedBytes);
  317. IPEndPoint returnEP = remoteEP;
  318. if (protocol == DnsTransportProtocol.UdpProxy)
  319. {
  320. if (!NetUtilities.IsPrivateIP(remoteEP.Address))
  321. {
  322. //intentionally blocking public IP addresses from using DNS-over-UDP-PROXY
  323. //this feature is intended to be used with a reverse proxy or load balancer on private network
  324. continue;
  325. }
  326. ProxyProtocolStream proxyStream = await ProxyProtocolStream.CreateAsServerAsync(recvBufferStream);
  327. remoteEP = new IPEndPoint(proxyStream.SourceAddress, proxyStream.SourcePort);
  328. recvBufferStream.Position = proxyStream.DataOffset;
  329. }
  330. if (IsQpmLimitCrossed(remoteEP.Address))
  331. {
  332. _stats.QueueUpdate(null, remoteEP, protocol, null, true);
  333. continue;
  334. }
  335. DnsDatagram request = DnsDatagram.ReadFrom(recvBufferStream);
  336. request.SetMetadata(new NameServerAddress(new IPEndPoint(result.PacketInformation.Address, localPort), DnsTransportProtocol.Udp));
  337. _ = ProcessUdpRequestAsync(udpListener, remoteEP, returnEP, protocol, request);
  338. }
  339. catch (EndOfStreamException)
  340. {
  341. //ignore incomplete udp datagrams
  342. }
  343. catch (Exception ex)
  344. {
  345. _log?.Write(remoteEP, protocol, ex);
  346. }
  347. }
  348. }
  349. }
  350. catch (ObjectDisposedException)
  351. {
  352. //server stopping
  353. }
  354. catch (SocketException ex)
  355. {
  356. switch (ex.SocketErrorCode)
  357. {
  358. case SocketError.OperationAborted:
  359. case SocketError.Interrupted:
  360. break; //server stopping
  361. default:
  362. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  363. return; //server stopping
  364. _log?.Write(ex);
  365. break;
  366. }
  367. }
  368. catch (Exception ex)
  369. {
  370. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  371. return; //server stopping
  372. _log?.Write(ex);
  373. }
  374. }
  375. private async Task ProcessUdpRequestAsync(Socket udpListener, IPEndPoint remoteEP, IPEndPoint returnEP, DnsTransportProtocol protocol, DnsDatagram request)
  376. {
  377. byte[] sendBuffer = null;
  378. try
  379. {
  380. DnsDatagram response = await ProcessRequestAsync(request, remoteEP, protocol, IsRecursionAllowed(remoteEP.Address));
  381. if (response is null)
  382. {
  383. _stats.QueueUpdate(null, remoteEP, protocol, null, false);
  384. return; //drop request
  385. }
  386. //send response
  387. int sendBufferSize;
  388. if (request.EDNS is null)
  389. sendBufferSize = 512;
  390. else if (request.EDNS.UdpPayloadSize > _udpPayloadSize)
  391. sendBufferSize = _udpPayloadSize;
  392. else
  393. sendBufferSize = request.EDNS.UdpPayloadSize;
  394. sendBuffer = ArrayPool<byte>.Shared.Rent(sendBufferSize);
  395. using (MemoryStream sendBufferStream = new MemoryStream(sendBuffer, 0, sendBufferSize))
  396. {
  397. try
  398. {
  399. response.WriteTo(sendBufferStream);
  400. }
  401. catch (NotSupportedException)
  402. {
  403. if (response.IsSigned)
  404. {
  405. //rfc8945 section 5.3
  406. 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 };
  407. }
  408. else
  409. {
  410. switch (response.Question[0].Type)
  411. {
  412. case DnsResourceRecordType.MX:
  413. case DnsResourceRecordType.SRV:
  414. case DnsResourceRecordType.SVCB:
  415. case DnsResourceRecordType.HTTPS:
  416. //removing glue records and trying again since some mail servers fail to fallback to TCP on truncation
  417. //removing glue records to prevent truncation for SRV/SVCB/HTTPS
  418. response = response.CloneWithoutGlueRecords();
  419. sendBufferStream.Position = 0;
  420. try
  421. {
  422. response.WriteTo(sendBufferStream);
  423. }
  424. catch (NotSupportedException)
  425. {
  426. //send TC since response is still big even after removing glue records
  427. 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 };
  428. }
  429. break;
  430. case DnsResourceRecordType.IXFR:
  431. 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
  432. break;
  433. default:
  434. 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 };
  435. break;
  436. }
  437. }
  438. sendBufferStream.Position = 0;
  439. response.WriteTo(sendBufferStream);
  440. }
  441. //send dns datagram async
  442. await udpListener.SendToAsync(new ArraySegment<byte>(sendBuffer, 0, (int)sendBufferStream.Position), SocketFlags.None, returnEP);
  443. }
  444. _queryLog?.Write(remoteEP, protocol, request, response);
  445. _stats.QueueUpdate(request, remoteEP, protocol, response, false);
  446. }
  447. catch (Exception ex)
  448. {
  449. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  450. return; //server stopping
  451. _queryLog?.Write(remoteEP, protocol, request, null);
  452. _log?.Write(remoteEP, protocol, ex);
  453. }
  454. finally
  455. {
  456. if (sendBuffer is not null)
  457. ArrayPool<byte>.Shared.Return(sendBuffer);
  458. }
  459. }
  460. private async Task AcceptConnectionAsync(Socket tcpListener, DnsTransportProtocol protocol)
  461. {
  462. IPEndPoint localEP = tcpListener.LocalEndPoint as IPEndPoint;
  463. try
  464. {
  465. tcpListener.SendTimeout = _tcpSendTimeout;
  466. tcpListener.ReceiveTimeout = _tcpReceiveTimeout;
  467. tcpListener.NoDelay = true;
  468. while (true)
  469. {
  470. Socket socket = await tcpListener.AcceptAsync();
  471. _ = ProcessConnectionAsync(socket, protocol);
  472. }
  473. }
  474. catch (SocketException ex)
  475. {
  476. if (ex.SocketErrorCode == SocketError.OperationAborted)
  477. return; //server stopping
  478. _log?.Write(localEP, protocol, ex);
  479. }
  480. catch (ObjectDisposedException)
  481. {
  482. //server stopped
  483. }
  484. catch (Exception ex)
  485. {
  486. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  487. return; //server stopping
  488. _log?.Write(localEP, protocol, ex);
  489. }
  490. }
  491. private async Task ProcessConnectionAsync(Socket socket, DnsTransportProtocol protocol)
  492. {
  493. IPEndPoint remoteEP = null;
  494. try
  495. {
  496. remoteEP = socket.RemoteEndPoint as IPEndPoint;
  497. switch (protocol)
  498. {
  499. case DnsTransportProtocol.Tcp:
  500. await ReadStreamRequestAsync(new NetworkStream(socket), remoteEP, new NameServerAddress(socket.LocalEndPoint, DnsTransportProtocol.Tcp), protocol);
  501. break;
  502. case DnsTransportProtocol.Tls:
  503. SslStream tlsStream = new SslStream(new NetworkStream(socket));
  504. string serverName = null;
  505. await TechnitiumLibrary.TaskExtensions.TimeoutAsync(delegate (CancellationToken cancellationToken1)
  506. {
  507. return tlsStream.AuthenticateAsServerAsync(delegate (SslStream stream, SslClientHelloInfo clientHelloInfo, object state, CancellationToken cancellationToken)
  508. {
  509. serverName = clientHelloInfo.ServerName;
  510. return ValueTask.FromResult(_sslServerAuthenticationOptions);
  511. }, null, cancellationToken1);
  512. }, _tcpReceiveTimeout);
  513. NameServerAddress dnsEP;
  514. if (string.IsNullOrEmpty(serverName))
  515. dnsEP = new NameServerAddress(socket.LocalEndPoint, DnsTransportProtocol.Tls);
  516. else
  517. dnsEP = new NameServerAddress(serverName, socket.LocalEndPoint as IPEndPoint, DnsTransportProtocol.Tls);
  518. await ReadStreamRequestAsync(tlsStream, remoteEP, dnsEP, protocol);
  519. break;
  520. case DnsTransportProtocol.TcpProxy:
  521. if (!NetUtilities.IsPrivateIP(remoteEP.Address))
  522. {
  523. //intentionally blocking public IP addresses from using DNS-over-TCP-PROXY
  524. //this feature is intended to be used with a reverse proxy or load balancer on private network
  525. return;
  526. }
  527. ProxyProtocolStream proxyStream = await TechnitiumLibrary.TaskExtensions.TimeoutAsync(delegate (CancellationToken cancellationToken1)
  528. {
  529. return ProxyProtocolStream.CreateAsServerAsync(new NetworkStream(socket), cancellationToken1);
  530. }, _tcpReceiveTimeout);
  531. remoteEP = new IPEndPoint(proxyStream.SourceAddress, proxyStream.SourcePort);
  532. await ReadStreamRequestAsync(proxyStream, remoteEP, new NameServerAddress(socket.LocalEndPoint, DnsTransportProtocol.Tcp), protocol);
  533. break;
  534. default:
  535. throw new InvalidOperationException();
  536. }
  537. }
  538. catch (AuthenticationException)
  539. {
  540. //ignore TLS auth exception
  541. }
  542. catch (TimeoutException)
  543. {
  544. //ignore timeout exception on TLS auth
  545. }
  546. catch (IOException)
  547. {
  548. //ignore IO exceptions
  549. }
  550. catch (Exception ex)
  551. {
  552. _log?.Write(remoteEP, protocol, ex);
  553. }
  554. finally
  555. {
  556. socket.Dispose();
  557. }
  558. }
  559. private async Task ReadStreamRequestAsync(Stream stream, IPEndPoint remoteEP, NameServerAddress dnsEP, DnsTransportProtocol protocol)
  560. {
  561. try
  562. {
  563. using MemoryStream readBuffer = new MemoryStream(64);
  564. using MemoryStream writeBuffer = new MemoryStream(2048);
  565. using SemaphoreSlim writeSemaphore = new SemaphoreSlim(1, 1);
  566. while (true)
  567. {
  568. if (IsQpmLimitCrossed(remoteEP.Address))
  569. {
  570. _stats.QueueUpdate(null, remoteEP, protocol, null, true);
  571. break;
  572. }
  573. DnsDatagram request;
  574. //read dns datagram with timeout
  575. using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource())
  576. {
  577. Task<DnsDatagram> task = DnsDatagram.ReadFromTcpAsync(stream, readBuffer, cancellationTokenSource.Token);
  578. if (await Task.WhenAny(task, Task.Delay(_tcpReceiveTimeout, cancellationTokenSource.Token)) != task)
  579. {
  580. //read timed out
  581. await stream.DisposeAsync();
  582. return;
  583. }
  584. cancellationTokenSource.Cancel(); //cancel delay task
  585. request = await task;
  586. request.SetMetadata(dnsEP);
  587. }
  588. //process request async
  589. _ = ProcessStreamRequestAsync(stream, writeBuffer, writeSemaphore, remoteEP, request, protocol);
  590. }
  591. }
  592. catch (ObjectDisposedException)
  593. {
  594. //ignore
  595. }
  596. catch (IOException)
  597. {
  598. //ignore IO exceptions
  599. }
  600. catch (Exception ex)
  601. {
  602. _log?.Write(remoteEP, protocol, ex);
  603. }
  604. }
  605. private async Task ProcessStreamRequestAsync(Stream stream, MemoryStream writeBuffer, SemaphoreSlim writeSemaphore, IPEndPoint remoteEP, DnsDatagram request, DnsTransportProtocol protocol)
  606. {
  607. try
  608. {
  609. DnsDatagram response = await ProcessRequestAsync(request, remoteEP, protocol, IsRecursionAllowed(remoteEP.Address));
  610. if (response is null)
  611. {
  612. await stream.DisposeAsync();
  613. _stats.QueueUpdate(null, remoteEP, protocol, null, false);
  614. return; //drop request
  615. }
  616. //send response
  617. await TechnitiumLibrary.TaskExtensions.TimeoutAsync(async delegate (CancellationToken cancellationToken1)
  618. {
  619. await writeSemaphore.WaitAsync(cancellationToken1);
  620. try
  621. {
  622. //send dns datagram
  623. await response.WriteToTcpAsync(stream, writeBuffer, cancellationToken1);
  624. await stream.FlushAsync(cancellationToken1);
  625. }
  626. finally
  627. {
  628. writeSemaphore.Release();
  629. }
  630. }, _tcpSendTimeout);
  631. _queryLog?.Write(remoteEP, protocol, request, response);
  632. _stats.QueueUpdate(request, remoteEP, protocol, response, false);
  633. }
  634. catch (ObjectDisposedException)
  635. {
  636. //ignore
  637. }
  638. catch (IOException)
  639. {
  640. //ignore IO exceptions
  641. }
  642. catch (Exception ex)
  643. {
  644. if (request is not null)
  645. _queryLog.Write(remoteEP, protocol, request, null);
  646. _log?.Write(remoteEP, protocol, ex);
  647. }
  648. }
  649. private async Task AcceptQuicConnectionAsync(QuicListener quicListener)
  650. {
  651. try
  652. {
  653. while (true)
  654. {
  655. QuicConnection quicConnection = await quicListener.AcceptConnectionAsync();
  656. _ = ProcessQuicConnectionAsync(quicConnection);
  657. }
  658. }
  659. catch (ObjectDisposedException)
  660. {
  661. //server stopped
  662. }
  663. catch (Exception ex)
  664. {
  665. if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
  666. return; //server stopping
  667. _log?.Write(quicListener.LocalEndPoint, DnsTransportProtocol.Quic, ex);
  668. }
  669. }
  670. private async Task ProcessQuicConnectionAsync(QuicConnection quicConnection)
  671. {
  672. try
  673. {
  674. NameServerAddress dnsEP;
  675. if (string.IsNullOrEmpty(quicConnection.TargetHostName))
  676. dnsEP = new NameServerAddress(quicConnection.LocalEndPoint, DnsTransportProtocol.Quic);
  677. else
  678. dnsEP = new NameServerAddress(quicConnection.TargetHostName, quicConnection.LocalEndPoint, DnsTransportProtocol.Quic);
  679. while (true)
  680. {
  681. if (IsQpmLimitCrossed(quicConnection.RemoteEndPoint.Address))
  682. {
  683. _stats.QueueUpdate(null, quicConnection.RemoteEndPoint, DnsTransportProtocol.Quic, null, true);
  684. break;
  685. }
  686. QuicStream quicStream = await quicConnection.AcceptInboundStreamAsync();
  687. _ = ProcessQuicStreamRequestAsync(quicStream, quicConnection.RemoteEndPoint, dnsEP);
  688. }
  689. }
  690. catch (QuicException ex)
  691. {
  692. switch (ex.QuicError)
  693. {
  694. case QuicError.ConnectionIdle:
  695. case QuicError.ConnectionAborted:
  696. case QuicError.ConnectionTimeout:
  697. break;
  698. default:
  699. _log?.Write(quicConnection.RemoteEndPoint, DnsTransportProtocol.Quic, ex);
  700. break;
  701. }
  702. }
  703. catch (Exception ex)
  704. {
  705. _log?.Write(quicConnection.RemoteEndPoint, DnsTransportProtocol.Quic, ex);
  706. }
  707. finally
  708. {
  709. await quicConnection.DisposeAsync();
  710. }
  711. }
  712. private async Task ProcessQuicStreamRequestAsync(QuicStream quicStream, IPEndPoint remoteEP, NameServerAddress dnsEP)
  713. {
  714. MemoryStream sharedBuffer = new MemoryStream(512);
  715. DnsDatagram request = null;
  716. try
  717. {
  718. //read dns datagram with timeout
  719. using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource())
  720. {
  721. Task<DnsDatagram> task = DnsDatagram.ReadFromTcpAsync(quicStream, sharedBuffer, cancellationTokenSource.Token);
  722. if (await Task.WhenAny(task, Task.Delay(_tcpReceiveTimeout, cancellationTokenSource.Token)) != task)
  723. {
  724. //read timed out
  725. quicStream.Abort(QuicAbortDirection.Both, (long)DnsOverQuicErrorCodes.DOQ_UNSPECIFIED_ERROR);
  726. return;
  727. }
  728. cancellationTokenSource.Cancel(); //cancel delay task
  729. request = await task;
  730. request.SetMetadata(dnsEP);
  731. }
  732. //process request async
  733. DnsDatagram response = await ProcessRequestAsync(request, remoteEP, DnsTransportProtocol.Quic, IsRecursionAllowed(remoteEP.Address));
  734. if (response is null)
  735. {
  736. _stats.QueueUpdate(null, remoteEP, DnsTransportProtocol.Quic, null, false);
  737. return; //drop request
  738. }
  739. //send response
  740. await response.WriteToTcpAsync(quicStream, sharedBuffer);
  741. _queryLog?.Write(remoteEP, DnsTransportProtocol.Quic, request, response);
  742. _stats.QueueUpdate(request, remoteEP, DnsTransportProtocol.Quic, response, false);
  743. }
  744. catch (IOException)
  745. {
  746. //ignore QuicException / IOException
  747. }
  748. catch (Exception ex)
  749. {
  750. if (request is not null)
  751. _queryLog.Write(remoteEP, DnsTransportProtocol.Quic, request, null);
  752. _log?.Write(remoteEP, DnsTransportProtocol.Quic, ex);
  753. }
  754. finally
  755. {
  756. await sharedBuffer.DisposeAsync();
  757. await quicStream.DisposeAsync();
  758. }
  759. }
  760. private async Task ProcessDoHRequestAsync(HttpContext context)
  761. {
  762. IPEndPoint remoteEP = context.GetRemoteEndPoint(_dnsOverHttpRealIpHeader);
  763. DnsDatagram dnsRequest = null;
  764. try
  765. {
  766. HttpRequest request = context.Request;
  767. HttpResponse response = context.Response;
  768. if (IsQpmLimitCrossed(remoteEP.Address))
  769. {
  770. _stats.QueueUpdate(null, remoteEP, DnsTransportProtocol.Https, null, true);
  771. response.StatusCode = 429;
  772. await response.WriteAsync("Too Many Requests");
  773. return;
  774. }
  775. if (!request.IsHttps)
  776. {
  777. //get the actual connection remote EP
  778. IPEndPoint connectionEp = context.GetRemoteEndPoint(null);
  779. if (!NetUtilities.IsPrivateIP(connectionEp.Address))
  780. {
  781. //intentionally blocking public IP addresses from using DNS-over-HTTP (without TLS)
  782. //this feature is intended to be used with an SSL terminated reverse proxy like nginx on private network
  783. response.StatusCode = 403;
  784. await response.WriteAsync("DNS-over-HTTPS (DoH) queries are supported only on HTTPS.");
  785. return;
  786. }
  787. }
  788. switch (request.Method)
  789. {
  790. case "GET":
  791. bool acceptsDoH = false;
  792. string requestAccept = request.Headers.Accept;
  793. if (string.IsNullOrEmpty(requestAccept))
  794. {
  795. acceptsDoH = true;
  796. }
  797. else
  798. {
  799. foreach (string mediaType in requestAccept.Split(','))
  800. {
  801. if (mediaType.Equals("application/dns-message", StringComparison.OrdinalIgnoreCase))
  802. {
  803. acceptsDoH = true;
  804. break;
  805. }
  806. }
  807. }
  808. if (!acceptsDoH)
  809. {
  810. response.Redirect((request.IsHttps ? "https://" : "http://") + request.Headers.Host);
  811. return;
  812. }
  813. string dnsRequestBase64Url = request.Query["dns"];
  814. if (string.IsNullOrEmpty(dnsRequestBase64Url))
  815. {
  816. response.StatusCode = 400;
  817. await response.WriteAsync("Bad Request");
  818. return;
  819. }
  820. //convert from base64url to base64
  821. dnsRequestBase64Url = dnsRequestBase64Url.Replace('-', '+');
  822. dnsRequestBase64Url = dnsRequestBase64Url.Replace('_', '/');
  823. //add padding
  824. int x = dnsRequestBase64Url.Length % 4;
  825. if (x > 0)
  826. dnsRequestBase64Url = dnsRequestBase64Url.PadRight(dnsRequestBase64Url.Length - x + 4, '=');
  827. using (MemoryStream mS = new MemoryStream(Convert.FromBase64String(dnsRequestBase64Url)))
  828. {
  829. dnsRequest = DnsDatagram.ReadFrom(mS);
  830. dnsRequest.SetMetadata(new NameServerAddress(new Uri(context.Request.GetDisplayUrl()), context.GetLocalIpAddress()));
  831. }
  832. break;
  833. case "POST":
  834. if (!string.Equals(request.Headers.ContentType, "application/dns-message", StringComparison.OrdinalIgnoreCase))
  835. {
  836. response.StatusCode = 415;
  837. await response.WriteAsync("Unsupported Media Type");
  838. return;
  839. }
  840. using (MemoryStream mS = new MemoryStream(32))
  841. {
  842. await request.Body.CopyToAsync(mS, 32);
  843. mS.Position = 0;
  844. dnsRequest = DnsDatagram.ReadFrom(mS);
  845. dnsRequest.SetMetadata(new NameServerAddress(new Uri(context.Request.GetDisplayUrl()), context.GetLocalIpAddress()));
  846. }
  847. break;
  848. default:
  849. throw new InvalidOperationException();
  850. }
  851. DnsDatagram dnsResponse = await ProcessRequestAsync(dnsRequest, remoteEP, DnsTransportProtocol.Https, IsRecursionAllowed(remoteEP.Address));
  852. if (dnsResponse is null)
  853. {
  854. //drop request
  855. context.Connection.RequestClose();
  856. _stats.QueueUpdate(null, remoteEP, DnsTransportProtocol.Https, null, false);
  857. return;
  858. }
  859. using (MemoryStream mS = new MemoryStream(512))
  860. {
  861. dnsResponse.WriteTo(mS);
  862. mS.Position = 0;
  863. response.ContentType = "application/dns-message";
  864. response.ContentLength = mS.Length;
  865. await TechnitiumLibrary.TaskExtensions.TimeoutAsync(async delegate (CancellationToken cancellationToken1)
  866. {
  867. await using (Stream s = response.Body)
  868. {
  869. await mS.CopyToAsync(s, 512, cancellationToken1);
  870. }
  871. }, _tcpSendTimeout);
  872. }
  873. _queryLog?.Write(remoteEP, DnsTransportProtocol.Https, dnsRequest, dnsResponse);
  874. _stats.QueueUpdate(dnsRequest, remoteEP, DnsTransportProtocol.Https, dnsResponse, false);
  875. }
  876. catch (IOException)
  877. {
  878. //ignore IO exceptions
  879. }
  880. catch (Exception ex)
  881. {
  882. if (dnsRequest is not null)
  883. _queryLog?.Write(remoteEP, DnsTransportProtocol.Https, dnsRequest, null);
  884. _log?.Write(remoteEP, DnsTransportProtocol.Https, ex);
  885. }
  886. }
  887. private bool IsRecursionAllowed(IPAddress remoteIP)
  888. {
  889. switch (_recursion)
  890. {
  891. case DnsServerRecursion.Allow:
  892. return true;
  893. case DnsServerRecursion.AllowOnlyForPrivateNetworks:
  894. switch (remoteIP.AddressFamily)
  895. {
  896. case AddressFamily.InterNetwork:
  897. case AddressFamily.InterNetworkV6:
  898. return NetUtilities.IsPrivateIP(remoteIP);
  899. default:
  900. return false;
  901. }
  902. case DnsServerRecursion.UseSpecifiedNetworkACL:
  903. return NetworkAccessControl.IsAddressAllowed(remoteIP, _recursionNetworkACL, true);
  904. default:
  905. return false;
  906. }
  907. }
  908. private async Task<DnsDatagram> ProcessRequestAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed)
  909. {
  910. foreach (IDnsRequestController requestController in _dnsApplicationManager.DnsRequestControllers)
  911. {
  912. try
  913. {
  914. DnsRequestControllerAction action = await requestController.GetRequestActionAsync(request, remoteEP, protocol);
  915. switch (action)
  916. {
  917. case DnsRequestControllerAction.DropSilently:
  918. return null; //drop request
  919. case DnsRequestControllerAction.DropWithRefused:
  920. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, 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
  921. }
  922. }
  923. catch (Exception ex)
  924. {
  925. _log?.Write(remoteEP, protocol, ex);
  926. }
  927. }
  928. if (request.ParsingException is not null)
  929. {
  930. //format error
  931. if (request.ParsingException is not IOException)
  932. _log?.Write(remoteEP, protocol, request.ParsingException);
  933. //format error response
  934. return new DnsDatagram(request.Identifier, true, request.OPCODE, false, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, DnsResponseCode.FormatError, request.Question, null, null, null, request.EDNS is null ? ushort.MinValue : _udpPayloadSize, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None) { Tag = DnsServerResponseType.Authoritative };
  935. }
  936. if (request.IsSigned)
  937. {
  938. if (!request.VerifySignedRequest(_tsigKeys, out DnsDatagram unsignedRequest, out DnsDatagram errorResponse))
  939. {
  940. _log?.Write(remoteEP, protocol, "DNS Server received a request that failed TSIG signature verification (RCODE: " + errorResponse.RCODE + "; TSIG Error: " + errorResponse.TsigError + ")");
  941. errorResponse.Tag = DnsServerResponseType.Authoritative;
  942. return errorResponse;
  943. }
  944. DnsDatagram unsignedResponse = await ProcessQueryAsync(unsignedRequest, remoteEP, protocol, isRecursionAllowed, false, request.TsigKeyName);
  945. if (unsignedResponse is null)
  946. return null;
  947. unsignedResponse = await PostProcessQueryAsync(request, remoteEP, protocol, unsignedResponse);
  948. if (unsignedResponse is null)
  949. return null;
  950. return unsignedResponse.SignResponse(request, _tsigKeys);
  951. }
  952. if (request.EDNS is not null)
  953. {
  954. if (request.EDNS.Version != 0)
  955. return new DnsDatagram(request.Identifier, true, request.OPCODE, false, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, DnsResponseCode.BADVERS, request.Question, null, null, null, _udpPayloadSize, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None) { Tag = DnsServerResponseType.Authoritative };
  956. }
  957. DnsDatagram response = await ProcessQueryAsync(request, remoteEP, protocol, isRecursionAllowed, false, null);
  958. if (response is null)
  959. return null;
  960. return await PostProcessQueryAsync(request, remoteEP, protocol, response);
  961. }
  962. private async Task<DnsDatagram> PostProcessQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, DnsDatagram response)
  963. {
  964. foreach (IDnsPostProcessor postProcessor in _dnsApplicationManager.DnsPostProcessors)
  965. {
  966. try
  967. {
  968. response = await postProcessor.PostProcessAsync(request, remoteEP, protocol, response);
  969. if (response is null)
  970. return null;
  971. }
  972. catch (Exception ex)
  973. {
  974. _log?.Write(remoteEP, protocol, ex);
  975. }
  976. }
  977. if (request.EDNS is null)
  978. {
  979. if (response.EDNS is not null)
  980. response = response.CloneWithoutEDns();
  981. return response;
  982. }
  983. if (response.EDNS is not null)
  984. return response;
  985. IReadOnlyList<EDnsOption> options = null;
  986. EDnsClientSubnetOptionData requestECS = request.GetEDnsClientSubnetOption(true);
  987. if (requestECS is not null)
  988. options = EDnsClientSubnetOptionData.GetEDnsClientSubnetOption(requestECS.SourcePrefixLength, 0, requestECS.Address);
  989. if (response.Additional.Count == 0)
  990. return response.Clone(null, null, new DnsResourceRecord[] { DnsDatagramEdns.GetOPTFor(_udpPayloadSize, response.RCODE, 0, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, options) });
  991. if (response.IsSigned)
  992. return response;
  993. DnsResourceRecord[] newAdditional = new DnsResourceRecord[response.Additional.Count + 1];
  994. for (int i = 0; i < response.Additional.Count; i++)
  995. newAdditional[i] = response.Additional[i];
  996. newAdditional[response.Additional.Count] = DnsDatagramEdns.GetOPTFor(_udpPayloadSize, response.RCODE, 0, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, options);
  997. return response.Clone(null, null, newAdditional);
  998. }
  999. private async Task<DnsDatagram> ProcessQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, bool skipDnsAppAuthoritativeRequestHandlers, string tsigAuthenticatedKeyName)
  1000. {
  1001. if (request.IsResponse)
  1002. return null; //drop response datagram to avoid loops in rare scenarios
  1003. switch (request.OPCODE)
  1004. {
  1005. case DnsOpcode.StandardQuery:
  1006. if (request.Question.Count != 1)
  1007. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1008. if (request.Question[0].Class != DnsClass.IN)
  1009. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1010. try
  1011. {
  1012. DnsQuestionRecord question = request.Question[0];
  1013. switch (question.Type)
  1014. {
  1015. case DnsResourceRecordType.AXFR:
  1016. if (protocol == DnsTransportProtocol.Udp)
  1017. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, request.CheckingDisabled, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1018. return await ProcessZoneTransferQueryAsync(request, remoteEP, protocol, tsigAuthenticatedKeyName);
  1019. case DnsResourceRecordType.IXFR:
  1020. return await ProcessZoneTransferQueryAsync(request, remoteEP, protocol, tsigAuthenticatedKeyName);
  1021. case DnsResourceRecordType.FWD:
  1022. case DnsResourceRecordType.APP:
  1023. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1024. }
  1025. //query authoritative zone
  1026. DnsDatagram response = await ProcessAuthoritativeQueryAsync(request, remoteEP, protocol, isRecursionAllowed, skipDnsAppAuthoritativeRequestHandlers);
  1027. if (response is not null)
  1028. {
  1029. if ((question.Type == DnsResourceRecordType.ANY) && (protocol == DnsTransportProtocol.Udp)) //force TCP for ANY request
  1030. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, true, true, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, response.RCODE, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1031. return response;
  1032. }
  1033. if (!request.RecursionDesired || !isRecursionAllowed)
  1034. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1035. //do recursive query
  1036. if ((question.Type == DnsResourceRecordType.ANY) && (protocol == DnsTransportProtocol.Udp)) //force TCP for ANY request
  1037. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, true, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, DnsResponseCode.NoError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1038. return await ProcessRecursiveQueryAsync(request, remoteEP, protocol, null, _dnssecValidation, false, skipDnsAppAuthoritativeRequestHandlers);
  1039. }
  1040. catch (InvalidDomainNameException)
  1041. {
  1042. //format error response
  1043. return new DnsDatagram(request.Identifier, true, request.OPCODE, false, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1044. }
  1045. catch (TimeoutException ex)
  1046. {
  1047. DnsDatagram response = new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, DnsResponseCode.ServerFailure, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1048. _log?.Write(remoteEP, protocol, request, response);
  1049. _log?.Write(remoteEP, protocol, ex);
  1050. return response;
  1051. }
  1052. catch (Exception ex)
  1053. {
  1054. _log?.Write(remoteEP, protocol, ex);
  1055. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, DnsResponseCode.ServerFailure, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1056. }
  1057. case DnsOpcode.Notify:
  1058. return await ProcessNotifyQueryAsync(request, remoteEP, protocol);
  1059. case DnsOpcode.Update:
  1060. return await ProcessUpdateQueryAsync(request, remoteEP, protocol, tsigAuthenticatedKeyName);
  1061. default:
  1062. return new DnsDatagram(request.Identifier, true, request.OPCODE, false, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, DnsResponseCode.NotImplemented, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1063. }
  1064. }
  1065. private async Task<DnsDatagram> ProcessNotifyQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol)
  1066. {
  1067. AuthZoneInfo zoneInfo = _authZoneManager.GetAuthZoneInfo(request.Question[0].Name);
  1068. if ((zoneInfo is null) || ((zoneInfo.Type != AuthZoneType.Secondary) && (zoneInfo.Type != AuthZoneType.SecondaryForwarder) && (zoneInfo.Type != AuthZoneType.SecondaryCatalog)) || zoneInfo.Disabled)
  1069. return new DnsDatagram(request.Identifier, true, DnsOpcode.Notify, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1070. async Task<bool> RemoteVerifiedAsync(IPAddress remoteAddress)
  1071. {
  1072. if (_notifyAllowedNetworks is not null)
  1073. {
  1074. foreach (NetworkAddress notifyAllowedNetwork in _notifyAllowedNetworks)
  1075. {
  1076. if (notifyAllowedNetwork.Contains(remoteAddress))
  1077. return true;
  1078. }
  1079. }
  1080. IReadOnlyList<NameServerAddress> primaryNameServerAddresses;
  1081. SecondaryCatalogZone secondaryCatalogZone = zoneInfo.ApexZone.SecondaryCatalogZone;
  1082. if ((secondaryCatalogZone is not null) && !zoneInfo.OverrideCatalogPrimaryNameServers)
  1083. primaryNameServerAddresses = await zoneInfo.ApexZone.GetResolvedNameServerAddressesAsync(secondaryCatalogZone.PrimaryNameServerAddresses);
  1084. else
  1085. primaryNameServerAddresses = await zoneInfo.ApexZone.GetResolvedPrimaryNameServerAddressesAsync();
  1086. foreach (NameServerAddress primaryNameServer in primaryNameServerAddresses)
  1087. {
  1088. if (primaryNameServer.IPEndPoint.Address.Equals(remoteAddress))
  1089. return true;
  1090. }
  1091. return false;
  1092. }
  1093. if (!await RemoteVerifiedAsync(remoteEP.Address))
  1094. {
  1095. _log?.Write(remoteEP, protocol, "DNS Server refused a NOTIFY request since the request IP address was not recognized by the secondary zone: " + zoneInfo.DisplayName);
  1096. return new DnsDatagram(request.Identifier, true, DnsOpcode.Notify, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1097. }
  1098. _log?.Write(remoteEP, protocol, "DNS Server received a NOTIFY request for secondary zone: " + zoneInfo.DisplayName);
  1099. if ((request.Answer.Count > 0) && (request.Answer[0].Type == DnsResourceRecordType.SOA))
  1100. {
  1101. IReadOnlyList<DnsResourceRecord> localSoaRecords = zoneInfo.ApexZone.GetRecords(DnsResourceRecordType.SOA);
  1102. if (!DnsSOARecordData.IsZoneUpdateAvailable((localSoaRecords[0].RDATA as DnsSOARecordData).Serial, (request.Answer[0].RDATA as DnsSOARecordData).Serial))
  1103. {
  1104. //no update was available
  1105. return new DnsDatagram(request.Identifier, true, DnsOpcode.Notify, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NoError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1106. }
  1107. }
  1108. zoneInfo.TriggerRefresh();
  1109. return new DnsDatagram(request.Identifier, true, DnsOpcode.Notify, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NoError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1110. }
  1111. private async Task<DnsDatagram> ProcessUpdateQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, string tsigAuthenticatedKeyName)
  1112. {
  1113. if ((request.Question.Count != 1) || (request.Question[0].Type != DnsResourceRecordType.SOA))
  1114. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1115. if (request.Question[0].Class != DnsClass.IN)
  1116. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NotAuth, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1117. AuthZoneInfo zoneInfo = _authZoneManager.FindAuthZoneInfo(request.Question[0].Name);
  1118. if ((zoneInfo is null) || zoneInfo.Disabled)
  1119. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NotAuth, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1120. _log?.Write(remoteEP, protocol, "DNS Server received a zone UPDATE request for zone: " + zoneInfo.DisplayName);
  1121. async Task<bool> IsZoneNameServerAllowedAsync()
  1122. {
  1123. IPAddress remoteAddress = remoteEP.Address;
  1124. IReadOnlyList<NameServerAddress> secondaryNameServers = await zoneInfo.ApexZone.GetResolvedSecondaryNameServerAddressesAsync();
  1125. foreach (NameServerAddress secondaryNameServer in secondaryNameServers)
  1126. {
  1127. if (secondaryNameServer.IPEndPoint.Address.Equals(remoteAddress))
  1128. return true;
  1129. }
  1130. return false;
  1131. }
  1132. async Task<bool> IsUpdatePermittedAsync()
  1133. {
  1134. bool isUpdateAllowed;
  1135. switch (zoneInfo.Update)
  1136. {
  1137. case AuthZoneUpdate.Allow:
  1138. isUpdateAllowed = true;
  1139. break;
  1140. case AuthZoneUpdate.AllowOnlyZoneNameServers:
  1141. isUpdateAllowed = await IsZoneNameServerAllowedAsync();
  1142. break;
  1143. case AuthZoneUpdate.UseSpecifiedNetworkACL:
  1144. isUpdateAllowed = NetworkAccessControl.IsAddressAllowed(remoteEP.Address, zoneInfo.UpdateNetworkACL);
  1145. break;
  1146. case AuthZoneUpdate.AllowZoneNameServersAndUseSpecifiedNetworkACL:
  1147. isUpdateAllowed = NetworkAccessControl.IsAddressAllowed(remoteEP.Address, zoneInfo.UpdateNetworkACL) || await IsZoneNameServerAllowedAsync();
  1148. break;
  1149. case AuthZoneUpdate.Deny:
  1150. default:
  1151. isUpdateAllowed = false;
  1152. break;
  1153. }
  1154. if (!isUpdateAllowed)
  1155. {
  1156. _log?.Write(remoteEP, protocol, "DNS Server refused a zone UPDATE request since the request IP address is not allowed by the zone: " + zoneInfo.DisplayName);
  1157. return false;
  1158. }
  1159. //check security policies
  1160. if ((zoneInfo.UpdateSecurityPolicies is not null) && (zoneInfo.UpdateSecurityPolicies.Count > 0))
  1161. {
  1162. if ((tsigAuthenticatedKeyName is null) || !zoneInfo.UpdateSecurityPolicies.TryGetValue(tsigAuthenticatedKeyName.ToLowerInvariant(), out IReadOnlyDictionary<string, IReadOnlyList<DnsResourceRecordType>> policyMap))
  1163. {
  1164. _log?.Write(remoteEP, protocol, "DNS Server refused a zone UPDATE request since the request is missing TSIG auth required by the zone: " + zoneInfo.DisplayName);
  1165. return false;
  1166. }
  1167. //check policy
  1168. foreach (DnsResourceRecord uRecord in request.Authority)
  1169. {
  1170. bool isPermitted = false;
  1171. foreach (KeyValuePair<string, IReadOnlyList<DnsResourceRecordType>> policy in policyMap)
  1172. {
  1173. if (
  1174. uRecord.Name.Equals(policy.Key, StringComparison.OrdinalIgnoreCase) ||
  1175. (policy.Key.StartsWith("*.") && uRecord.Name.EndsWith(policy.Key.Substring(1), StringComparison.OrdinalIgnoreCase))
  1176. )
  1177. {
  1178. foreach (DnsResourceRecordType allowedType in policy.Value)
  1179. {
  1180. if ((allowedType == DnsResourceRecordType.ANY) || (allowedType == uRecord.Type))
  1181. {
  1182. isPermitted = true;
  1183. break;
  1184. }
  1185. }
  1186. if (isPermitted)
  1187. break;
  1188. }
  1189. }
  1190. if (!isPermitted)
  1191. {
  1192. _log?.Write(remoteEP, protocol, "DNS Server refused a zone UPDATE request [" + uRecord.Name.ToLowerInvariant() + " " + uRecord.Type.ToString() + " " + uRecord.Class.ToString() + "] due to Dynamic Updates Security Policy for zone: " + zoneInfo.DisplayName);
  1193. return false;
  1194. }
  1195. }
  1196. }
  1197. return true;
  1198. }
  1199. switch (zoneInfo.Type)
  1200. {
  1201. case AuthZoneType.Primary:
  1202. case AuthZoneType.Forwarder:
  1203. //update
  1204. {
  1205. //process prerequisite section
  1206. {
  1207. Dictionary<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>> temp = new Dictionary<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>>();
  1208. foreach (DnsResourceRecord prRecord in request.Answer)
  1209. {
  1210. if (prRecord.TTL != 0)
  1211. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1212. AuthZoneInfo prAuthZoneInfo = _authZoneManager.FindAuthZoneInfo(prRecord.Name);
  1213. if ((prAuthZoneInfo is null) || !prAuthZoneInfo.Name.Equals(zoneInfo.Name, StringComparison.OrdinalIgnoreCase))
  1214. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NotZone, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1215. if (prRecord.Class == DnsClass.ANY)
  1216. {
  1217. if (prRecord.RDATA.RDLENGTH != 0)
  1218. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1219. if (prRecord.Type == DnsResourceRecordType.ANY)
  1220. {
  1221. //check if name is in use
  1222. if (!_authZoneManager.NameExists(zoneInfo.Name, prRecord.Name))
  1223. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NxDomain, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1224. }
  1225. else
  1226. {
  1227. //check if RRSet exists (value independent)
  1228. IReadOnlyList<DnsResourceRecord> rrset = _authZoneManager.GetRecords(zoneInfo.Name, prRecord.Name, prRecord.Type);
  1229. if (rrset.Count == 0)
  1230. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NXRRSet, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1231. }
  1232. }
  1233. else if (prRecord.Class == DnsClass.NONE)
  1234. {
  1235. if (prRecord.RDATA.RDLENGTH != 0)
  1236. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1237. if (prRecord.Type == DnsResourceRecordType.ANY)
  1238. {
  1239. //check if name is not in use
  1240. if (_authZoneManager.NameExists(zoneInfo.Name, prRecord.Name))
  1241. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.YXDomain, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1242. }
  1243. else
  1244. {
  1245. //check if RRSet does not exists
  1246. IReadOnlyList<DnsResourceRecord> rrset = _authZoneManager.GetRecords(zoneInfo.Name, prRecord.Name, prRecord.Type);
  1247. if (rrset.Count > 0)
  1248. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.YXRRSet, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1249. }
  1250. }
  1251. else if (prRecord.Class == request.Question[0].Class)
  1252. {
  1253. //check if RRSet exists (value dependent)
  1254. //add to temp for later comparison
  1255. string recordName = prRecord.Name.ToLowerInvariant();
  1256. if (!temp.TryGetValue(recordName, out Dictionary<DnsResourceRecordType, List<DnsResourceRecord>> rrsetEntry))
  1257. {
  1258. rrsetEntry = new Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>();
  1259. temp.Add(recordName, rrsetEntry);
  1260. }
  1261. if (!rrsetEntry.TryGetValue(prRecord.Type, out List<DnsResourceRecord> rrset))
  1262. {
  1263. rrset = new List<DnsResourceRecord>();
  1264. rrsetEntry.Add(prRecord.Type, rrset);
  1265. }
  1266. rrset.Add(prRecord);
  1267. }
  1268. else
  1269. {
  1270. //FORMERR
  1271. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1272. }
  1273. }
  1274. //compare collected RRSets in temp
  1275. foreach (KeyValuePair<string, Dictionary<DnsResourceRecordType, List<DnsResourceRecord>>> zoneEntry in temp)
  1276. {
  1277. foreach (KeyValuePair<DnsResourceRecordType, List<DnsResourceRecord>> rrsetEntry in zoneEntry.Value)
  1278. {
  1279. IReadOnlyList<DnsResourceRecord> prRRSet = rrsetEntry.Value;
  1280. IReadOnlyList<DnsResourceRecord> rrset = _authZoneManager.GetRecords(zoneInfo.Name, zoneEntry.Key, rrsetEntry.Key);
  1281. //check if RRSet exists (value dependent)
  1282. //compare RRSets
  1283. if (prRRSet.Count != rrset.Count)
  1284. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NXRRSet, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1285. foreach (DnsResourceRecord prRecord in prRRSet)
  1286. {
  1287. bool found = false;
  1288. foreach (DnsResourceRecord record in rrset)
  1289. {
  1290. if (
  1291. prRecord.Name.Equals(record.Name, StringComparison.OrdinalIgnoreCase) &&
  1292. (prRecord.Class == record.Class) &&
  1293. (prRecord.Type == record.Type) &&
  1294. (prRecord.RDATA.RDLENGTH == record.RDATA.RDLENGTH) &&
  1295. prRecord.RDATA.Equals(record.RDATA)
  1296. )
  1297. {
  1298. found = true;
  1299. break;
  1300. }
  1301. }
  1302. if (!found)
  1303. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NXRRSet, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1304. }
  1305. }
  1306. }
  1307. }
  1308. //check for permissions
  1309. if (!await IsUpdatePermittedAsync())
  1310. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1311. //process update section
  1312. {
  1313. //prescan
  1314. foreach (DnsResourceRecord uRecord in request.Authority)
  1315. {
  1316. AuthZoneInfo prAuthZoneInfo = _authZoneManager.FindAuthZoneInfo(uRecord.Name);
  1317. if ((prAuthZoneInfo is null) || !prAuthZoneInfo.Name.Equals(zoneInfo.Name, StringComparison.OrdinalIgnoreCase))
  1318. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NotZone, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1319. if (uRecord.Class == request.Question[0].Class)
  1320. {
  1321. switch (uRecord.Type)
  1322. {
  1323. case DnsResourceRecordType.ANY:
  1324. case DnsResourceRecordType.AXFR:
  1325. case DnsResourceRecordType.MAILA:
  1326. case DnsResourceRecordType.MAILB:
  1327. case DnsResourceRecordType.IXFR:
  1328. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1329. }
  1330. }
  1331. else if (uRecord.Class == DnsClass.ANY)
  1332. {
  1333. if ((uRecord.TTL != 0) || (uRecord.RDATA.RDLENGTH != 0))
  1334. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1335. switch (uRecord.Type)
  1336. {
  1337. case DnsResourceRecordType.AXFR:
  1338. case DnsResourceRecordType.MAILA:
  1339. case DnsResourceRecordType.MAILB:
  1340. case DnsResourceRecordType.IXFR:
  1341. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1342. }
  1343. }
  1344. else if (uRecord.Class == DnsClass.NONE)
  1345. {
  1346. if (uRecord.TTL != 0)
  1347. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1348. switch (uRecord.Type)
  1349. {
  1350. case DnsResourceRecordType.ANY:
  1351. case DnsResourceRecordType.AXFR:
  1352. case DnsResourceRecordType.MAILA:
  1353. case DnsResourceRecordType.MAILB:
  1354. case DnsResourceRecordType.IXFR:
  1355. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1356. }
  1357. }
  1358. else
  1359. {
  1360. //FORMERR
  1361. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1362. }
  1363. }
  1364. //update
  1365. Dictionary<string, Dictionary<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>>> originalRRSets = new Dictionary<string, Dictionary<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>>>();
  1366. void AddToOriginalRRSets(string domain, DnsResourceRecordType type, IReadOnlyList<DnsResourceRecord> existingRRSet)
  1367. {
  1368. if (!originalRRSets.TryGetValue(domain, out Dictionary<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>> originalRRSetEntries))
  1369. {
  1370. originalRRSetEntries = new Dictionary<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>>();
  1371. originalRRSets.Add(domain, originalRRSetEntries);
  1372. }
  1373. originalRRSetEntries.TryAdd(type, existingRRSet);
  1374. }
  1375. try
  1376. {
  1377. foreach (DnsResourceRecord uRecord in request.Authority)
  1378. {
  1379. if (uRecord.Class == request.Question[0].Class)
  1380. {
  1381. //Add to an RRset
  1382. if (uRecord.Type == DnsResourceRecordType.CNAME)
  1383. {
  1384. if (_authZoneManager.NameExists(zoneInfo.Name, uRecord.Name) && (_authZoneManager.GetRecords(zoneInfo.Name, uRecord.Name, DnsResourceRecordType.CNAME).Count == 0))
  1385. continue; //current name exists and has non-CNAME records so cannot add CNAME record
  1386. IReadOnlyList<DnsResourceRecord> existingRRSet = _authZoneManager.GetRecords(zoneInfo.Name, uRecord.Name, uRecord.Type);
  1387. AddToOriginalRRSets(uRecord.Name, uRecord.Type, existingRRSet);
  1388. _authZoneManager.SetRecord(zoneInfo.Name, uRecord);
  1389. }
  1390. else if (uRecord.Type == DnsResourceRecordType.DNAME)
  1391. {
  1392. IReadOnlyList<DnsResourceRecord> existingRRSet = _authZoneManager.GetRecords(zoneInfo.Name, uRecord.Name, uRecord.Type);
  1393. AddToOriginalRRSets(uRecord.Name, uRecord.Type, existingRRSet);
  1394. _authZoneManager.SetRecord(zoneInfo.Name, uRecord);
  1395. }
  1396. else if (uRecord.Type == DnsResourceRecordType.SOA)
  1397. {
  1398. if (!uRecord.Name.Equals(zoneInfo.Name, StringComparison.OrdinalIgnoreCase))
  1399. continue; //can add SOA only to apex
  1400. IReadOnlyList<DnsResourceRecord> existingRRSet = _authZoneManager.GetRecords(zoneInfo.Name, uRecord.Name, uRecord.Type);
  1401. AddToOriginalRRSets(uRecord.Name, uRecord.Type, existingRRSet);
  1402. _authZoneManager.SetRecord(zoneInfo.Name, uRecord);
  1403. }
  1404. else
  1405. {
  1406. if (_authZoneManager.GetRecords(zoneInfo.Name, uRecord.Name, DnsResourceRecordType.CNAME).Count > 0)
  1407. continue; //current name contains CNAME so cannot add non-CNAME record
  1408. IReadOnlyList<DnsResourceRecord> existingRRSet = _authZoneManager.GetRecords(zoneInfo.Name, uRecord.Name, uRecord.Type);
  1409. AddToOriginalRRSets(uRecord.Name, uRecord.Type, existingRRSet);
  1410. if (uRecord.Type == DnsResourceRecordType.NS)
  1411. uRecord.SyncGlueRecords(request.Additional);
  1412. _authZoneManager.AddRecord(zoneInfo.Name, uRecord);
  1413. }
  1414. }
  1415. else if (uRecord.Class == DnsClass.ANY)
  1416. {
  1417. if (uRecord.Type == DnsResourceRecordType.ANY)
  1418. {
  1419. //Delete all RRsets from a name
  1420. IReadOnlyDictionary<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>> existingRRSets = _authZoneManager.GetEntriesFor(zoneInfo.Name, uRecord.Name);
  1421. if (uRecord.Name.Equals(zoneInfo.Name, StringComparison.OrdinalIgnoreCase))
  1422. {
  1423. foreach (KeyValuePair<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>> existingRRSet in existingRRSets)
  1424. {
  1425. switch (existingRRSet.Key)
  1426. {
  1427. case DnsResourceRecordType.SOA:
  1428. case DnsResourceRecordType.NS:
  1429. case DnsResourceRecordType.DNSKEY:
  1430. case DnsResourceRecordType.RRSIG:
  1431. case DnsResourceRecordType.NSEC:
  1432. case DnsResourceRecordType.NSEC3PARAM:
  1433. case DnsResourceRecordType.NSEC3:
  1434. continue; //no apex SOA/NS can be deleted; skip DNSSEC rrsets
  1435. }
  1436. AddToOriginalRRSets(uRecord.Name, existingRRSet.Key, existingRRSet.Value);
  1437. _authZoneManager.DeleteRecords(zoneInfo.Name, uRecord.Name, existingRRSet.Key);
  1438. }
  1439. }
  1440. else
  1441. {
  1442. foreach (KeyValuePair<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>> existingRRSet in existingRRSets)
  1443. {
  1444. switch (existingRRSet.Key)
  1445. {
  1446. case DnsResourceRecordType.DNSKEY:
  1447. case DnsResourceRecordType.RRSIG:
  1448. case DnsResourceRecordType.NSEC:
  1449. case DnsResourceRecordType.NSEC3PARAM:
  1450. case DnsResourceRecordType.NSEC3:
  1451. continue; //skip DNSSEC rrsets
  1452. }
  1453. AddToOriginalRRSets(uRecord.Name, existingRRSet.Key, existingRRSet.Value);
  1454. _authZoneManager.DeleteRecords(zoneInfo.Name, uRecord.Name, existingRRSet.Key);
  1455. }
  1456. }
  1457. }
  1458. else
  1459. {
  1460. //Delete an RRset
  1461. if (uRecord.Name.Equals(zoneInfo.Name, StringComparison.OrdinalIgnoreCase))
  1462. {
  1463. switch (uRecord.Type)
  1464. {
  1465. case DnsResourceRecordType.SOA:
  1466. case DnsResourceRecordType.NS:
  1467. case DnsResourceRecordType.DNSKEY:
  1468. case DnsResourceRecordType.RRSIG:
  1469. case DnsResourceRecordType.NSEC:
  1470. case DnsResourceRecordType.NSEC3PARAM:
  1471. case DnsResourceRecordType.NSEC3:
  1472. continue; //no apex SOA/NS can be deleted; skip DNSSEC rrsets
  1473. }
  1474. }
  1475. IReadOnlyList<DnsResourceRecord> existingRRSet = _authZoneManager.GetRecords(zoneInfo.Name, uRecord.Name, uRecord.Type);
  1476. AddToOriginalRRSets(uRecord.Name, uRecord.Type, existingRRSet);
  1477. _authZoneManager.DeleteRecords(zoneInfo.Name, uRecord.Name, uRecord.Type);
  1478. }
  1479. }
  1480. else if (uRecord.Class == DnsClass.NONE)
  1481. {
  1482. //Delete an RR from an RRset
  1483. switch (uRecord.Type)
  1484. {
  1485. case DnsResourceRecordType.SOA:
  1486. case DnsResourceRecordType.DNSKEY:
  1487. case DnsResourceRecordType.RRSIG:
  1488. case DnsResourceRecordType.NSEC:
  1489. case DnsResourceRecordType.NSEC3PARAM:
  1490. case DnsResourceRecordType.NSEC3:
  1491. continue; //no SOA can be deleted; skip DNSSEC rrsets
  1492. }
  1493. IReadOnlyList<DnsResourceRecord> existingRRSet = _authZoneManager.GetRecords(zoneInfo.Name, uRecord.Name, uRecord.Type);
  1494. if ((uRecord.Type == DnsResourceRecordType.NS) && (existingRRSet.Count == 1) && uRecord.Name.Equals(zoneInfo.Name, StringComparison.OrdinalIgnoreCase))
  1495. continue; //no apex NS can be deleted if only 1 NS exists
  1496. AddToOriginalRRSets(uRecord.Name, uRecord.Type, existingRRSet);
  1497. _authZoneManager.DeleteRecord(zoneInfo.Name, uRecord.Name, uRecord.Type, uRecord.RDATA);
  1498. }
  1499. }
  1500. }
  1501. catch
  1502. {
  1503. //revert
  1504. foreach (KeyValuePair<string, Dictionary<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>>> originalRRSetEntries in originalRRSets)
  1505. {
  1506. foreach (KeyValuePair<DnsResourceRecordType, IReadOnlyList<DnsResourceRecord>> originalRRSet in originalRRSetEntries.Value)
  1507. {
  1508. if (originalRRSet.Value.Count == 0)
  1509. _authZoneManager.DeleteRecords(zoneInfo.Name, originalRRSetEntries.Key, originalRRSet.Key);
  1510. else
  1511. _authZoneManager.SetRecords(zoneInfo.Name, originalRRSet.Value);
  1512. }
  1513. }
  1514. throw;
  1515. }
  1516. }
  1517. _authZoneManager.SaveZoneFile(zoneInfo.Name);
  1518. _log?.Write(remoteEP, protocol, "DNS Server successfully processed a zone UPDATE request for zone: " + zoneInfo.DisplayName);
  1519. //NOERROR
  1520. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NoError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1521. }
  1522. case AuthZoneType.Secondary:
  1523. case AuthZoneType.SecondaryForwarder:
  1524. //forward
  1525. {
  1526. //check for permissions
  1527. if (!await IsUpdatePermittedAsync())
  1528. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1529. //forward to primary
  1530. IReadOnlyList<NameServerAddress> primaryNameServerAddresses;
  1531. DnsTransportProtocol primaryZoneTransferProtocol;
  1532. SecondaryCatalogZone secondaryCatalogZone = zoneInfo.ApexZone.SecondaryCatalogZone;
  1533. if ((secondaryCatalogZone is not null) && !zoneInfo.OverrideCatalogPrimaryNameServers)
  1534. {
  1535. primaryNameServerAddresses = await zoneInfo.ApexZone.GetResolvedNameServerAddressesAsync(secondaryCatalogZone.PrimaryNameServerAddresses);
  1536. primaryZoneTransferProtocol = secondaryCatalogZone.PrimaryZoneTransferProtocol;
  1537. }
  1538. else
  1539. {
  1540. primaryNameServerAddresses = await zoneInfo.ApexZone.GetResolvedPrimaryNameServerAddressesAsync();
  1541. primaryZoneTransferProtocol = zoneInfo.PrimaryZoneTransferProtocol;
  1542. }
  1543. switch (primaryZoneTransferProtocol)
  1544. {
  1545. case DnsTransportProtocol.Tls:
  1546. case DnsTransportProtocol.Quic:
  1547. {
  1548. //change name server protocol to TLS/QUIC
  1549. List<NameServerAddress> updatedNameServers = new List<NameServerAddress>(primaryNameServerAddresses.Count);
  1550. foreach (NameServerAddress primaryNameServer in primaryNameServerAddresses)
  1551. {
  1552. if (primaryNameServer.Protocol == primaryZoneTransferProtocol)
  1553. updatedNameServers.Add(primaryNameServer);
  1554. else
  1555. updatedNameServers.Add(primaryNameServer.ChangeProtocol(primaryZoneTransferProtocol));
  1556. }
  1557. primaryNameServerAddresses = updatedNameServers;
  1558. }
  1559. break;
  1560. default:
  1561. if (protocol == DnsTransportProtocol.Tcp)
  1562. {
  1563. //change name server protocol to TCP
  1564. List<NameServerAddress> updatedNameServers = new List<NameServerAddress>(primaryNameServerAddresses.Count);
  1565. foreach (NameServerAddress primaryNameServer in primaryNameServerAddresses)
  1566. {
  1567. if (primaryNameServer.Protocol == DnsTransportProtocol.Tcp)
  1568. updatedNameServers.Add(primaryNameServer);
  1569. else
  1570. updatedNameServers.Add(primaryNameServer.ChangeProtocol(DnsTransportProtocol.Tcp));
  1571. }
  1572. primaryNameServerAddresses = updatedNameServers;
  1573. }
  1574. break;
  1575. }
  1576. TsigKey key = null;
  1577. if (!string.IsNullOrEmpty(tsigAuthenticatedKeyName) && ((_tsigKeys is null) || !_tsigKeys.TryGetValue(tsigAuthenticatedKeyName, out key)))
  1578. throw new DnsServerException("DNS Server does not have TSIG key '" + tsigAuthenticatedKeyName + "' configured to authenticate dynamic updates for " + zoneInfo.TypeName + " zone: " + zoneInfo.DisplayName);
  1579. DnsClient dnsClient = new DnsClient(primaryNameServerAddresses);
  1580. dnsClient.Proxy = _proxy;
  1581. dnsClient.PreferIPv6 = _preferIPv6;
  1582. dnsClient.Retries = _forwarderRetries;
  1583. dnsClient.Timeout = _forwarderTimeout;
  1584. dnsClient.Concurrency = 1;
  1585. DnsDatagram newRequest = request.Clone();
  1586. newRequest.SetRandomIdentifier();
  1587. DnsDatagram newResponse;
  1588. if (key is null)
  1589. newResponse = await dnsClient.RawResolveAsync(newRequest);
  1590. else
  1591. newResponse = await dnsClient.TsigResolveAsync(newRequest, key);
  1592. newResponse.SetIdentifier(request.Identifier);
  1593. return newResponse;
  1594. }
  1595. default:
  1596. return new DnsDatagram(request.Identifier, true, DnsOpcode.Update, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NotAuth, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1597. }
  1598. }
  1599. private async Task<DnsDatagram> ProcessZoneTransferQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, string tsigAuthenticatedKeyName)
  1600. {
  1601. AuthZoneInfo zoneInfo = _authZoneManager.GetAuthZoneInfo(request.Question[0].Name);
  1602. if ((zoneInfo is null) || !zoneInfo.ApexZone.IsActive)
  1603. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1604. switch (zoneInfo.Type)
  1605. {
  1606. case AuthZoneType.Primary:
  1607. case AuthZoneType.Secondary:
  1608. case AuthZoneType.Forwarder:
  1609. case AuthZoneType.Catalog:
  1610. break;
  1611. default:
  1612. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1613. }
  1614. async Task<bool> IsZoneNameServerAllowedAsync(ApexZone apexZone)
  1615. {
  1616. IPAddress remoteAddress = remoteEP.Address;
  1617. IReadOnlyList<NameServerAddress> secondaryNameServers = await apexZone.GetResolvedSecondaryNameServerAddressesAsync();
  1618. foreach (NameServerAddress secondaryNameServer in secondaryNameServers)
  1619. {
  1620. if (secondaryNameServer.IPEndPoint.Address.Equals(remoteAddress))
  1621. return true;
  1622. }
  1623. return false;
  1624. }
  1625. async Task<bool> IsZoneTransferAllowed(ApexZone apexZone)
  1626. {
  1627. switch (apexZone.ZoneTransfer)
  1628. {
  1629. case AuthZoneTransfer.Allow:
  1630. return true;
  1631. case AuthZoneTransfer.AllowOnlyZoneNameServers:
  1632. return await IsZoneNameServerAllowedAsync(apexZone);
  1633. case AuthZoneTransfer.UseSpecifiedNetworkACL:
  1634. return NetworkAccessControl.IsAddressAllowed(remoteEP.Address, apexZone.ZoneTransferNetworkACL);
  1635. case AuthZoneTransfer.AllowZoneNameServersAndUseSpecifiedNetworkACL:
  1636. return NetworkAccessControl.IsAddressAllowed(remoteEP.Address, apexZone.ZoneTransferNetworkACL) || await IsZoneNameServerAllowedAsync(apexZone);
  1637. case AuthZoneTransfer.Deny:
  1638. default:
  1639. return false;
  1640. }
  1641. }
  1642. bool IsTsigAuthenticated(ApexZone apexZone)
  1643. {
  1644. if ((apexZone.ZoneTransferTsigKeyNames is null) || (apexZone.ZoneTransferTsigKeyNames.Count < 1))
  1645. return true; //no auth needed
  1646. if ((tsigAuthenticatedKeyName is not null) && apexZone.ZoneTransferTsigKeyNames.ContainsKey(tsigAuthenticatedKeyName.ToLowerInvariant()))
  1647. return true; //key matches
  1648. return false;
  1649. }
  1650. bool isInZoneTransferAllowedList = false;
  1651. if (_zoneTransferAllowedNetworks is not null)
  1652. {
  1653. IPAddress remoteAddress = remoteEP.Address;
  1654. foreach (NetworkAddress networkAddress in _zoneTransferAllowedNetworks)
  1655. {
  1656. if (networkAddress.Contains(remoteAddress))
  1657. {
  1658. isInZoneTransferAllowedList = true;
  1659. break;
  1660. }
  1661. }
  1662. }
  1663. if (!isInZoneTransferAllowedList)
  1664. {
  1665. ApexZone apexZone = zoneInfo.ApexZone;
  1666. CatalogZone catalogZone = apexZone.CatalogZone;
  1667. if (catalogZone is not null)
  1668. {
  1669. if (!apexZone.OverrideCatalogZoneTransfer)
  1670. apexZone = catalogZone; //use catalog zone transfer options
  1671. }
  1672. else
  1673. {
  1674. SecondaryCatalogZone secondaryCatalogZone = apexZone.SecondaryCatalogZone;
  1675. if (secondaryCatalogZone is not null)
  1676. {
  1677. if (!apexZone.OverrideCatalogZoneTransfer)
  1678. apexZone = secondaryCatalogZone; //use secondary zone transfer options
  1679. }
  1680. }
  1681. if (!await IsZoneTransferAllowed(apexZone))
  1682. {
  1683. _log?.Write(remoteEP, protocol, "DNS Server refused a zone transfer request since the request IP address is not allowed by the zone: " + zoneInfo.DisplayName);
  1684. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1685. }
  1686. if (!IsTsigAuthenticated(apexZone))
  1687. {
  1688. _log?.Write(remoteEP, protocol, "DNS Server refused a zone transfer request since the request is missing TSIG auth required by the zone: " + zoneInfo.DisplayName);
  1689. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.Refused, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1690. }
  1691. }
  1692. _log?.Write(remoteEP, protocol, "DNS Server received zone transfer request for zone: " + zoneInfo.DisplayName);
  1693. IReadOnlyList<DnsResourceRecord> xfrRecords;
  1694. if (request.Question[0].Type == DnsResourceRecordType.IXFR)
  1695. {
  1696. if ((request.Authority.Count == 1) && (request.Authority[0].Type == DnsResourceRecordType.SOA))
  1697. xfrRecords = _authZoneManager.QueryIncrementalZoneTransferRecords(request.Question[0].Name, request.Authority[0]);
  1698. else
  1699. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  1700. }
  1701. else
  1702. {
  1703. xfrRecords = _authZoneManager.QueryZoneTransferRecords(request.Question[0].Name);
  1704. }
  1705. DnsDatagram xfrResponse = new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, true, false, request.RecursionDesired, false, false, false, DnsResponseCode.NoError, request.Question, xfrRecords) { Tag = DnsServerResponseType.Authoritative };
  1706. xfrResponse = xfrResponse.Split();
  1707. //update notify failed list
  1708. NameServerAddress allowedZoneNameServer = null;
  1709. switch (zoneInfo.Notify)
  1710. {
  1711. case AuthZoneNotify.ZoneNameServers:
  1712. case AuthZoneNotify.BothZoneAndSpecifiedNameServers:
  1713. IPAddress remoteAddress = remoteEP.Address;
  1714. IReadOnlyList<NameServerAddress> secondaryNameServers = await zoneInfo.ApexZone.GetResolvedSecondaryNameServerAddressesAsync();
  1715. foreach (NameServerAddress secondaryNameServer in secondaryNameServers)
  1716. {
  1717. if (secondaryNameServer.IPEndPoint.Address.Equals(remoteAddress))
  1718. {
  1719. allowedZoneNameServer = secondaryNameServer;
  1720. break;
  1721. }
  1722. }
  1723. break;
  1724. }
  1725. zoneInfo.ApexZone.RemoveFromNotifyFailedList(allowedZoneNameServer, remoteEP.Address);
  1726. return xfrResponse;
  1727. }
  1728. private async Task<DnsDatagram> ProcessAuthoritativeQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, bool skipDnsAppAuthoritativeRequestHandlers)
  1729. {
  1730. DnsDatagram response = await AuthoritativeQueryAsync(request, remoteEP, protocol, isRecursionAllowed, skipDnsAppAuthoritativeRequestHandlers);
  1731. if (response is null)
  1732. return null;
  1733. bool reprocessResponse; //to allow resolving CNAME/ANAME in response
  1734. do
  1735. {
  1736. reprocessResponse = false;
  1737. if (response.RCODE == DnsResponseCode.NoError)
  1738. {
  1739. if (response.Answer.Count > 0)
  1740. {
  1741. DnsResourceRecordType questionType = request.Question[0].Type;
  1742. DnsResourceRecord lastRR = response.GetLastAnswerRecord();
  1743. if ((lastRR.Type != questionType) && (questionType != DnsResourceRecordType.ANY))
  1744. {
  1745. switch (lastRR.Type)
  1746. {
  1747. case DnsResourceRecordType.CNAME:
  1748. return await ProcessCNAMEAsync(request, response, remoteEP, protocol, isRecursionAllowed, false, skipDnsAppAuthoritativeRequestHandlers);
  1749. case DnsResourceRecordType.ANAME:
  1750. case DnsResourceRecordType.ALIAS:
  1751. return await ProcessANAMEAsync(request, response, remoteEP, protocol, isRecursionAllowed, skipDnsAppAuthoritativeRequestHandlers);
  1752. }
  1753. }
  1754. }
  1755. else if (response.Authority.Count > 0)
  1756. {
  1757. DnsResourceRecord firstAuthority = response.FindFirstAuthorityRecord();
  1758. switch (firstAuthority.Type)
  1759. {
  1760. case DnsResourceRecordType.NS:
  1761. if (request.RecursionDesired && isRecursionAllowed)
  1762. {
  1763. //do forced recursive resolution (with blocking support) using empty conditional forwarders; name servers will be provided via ResolverDnsCache
  1764. return await ProcessRecursiveQueryAsync(request, remoteEP, protocol, [], _dnssecValidation, false, skipDnsAppAuthoritativeRequestHandlers);
  1765. }
  1766. break;
  1767. case DnsResourceRecordType.FWD:
  1768. //do conditional forwarding (with blocking support)
  1769. return await ProcessRecursiveQueryAsync(request, remoteEP, protocol, response.Authority, _dnssecValidation, false, skipDnsAppAuthoritativeRequestHandlers);
  1770. case DnsResourceRecordType.APP:
  1771. response = await ProcessAPPAsync(request, response, remoteEP, protocol, isRecursionAllowed, skipDnsAppAuthoritativeRequestHandlers);
  1772. reprocessResponse = true;
  1773. break;
  1774. }
  1775. }
  1776. }
  1777. }
  1778. while (reprocessResponse);
  1779. return response;
  1780. }
  1781. private async Task<DnsDatagram> AuthoritativeQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, bool skipDnsAppAuthoritativeRequestHandlers)
  1782. {
  1783. DnsDatagram response = await TechnitiumLibrary.TaskExtensions.TimeoutAsync(delegate (CancellationToken cancellationToken1)
  1784. {
  1785. return _authZoneManager.QueryAsync(request, remoteEP.Address, isRecursionAllowed, cancellationToken1);
  1786. }, _clientTimeout);
  1787. if (response is not null)
  1788. {
  1789. response.Tag = DnsServerResponseType.Authoritative;
  1790. return response;
  1791. }
  1792. if (!skipDnsAppAuthoritativeRequestHandlers)
  1793. {
  1794. foreach (IDnsAuthoritativeRequestHandler requestHandler in _dnsApplicationManager.DnsAuthoritativeRequestHandlers)
  1795. {
  1796. try
  1797. {
  1798. DnsDatagram appResponse = await requestHandler.ProcessRequestAsync(request, remoteEP, protocol, isRecursionAllowed);
  1799. if (appResponse is not null)
  1800. {
  1801. if (appResponse.Tag is null)
  1802. appResponse.Tag = DnsServerResponseType.Authoritative;
  1803. return appResponse;
  1804. }
  1805. }
  1806. catch (Exception ex)
  1807. {
  1808. _log?.Write(remoteEP, protocol, ex);
  1809. }
  1810. }
  1811. }
  1812. return null;
  1813. }
  1814. private async Task<DnsDatagram> ProcessAPPAsync(DnsDatagram request, DnsDatagram response, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, bool skipDnsAppAuthoritativeRequestHandlers)
  1815. {
  1816. DnsResourceRecord appResourceRecord = response.Authority[0];
  1817. DnsApplicationRecordData appRecord = appResourceRecord.RDATA as DnsApplicationRecordData;
  1818. if (_dnsApplicationManager.Applications.TryGetValue(appRecord.AppName, out DnsApplication application))
  1819. {
  1820. if (application.DnsAppRecordRequestHandlers.TryGetValue(appRecord.ClassPath, out IDnsAppRecordRequestHandler appRecordRequestHandler))
  1821. {
  1822. AuthZoneInfo zoneInfo = _authZoneManager.FindAuthZoneInfo(appResourceRecord.Name);
  1823. DnsDatagram appResponse = await appRecordRequestHandler.ProcessRequestAsync(request, remoteEP, protocol, isRecursionAllowed, zoneInfo.Name, appResourceRecord.Name, appResourceRecord.TTL, appRecord.Data);
  1824. if (appResponse is null)
  1825. {
  1826. DnsResponseCode rcode;
  1827. IReadOnlyList<DnsResourceRecord> authority = null;
  1828. if (zoneInfo.Type == AuthZoneType.Forwarder)
  1829. {
  1830. //process FWD record if exists
  1831. if (!zoneInfo.Name.Equals(appResourceRecord.Name, StringComparison.OrdinalIgnoreCase))
  1832. {
  1833. AuthZone authZone = _authZoneManager.GetAuthZone(zoneInfo.Name, appResourceRecord.Name);
  1834. if (authZone is not null)
  1835. authority = authZone.QueryRecords(DnsResourceRecordType.FWD, false);
  1836. }
  1837. if ((authority is null) || (authority.Count == 0))
  1838. authority = zoneInfo.ApexZone.QueryRecords(DnsResourceRecordType.FWD, false);
  1839. if (authority.Count > 0)
  1840. return await RecursiveResolveAsync(request, remoteEP, authority, _dnssecValidation, false, false, skipDnsAppAuthoritativeRequestHandlers);
  1841. rcode = DnsResponseCode.NoError;
  1842. }
  1843. else
  1844. {
  1845. //return NODATA/NXDOMAIN response
  1846. if ((request.Question[0].Name.Length == appResourceRecord.Name.Length) || appResourceRecord.Name.StartsWith('*'))
  1847. rcode = DnsResponseCode.NoError;
  1848. else
  1849. rcode = DnsResponseCode.NxDomain;
  1850. authority = zoneInfo.ApexZone.GetRecords(DnsResourceRecordType.SOA);
  1851. }
  1852. return new DnsDatagram(request.Identifier, true, request.OPCODE, false, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, rcode, request.Question, null, authority) { Tag = DnsServerResponseType.Authoritative };
  1853. }
  1854. else
  1855. {
  1856. if (appResponse.AuthoritativeAnswer)
  1857. appResponse.Tag = DnsServerResponseType.Authoritative;
  1858. return appResponse; //return app response
  1859. }
  1860. }
  1861. else
  1862. {
  1863. _log?.Write(remoteEP, protocol, "DNS request handler '" + appRecord.ClassPath + "' was not found in the application '" + appRecord.AppName + "': " + appResourceRecord.Name);
  1864. }
  1865. }
  1866. else
  1867. {
  1868. _log?.Write(remoteEP, protocol, "DNS application '" + appRecord.AppName + "' was not found: " + appResourceRecord.Name);
  1869. }
  1870. //return server failure response with SOA
  1871. {
  1872. AuthZoneInfo zoneInfo = _authZoneManager.FindAuthZoneInfo(request.Question[0].Name);
  1873. IReadOnlyList<DnsResourceRecord> authority = zoneInfo.ApexZone.GetRecords(DnsResourceRecordType.SOA);
  1874. return new DnsDatagram(request.Identifier, true, request.OPCODE, false, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, DnsResponseCode.ServerFailure, request.Question, null, authority) { Tag = DnsServerResponseType.Authoritative };
  1875. }
  1876. }
  1877. private async Task<DnsDatagram> ProcessCNAMEAsync(DnsDatagram request, DnsDatagram response, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, bool cacheRefreshOperation, bool skipDnsAppAuthoritativeRequestHandlers)
  1878. {
  1879. List<DnsResourceRecord> newAnswer = new List<DnsResourceRecord>(response.Answer.Count + 4);
  1880. newAnswer.AddRange(response.Answer);
  1881. //copying NSEC/NSEC3 for for wildcard answers
  1882. List<DnsResourceRecord> newAuthority = new List<DnsResourceRecord>(2);
  1883. foreach (DnsResourceRecord record in response.Authority)
  1884. {
  1885. switch (record.Type)
  1886. {
  1887. case DnsResourceRecordType.NSEC:
  1888. case DnsResourceRecordType.NSEC3:
  1889. newAuthority.Add(record);
  1890. break;
  1891. case DnsResourceRecordType.RRSIG:
  1892. switch ((record.RDATA as DnsRRSIGRecordData).TypeCovered)
  1893. {
  1894. case DnsResourceRecordType.NSEC:
  1895. case DnsResourceRecordType.NSEC3:
  1896. newAuthority.Add(record);
  1897. break;
  1898. }
  1899. break;
  1900. }
  1901. }
  1902. DnsDatagram lastResponse = response;
  1903. bool isAuthoritativeAnswer = response.AuthoritativeAnswer;
  1904. DnsResourceRecord lastRR = response.GetLastAnswerRecord();
  1905. EDnsOption[] eDnsClientSubnetOption = null;
  1906. DnsDatagram newResponse = null;
  1907. if (_eDnsClientSubnet)
  1908. {
  1909. EDnsClientSubnetOptionData requestECS = request.GetEDnsClientSubnetOption();
  1910. if (requestECS is not null)
  1911. eDnsClientSubnetOption = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EDNS_CLIENT_SUBNET, requestECS) };
  1912. }
  1913. int queryCount = 0;
  1914. do
  1915. {
  1916. string cnameDomain = (lastRR.RDATA as DnsCNAMERecordData).Domain;
  1917. if (lastRR.Name.Equals(cnameDomain, StringComparison.OrdinalIgnoreCase))
  1918. break; //loop detected
  1919. DnsDatagram newRequest = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, request.CheckingDisabled, 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);
  1920. //query authoritative zone first
  1921. newResponse = await AuthoritativeQueryAsync(newRequest, remoteEP, protocol, isRecursionAllowed, skipDnsAppAuthoritativeRequestHandlers);
  1922. if (newResponse is null)
  1923. {
  1924. //not found in auth zone
  1925. if (newRequest.RecursionDesired && isRecursionAllowed)
  1926. {
  1927. //do recursion
  1928. newResponse = await RecursiveResolveAsync(newRequest, remoteEP, null, _dnssecValidation, false, cacheRefreshOperation, skipDnsAppAuthoritativeRequestHandlers);
  1929. isAuthoritativeAnswer = false;
  1930. }
  1931. else
  1932. {
  1933. //break since no recursion allowed/desired
  1934. break;
  1935. }
  1936. }
  1937. else if ((newResponse.Answer.Count > 0) && (newResponse.GetLastAnswerRecord() is DnsResourceRecord lastAnswer) && ((lastAnswer.Type == DnsResourceRecordType.ANAME) || (lastAnswer.Type == DnsResourceRecordType.ALIAS)))
  1938. {
  1939. newResponse = await ProcessANAMEAsync(request, newResponse, remoteEP, protocol, isRecursionAllowed, skipDnsAppAuthoritativeRequestHandlers);
  1940. }
  1941. else if ((newResponse.Answer.Count == 0) && (newResponse.Authority.Count > 0))
  1942. {
  1943. //found delegated/forwarded zone
  1944. DnsResourceRecord firstAuthority = newResponse.FindFirstAuthorityRecord();
  1945. switch (firstAuthority.Type)
  1946. {
  1947. case DnsResourceRecordType.NS:
  1948. if (newRequest.RecursionDesired && isRecursionAllowed)
  1949. {
  1950. //do forced recursive resolution using empty conditional forwarders; name servers will be provided via ResolveDnsCache
  1951. newResponse = await RecursiveResolveAsync(newRequest, remoteEP, [], _dnssecValidation, false, false, skipDnsAppAuthoritativeRequestHandlers);
  1952. isAuthoritativeAnswer = false;
  1953. }
  1954. break;
  1955. case DnsResourceRecordType.FWD:
  1956. //do conditional forwarding
  1957. newResponse = await RecursiveResolveAsync(newRequest, remoteEP, newResponse.Authority, _dnssecValidation, false, false, skipDnsAppAuthoritativeRequestHandlers);
  1958. isAuthoritativeAnswer = false;
  1959. break;
  1960. case DnsResourceRecordType.APP:
  1961. newResponse = await ProcessAPPAsync(newRequest, newResponse, remoteEP, protocol, isRecursionAllowed, skipDnsAppAuthoritativeRequestHandlers);
  1962. break;
  1963. }
  1964. }
  1965. //check last response
  1966. if (newResponse.Answer.Count == 0)
  1967. break; //cannot proceed to resolve further
  1968. lastRR = newResponse.GetLastAnswerRecord();
  1969. if (lastRR.Type != DnsResourceRecordType.CNAME)
  1970. {
  1971. newAnswer.AddRange(newResponse.Answer);
  1972. break; //cname was resolved
  1973. }
  1974. bool foundRepeat = false;
  1975. foreach (DnsResourceRecord newResponseAnswerRecord in newResponse.Answer)
  1976. {
  1977. if ((newResponseAnswerRecord.Type == DnsResourceRecordType.CNAME) || (newResponseAnswerRecord.Type == DnsResourceRecordType.DNAME))
  1978. {
  1979. foreach (DnsResourceRecord answerRecord in newAnswer)
  1980. {
  1981. if (newResponseAnswerRecord.Equals(answerRecord))
  1982. {
  1983. foundRepeat = true;
  1984. break;
  1985. }
  1986. }
  1987. if (foundRepeat)
  1988. break;
  1989. }
  1990. newAnswer.Add(newResponseAnswerRecord);
  1991. }
  1992. if (foundRepeat)
  1993. break; //loop detected
  1994. lastResponse = newResponse;
  1995. }
  1996. while (++queryCount < MAX_CNAME_HOPS);
  1997. DnsResponseCode rcode;
  1998. IReadOnlyList<DnsResourceRecord> authority;
  1999. IReadOnlyList<DnsResourceRecord> additional;
  2000. if (newResponse is null)
  2001. {
  2002. //no recursion available
  2003. rcode = DnsResponseCode.NoError;
  2004. if (newAuthority.Count == 0)
  2005. {
  2006. authority = lastResponse.Authority;
  2007. }
  2008. else
  2009. {
  2010. newAuthority.AddRange(lastResponse.Authority);
  2011. authority = newAuthority;
  2012. }
  2013. additional = lastResponse.Additional;
  2014. }
  2015. else
  2016. {
  2017. rcode = newResponse.RCODE;
  2018. if (newAuthority.Count == 0)
  2019. {
  2020. authority = newResponse.Authority;
  2021. }
  2022. else
  2023. {
  2024. newAuthority.AddRange(newResponse.Authority);
  2025. authority = newAuthority;
  2026. }
  2027. additional = newResponse.Additional;
  2028. }
  2029. 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 };
  2030. }
  2031. private async Task<DnsDatagram> ProcessANAMEAsync(DnsDatagram request, DnsDatagram response, IPEndPoint remoteEP, DnsTransportProtocol protocol, bool isRecursionAllowed, bool skipDnsAppAuthoritativeRequestHandlers)
  2032. {
  2033. EDnsOption[] eDnsClientSubnetOption = null;
  2034. if (_eDnsClientSubnet)
  2035. {
  2036. EDnsClientSubnetOptionData requestECS = request.GetEDnsClientSubnetOption();
  2037. if (requestECS is not null)
  2038. eDnsClientSubnetOption = new EDnsOption[] { new EDnsOption(EDnsOptionCode.EDNS_CLIENT_SUBNET, requestECS) };
  2039. }
  2040. Queue<Task<IReadOnlyList<DnsResourceRecord>>> resolveQueue = new Queue<Task<IReadOnlyList<DnsResourceRecord>>>();
  2041. async Task<IReadOnlyList<DnsResourceRecord>> ResolveANAMEAsync(DnsResourceRecord anameRR, int queryCount = 0)
  2042. {
  2043. string lastDomain = (anameRR.RDATA as DnsANAMERecordData).Domain;
  2044. if (anameRR.Name.Equals(lastDomain, StringComparison.OrdinalIgnoreCase))
  2045. return null; //loop detected
  2046. do
  2047. {
  2048. DnsDatagram newRequest = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, request.CheckingDisabled, 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);
  2049. //query authoritative zone first
  2050. DnsDatagram newResponse = await AuthoritativeQueryAsync(newRequest, remoteEP, protocol, isRecursionAllowed, skipDnsAppAuthoritativeRequestHandlers);
  2051. if (newResponse is null)
  2052. {
  2053. //not found in auth zone; do recursion
  2054. newResponse = await RecursiveResolveAsync(newRequest, remoteEP, null, _dnssecValidation, false, false, skipDnsAppAuthoritativeRequestHandlers);
  2055. }
  2056. else if ((newResponse.Answer.Count == 0) && (newResponse.Authority.Count > 0))
  2057. {
  2058. //found delegated/forwarded zone
  2059. DnsResourceRecord firstAuthority = newResponse.FindFirstAuthorityRecord();
  2060. switch (firstAuthority.Type)
  2061. {
  2062. case DnsResourceRecordType.NS:
  2063. //do forced recursive resolution using empty conditional forwarders; name servers will be provided via ResolverDnsCache
  2064. newResponse = await RecursiveResolveAsync(newRequest, remoteEP, [], _dnssecValidation, false, false, skipDnsAppAuthoritativeRequestHandlers);
  2065. break;
  2066. case DnsResourceRecordType.FWD:
  2067. //do conditional forwarding
  2068. newResponse = await RecursiveResolveAsync(newRequest, remoteEP, newResponse.Authority, _dnssecValidation, false, false, skipDnsAppAuthoritativeRequestHandlers);
  2069. break;
  2070. case DnsResourceRecordType.APP:
  2071. newResponse = await ProcessAPPAsync(newRequest, newResponse, remoteEP, protocol, isRecursionAllowed, skipDnsAppAuthoritativeRequestHandlers);
  2072. break;
  2073. }
  2074. }
  2075. //check new response
  2076. if (newResponse.RCODE != DnsResponseCode.NoError)
  2077. return null; //cannot proceed to resolve further
  2078. if (newResponse.Answer.Count == 0)
  2079. return Array.Empty<DnsResourceRecord>(); //NO DATA
  2080. DnsResourceRecordType questionType = request.Question[0].Type;
  2081. DnsResourceRecord lastRR = newResponse.GetLastAnswerRecord();
  2082. if (lastRR.Type == questionType)
  2083. {
  2084. //found final answer
  2085. List<DnsResourceRecord> answers = new List<DnsResourceRecord>();
  2086. foreach (DnsResourceRecord answer in newResponse.Answer)
  2087. {
  2088. if (answer.Type != questionType)
  2089. continue;
  2090. if (anameRR.TTL < answer.TTL)
  2091. answers.Add(new DnsResourceRecord(anameRR.Name, answer.Type, answer.Class, anameRR.TTL, answer.RDATA));
  2092. else
  2093. answers.Add(new DnsResourceRecord(anameRR.Name, answer.Type, answer.Class, answer.TTL, answer.RDATA));
  2094. }
  2095. return answers;
  2096. }
  2097. switch (lastRR.Type)
  2098. {
  2099. case DnsResourceRecordType.ANAME:
  2100. case DnsResourceRecordType.ALIAS:
  2101. if (newResponse.Answer.Count == 1)
  2102. {
  2103. lastDomain = (lastRR.RDATA as DnsANAMERecordData).Domain;
  2104. }
  2105. else
  2106. {
  2107. //resolve multiple ANAME records async
  2108. queryCount++; //increment since one query was done already
  2109. foreach (DnsResourceRecord newAnswer in newResponse.Answer)
  2110. resolveQueue.Enqueue(ResolveANAMEAsync(newAnswer, queryCount));
  2111. return Array.Empty<DnsResourceRecord>();
  2112. }
  2113. break;
  2114. case DnsResourceRecordType.CNAME:
  2115. lastDomain = (lastRR.RDATA as DnsCNAMERecordData).Domain;
  2116. break;
  2117. default:
  2118. //aname/cname was resolved, but no answer found
  2119. return Array.Empty<DnsResourceRecord>();
  2120. }
  2121. }
  2122. while (++queryCount < MAX_CNAME_HOPS);
  2123. //max hops limit crossed
  2124. return null;
  2125. }
  2126. List<DnsResourceRecord> responseAnswer = new List<DnsResourceRecord>();
  2127. foreach (DnsResourceRecord answer in response.Answer)
  2128. {
  2129. switch (answer.Type)
  2130. {
  2131. case DnsResourceRecordType.ANAME:
  2132. case DnsResourceRecordType.ALIAS:
  2133. resolveQueue.Enqueue(ResolveANAMEAsync(answer));
  2134. break;
  2135. default:
  2136. if (resolveQueue.Count == 0)
  2137. responseAnswer.Add(answer);
  2138. break;
  2139. }
  2140. }
  2141. bool foundErrors = false;
  2142. while (resolveQueue.Count > 0)
  2143. {
  2144. IReadOnlyList<DnsResourceRecord> records = await resolveQueue.Dequeue();
  2145. if (records is null)
  2146. foundErrors = true;
  2147. else if (records.Count > 0)
  2148. responseAnswer.AddRange(records);
  2149. }
  2150. DnsResponseCode rcode = DnsResponseCode.NoError;
  2151. IReadOnlyList<DnsResourceRecord> authority = null;
  2152. if (responseAnswer.Count == 0)
  2153. {
  2154. if (foundErrors)
  2155. {
  2156. rcode = DnsResponseCode.ServerFailure;
  2157. }
  2158. else
  2159. {
  2160. authority = response.Authority;
  2161. //update last used on
  2162. DateTime utcNow = DateTime.UtcNow;
  2163. foreach (DnsResourceRecord record in authority)
  2164. record.GetAuthGenericRecordInfo().LastUsedOn = utcNow;
  2165. }
  2166. }
  2167. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, true, false, request.RecursionDesired, isRecursionAllowed, false, request.CheckingDisabled, rcode, request.Question, responseAnswer, authority, null) { Tag = response.Tag };
  2168. }
  2169. private DnsDatagram ProcessBlocked(DnsDatagram request)
  2170. {
  2171. DnsDatagram response = _blockedZoneManager.Query(request);
  2172. if (response is null)
  2173. {
  2174. //domain not blocked in blocked zone
  2175. response = _blockListZoneManager.Query(request); //check in block list zone
  2176. if (response is null)
  2177. return null; //domain not blocked in block list zone
  2178. //domain is blocked in block list zone
  2179. response.Tag = DnsServerResponseType.Blocked;
  2180. return response;
  2181. }
  2182. else
  2183. {
  2184. //domain is blocked in blocked zone
  2185. DnsQuestionRecord question = request.Question[0];
  2186. string GetBlockedDomain()
  2187. {
  2188. DnsResourceRecord firstAuthority = response.FindFirstAuthorityRecord();
  2189. if ((firstAuthority is not null) && (firstAuthority.Type == DnsResourceRecordType.SOA))
  2190. return firstAuthority.Name;
  2191. else
  2192. return question.Name;
  2193. }
  2194. if (_allowTxtBlockingReport && (question.Type == DnsResourceRecordType.TXT))
  2195. {
  2196. //return meta data
  2197. string blockedDomain = GetBlockedDomain();
  2198. IReadOnlyList<DnsResourceRecord> answer = [new DnsResourceRecord(question.Name, DnsResourceRecordType.TXT, question.Class, _blockingAnswerTtl, new DnsTXTRecordData("source=blocked-zone; domain=" + blockedDomain))];
  2199. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NoError, request.Question, answer) { Tag = DnsServerResponseType.Blocked };
  2200. }
  2201. else
  2202. {
  2203. string blockedDomain = null;
  2204. EDnsOption[] options = null;
  2205. if (_allowTxtBlockingReport && (request.EDNS is not null))
  2206. {
  2207. blockedDomain = GetBlockedDomain();
  2208. options = [new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.Blocked, "source=blocked-zone; domain=" + blockedDomain))];
  2209. }
  2210. IReadOnlyCollection<DnsARecordData> aRecords;
  2211. IReadOnlyCollection<DnsAAAARecordData> aaaaRecords;
  2212. switch (_blockingType)
  2213. {
  2214. case DnsServerBlockingType.AnyAddress:
  2215. aRecords = _aRecords;
  2216. aaaaRecords = _aaaaRecords;
  2217. break;
  2218. case DnsServerBlockingType.CustomAddress:
  2219. aRecords = _customBlockingARecords;
  2220. aaaaRecords = _customBlockingAAAARecords;
  2221. break;
  2222. case DnsServerBlockingType.NxDomain:
  2223. if (blockedDomain is null)
  2224. blockedDomain = GetBlockedDomain();
  2225. string parentDomain = AuthZoneManager.GetParentZone(blockedDomain);
  2226. if (parentDomain is null)
  2227. parentDomain = string.Empty;
  2228. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, false, false, false, DnsResponseCode.NxDomain, request.Question, null, [new DnsResourceRecord(parentDomain, DnsResourceRecordType.SOA, question.Class, _blockingAnswerTtl, _blockedZoneManager.DnsSOARecord)], null, request.EDNS is null ? ushort.MinValue : _udpPayloadSize, EDnsHeaderFlags.None, options) { Tag = DnsServerResponseType.Blocked };
  2229. default:
  2230. throw new InvalidOperationException();
  2231. }
  2232. IReadOnlyList<DnsResourceRecord> answer;
  2233. IReadOnlyList<DnsResourceRecord> authority = null;
  2234. switch (question.Type)
  2235. {
  2236. case DnsResourceRecordType.A:
  2237. {
  2238. if (aRecords.Count > 0)
  2239. {
  2240. DnsResourceRecord[] rrList = new DnsResourceRecord[aRecords.Count];
  2241. int i = 0;
  2242. foreach (DnsARecordData record in aRecords)
  2243. rrList[i++] = new DnsResourceRecord(question.Name, DnsResourceRecordType.A, question.Class, _blockingAnswerTtl, record);
  2244. answer = rrList;
  2245. }
  2246. else
  2247. {
  2248. answer = null;
  2249. authority = response.Authority;
  2250. }
  2251. }
  2252. break;
  2253. case DnsResourceRecordType.AAAA:
  2254. {
  2255. if (aaaaRecords.Count > 0)
  2256. {
  2257. DnsResourceRecord[] rrList = new DnsResourceRecord[aaaaRecords.Count];
  2258. int i = 0;
  2259. foreach (DnsAAAARecordData record in aaaaRecords)
  2260. rrList[i++] = new DnsResourceRecord(question.Name, DnsResourceRecordType.AAAA, question.Class, _blockingAnswerTtl, record);
  2261. answer = rrList;
  2262. }
  2263. else
  2264. {
  2265. answer = null;
  2266. authority = response.Authority;
  2267. }
  2268. }
  2269. break;
  2270. default:
  2271. answer = response.Answer;
  2272. authority = response.Authority;
  2273. break;
  2274. }
  2275. 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 };
  2276. }
  2277. }
  2278. }
  2279. private async Task<bool> IsAllowedAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol)
  2280. {
  2281. if (request.Question.Count > 0)
  2282. {
  2283. DnsQuestionRecord question = request.Question[0];
  2284. if (question.Type == DnsResourceRecordType.DS)
  2285. {
  2286. //DS is at parent zone which causes IsAllowed() to return null; change QTYPE to A to fix this issue that causes allowed domains to fail DNSSEC validation at downstream
  2287. DnsQuestionRecord newQuestion = new DnsQuestionRecord(question.Name, DnsResourceRecordType.A, DnsClass.IN);
  2288. request = new DnsDatagram(request.Identifier, request.IsResponse, request.OPCODE, request.AuthoritativeAnswer, request.Truncation, request.RecursionDesired, request.RecursionAvailable, request.AuthenticData, request.CheckingDisabled, request.RCODE, [newQuestion], request.Answer, request.Authority, request.Additional);
  2289. }
  2290. }
  2291. if (_enableBlocking)
  2292. {
  2293. if (_blockingBypassList is not null)
  2294. {
  2295. IPAddress remoteIP = remoteEP.Address;
  2296. foreach (NetworkAddress network in _blockingBypassList)
  2297. {
  2298. if (network.Contains(remoteIP))
  2299. return true;
  2300. }
  2301. }
  2302. if (_allowedZoneManager.IsAllowed(request) || _blockListZoneManager.IsAllowed(request))
  2303. return true;
  2304. }
  2305. foreach (IDnsRequestBlockingHandler blockingHandler in _dnsApplicationManager.DnsRequestBlockingHandlers)
  2306. {
  2307. try
  2308. {
  2309. if (await blockingHandler.IsAllowedAsync(request, remoteEP))
  2310. return true;
  2311. }
  2312. catch (Exception ex)
  2313. {
  2314. _log?.Write(remoteEP, protocol, ex);
  2315. }
  2316. }
  2317. return false;
  2318. }
  2319. private async Task<DnsDatagram> ProcessBlockedQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol)
  2320. {
  2321. if (_enableBlocking)
  2322. {
  2323. DnsDatagram blockedResponse = ProcessBlocked(request);
  2324. if (blockedResponse is not null)
  2325. return blockedResponse;
  2326. }
  2327. foreach (IDnsRequestBlockingHandler blockingHandler in _dnsApplicationManager.DnsRequestBlockingHandlers)
  2328. {
  2329. try
  2330. {
  2331. DnsDatagram appBlockedResponse = await blockingHandler.ProcessRequestAsync(request, remoteEP);
  2332. if (appBlockedResponse is not null)
  2333. {
  2334. if (appBlockedResponse.Tag is null)
  2335. appBlockedResponse.Tag = DnsServerResponseType.Blocked;
  2336. return appBlockedResponse;
  2337. }
  2338. }
  2339. catch (Exception ex)
  2340. {
  2341. _log?.Write(remoteEP, protocol, ex);
  2342. }
  2343. }
  2344. return null;
  2345. }
  2346. private async Task<DnsDatagram> ProcessRecursiveQueryAsync(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, IReadOnlyList<DnsResourceRecord> conditionalForwarders, bool dnssecValidation, bool cacheRefreshOperation, bool skipDnsAppAuthoritativeRequestHandlers)
  2347. {
  2348. bool isAllowed;
  2349. if (cacheRefreshOperation)
  2350. {
  2351. //cache refresh operation should be able to refresh all the records in cache
  2352. //this is since a blocked CNAME record could still be used by an allowed domain name and so must resolve
  2353. isAllowed = true;
  2354. }
  2355. else
  2356. {
  2357. isAllowed = await IsAllowedAsync(request, remoteEP, protocol);
  2358. if (!isAllowed)
  2359. {
  2360. DnsDatagram blockedResponse = await ProcessBlockedQueryAsync(request, remoteEP, protocol);
  2361. if (blockedResponse is not null)
  2362. return blockedResponse;
  2363. }
  2364. }
  2365. DnsDatagram response = await RecursiveResolveAsync(request, remoteEP, conditionalForwarders, dnssecValidation, false, cacheRefreshOperation, skipDnsAppAuthoritativeRequestHandlers);
  2366. if (response.Answer.Count > 0)
  2367. {
  2368. DnsResourceRecordType questionType = request.Question[0].Type;
  2369. DnsResourceRecord lastRR = response.GetLastAnswerRecord();
  2370. if ((lastRR.Type != questionType) && (lastRR.Type == DnsResourceRecordType.CNAME) && (questionType != DnsResourceRecordType.ANY))
  2371. response = await ProcessCNAMEAsync(request, response, remoteEP, protocol, true, cacheRefreshOperation, skipDnsAppAuthoritativeRequestHandlers);
  2372. if (!isAllowed)
  2373. {
  2374. //check for CNAME cloaking
  2375. for (int i = 0; i < response.Answer.Count; i++)
  2376. {
  2377. DnsResourceRecord record = response.Answer[i];
  2378. if (record.Type != DnsResourceRecordType.CNAME)
  2379. break; //no further CNAME records exists
  2380. 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);
  2381. if (request.Metadata is not null)
  2382. newRequest.SetMetadata(request.Metadata.NameServer);
  2383. //check allowed zone
  2384. isAllowed = await IsAllowedAsync(newRequest, remoteEP, protocol);
  2385. if (isAllowed)
  2386. break; //CNAME is in allowed zone
  2387. //check blocked zone and block list zone
  2388. DnsDatagram blockedResponse = await ProcessBlockedQueryAsync(newRequest, remoteEP, protocol);
  2389. if (blockedResponse is not null)
  2390. {
  2391. //found cname cloaking
  2392. List<DnsResourceRecord> answer = new List<DnsResourceRecord>();
  2393. //copy current and previous CNAME records
  2394. for (int j = 0; j <= i; j++)
  2395. answer.Add(response.Answer[j]);
  2396. //copy last response answers
  2397. answer.AddRange(blockedResponse.Answer);
  2398. //include blocked response additional section to pass on Extended DNS Errors
  2399. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, true, true, false, false, blockedResponse.RCODE, request.Question, answer, blockedResponse.Authority, blockedResponse.Additional) { Tag = blockedResponse.Tag };
  2400. }
  2401. }
  2402. }
  2403. }
  2404. if (response.Tag is null)
  2405. {
  2406. if (response.IsBlockedResponse())
  2407. response.Tag = DnsServerResponseType.UpstreamBlocked;
  2408. }
  2409. else if ((DnsServerResponseType)response.Tag == DnsServerResponseType.Cached)
  2410. {
  2411. if (response.IsBlockedResponse())
  2412. response.Tag = DnsServerResponseType.CacheBlocked;
  2413. }
  2414. return response;
  2415. }
  2416. private async Task<DnsDatagram> RecursiveResolveAsync(DnsDatagram request, IPEndPoint remoteEP, IReadOnlyList<DnsResourceRecord> conditionalForwarders, bool dnssecValidation, bool cachePrefetchOperation, bool cacheRefreshOperation, bool skipDnsAppAuthoritativeRequestHandlers)
  2417. {
  2418. DnsQuestionRecord question = request.Question[0];
  2419. NetworkAddress eDnsClientSubnet = null;
  2420. bool advancedForwardingClientSubnet = false; //this feature is used by Advanced Forwarding app to cache response per network group
  2421. if (_eDnsClientSubnet)
  2422. {
  2423. EDnsClientSubnetOptionData requestECS = request.GetEDnsClientSubnetOption();
  2424. if (requestECS is null)
  2425. {
  2426. if ((_eDnsClientSubnetIpv4Override is not null) && (remoteEP.AddressFamily == AddressFamily.InterNetwork))
  2427. {
  2428. //set ipv4 override shadow ECS option
  2429. eDnsClientSubnet = _eDnsClientSubnetIpv4Override;
  2430. request.SetShadowEDnsClientSubnetOption(eDnsClientSubnet);
  2431. }
  2432. else if ((_eDnsClientSubnetIpv6Override is not null) && (remoteEP.AddressFamily == AddressFamily.InterNetworkV6))
  2433. {
  2434. //set ipv6 override shadow ECS option
  2435. eDnsClientSubnet = _eDnsClientSubnetIpv6Override;
  2436. request.SetShadowEDnsClientSubnetOption(eDnsClientSubnet);
  2437. }
  2438. else if (!NetUtilities.IsPrivateIP(remoteEP.Address))
  2439. {
  2440. //set shadow ECS option
  2441. switch (remoteEP.AddressFamily)
  2442. {
  2443. case AddressFamily.InterNetwork:
  2444. eDnsClientSubnet = new NetworkAddress(remoteEP.Address, _eDnsClientSubnetIPv4PrefixLength);
  2445. request.SetShadowEDnsClientSubnetOption(eDnsClientSubnet);
  2446. break;
  2447. case AddressFamily.InterNetworkV6:
  2448. eDnsClientSubnet = new NetworkAddress(remoteEP.Address, _eDnsClientSubnetIPv6PrefixLength);
  2449. request.SetShadowEDnsClientSubnetOption(eDnsClientSubnet);
  2450. break;
  2451. default:
  2452. request.ShadowHideEDnsClientSubnetOption();
  2453. break;
  2454. }
  2455. }
  2456. }
  2457. else if ((requestECS.Family != EDnsClientSubnetAddressFamily.IPv4) && (requestECS.Family != EDnsClientSubnetAddressFamily.IPv6))
  2458. {
  2459. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, true, false, request.CheckingDisabled, DnsResponseCode.FormatError, request.Question) { Tag = DnsServerResponseType.Authoritative };
  2460. }
  2461. else if (requestECS.AdvancedForwardingClientSubnet)
  2462. {
  2463. //request from Advanced Forwarding app
  2464. advancedForwardingClientSubnet = true;
  2465. eDnsClientSubnet = new NetworkAddress(requestECS.Address, requestECS.SourcePrefixLength);
  2466. }
  2467. else if ((requestECS.SourcePrefixLength == 0) || NetUtilities.IsPrivateIP(requestECS.Address))
  2468. {
  2469. //disable ECS option
  2470. request.ShadowHideEDnsClientSubnetOption();
  2471. }
  2472. else if ((_eDnsClientSubnetIpv4Override is not null) && (remoteEP.AddressFamily == AddressFamily.InterNetwork))
  2473. {
  2474. //set ipv4 override shadow ECS option
  2475. eDnsClientSubnet = _eDnsClientSubnetIpv4Override;
  2476. request.SetShadowEDnsClientSubnetOption(eDnsClientSubnet);
  2477. }
  2478. else if ((_eDnsClientSubnetIpv6Override is not null) && (remoteEP.AddressFamily == AddressFamily.InterNetworkV6))
  2479. {
  2480. //set ipv6 override shadow ECS option
  2481. eDnsClientSubnet = _eDnsClientSubnetIpv6Override;
  2482. request.SetShadowEDnsClientSubnetOption(eDnsClientSubnet);
  2483. }
  2484. else
  2485. {
  2486. //use ECS from client request
  2487. switch (requestECS.Family)
  2488. {
  2489. case EDnsClientSubnetAddressFamily.IPv4:
  2490. eDnsClientSubnet = new NetworkAddress(requestECS.Address, Math.Min(requestECS.SourcePrefixLength, _eDnsClientSubnetIPv4PrefixLength));
  2491. request.SetShadowEDnsClientSubnetOption(eDnsClientSubnet);
  2492. break;
  2493. case EDnsClientSubnetAddressFamily.IPv6:
  2494. eDnsClientSubnet = new NetworkAddress(requestECS.Address, Math.Min(requestECS.SourcePrefixLength, _eDnsClientSubnetIPv6PrefixLength));
  2495. request.SetShadowEDnsClientSubnetOption(eDnsClientSubnet);
  2496. break;
  2497. }
  2498. }
  2499. }
  2500. else
  2501. {
  2502. //ECS feature disabled
  2503. EDnsClientSubnetOptionData requestECS = request.GetEDnsClientSubnetOption();
  2504. if (requestECS is not null)
  2505. {
  2506. advancedForwardingClientSubnet = requestECS.AdvancedForwardingClientSubnet;
  2507. if (advancedForwardingClientSubnet)
  2508. eDnsClientSubnet = new NetworkAddress(requestECS.Address, requestECS.SourcePrefixLength); //request from Advanced Forwarding app
  2509. else
  2510. request.ShadowHideEDnsClientSubnetOption(); //hide ECS option
  2511. }
  2512. }
  2513. if (!cachePrefetchOperation && !cacheRefreshOperation)
  2514. {
  2515. //query cache zone to see if answer available
  2516. DnsDatagram cacheResponse = QueryCache(request, false, false);
  2517. if (cacheResponse is not null)
  2518. {
  2519. if (_cachePrefetchTrigger > 0)
  2520. {
  2521. //inspect response TTL values to decide if prefetch trigger is needed
  2522. foreach (DnsResourceRecord answer in cacheResponse.Answer)
  2523. {
  2524. if ((answer.OriginalTtlValue >= _cachePrefetchEligibility) && (answer.TTL <= _cachePrefetchTrigger))
  2525. {
  2526. //trigger prefetch async
  2527. _ = PrefetchCacheAsync(request, remoteEP, conditionalForwarders);
  2528. break;
  2529. }
  2530. }
  2531. }
  2532. return cacheResponse;
  2533. }
  2534. }
  2535. //recursion with locking
  2536. TaskCompletionSource<RecursiveResolveResponse> resolverTaskCompletionSource = new TaskCompletionSource<RecursiveResolveResponse>();
  2537. Task<RecursiveResolveResponse> resolverTask = _resolverTasks.GetOrAdd(GetResolverQueryKey(question, eDnsClientSubnet), resolverTaskCompletionSource.Task);
  2538. if (resolverTask.Equals(resolverTaskCompletionSource.Task))
  2539. {
  2540. //got new resolver task added so question is not being resolved; do recursive resolution in another task on resolver thread pool
  2541. _ = Task.Factory.StartNew(delegate ()
  2542. {
  2543. return RecursiveResolverBackgroundTaskAsync(question, eDnsClientSubnet, advancedForwardingClientSubnet, conditionalForwarders, dnssecValidation, cachePrefetchOperation, cacheRefreshOperation, skipDnsAppAuthoritativeRequestHandlers, resolverTaskCompletionSource);
  2544. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _resolverTaskScheduler);
  2545. }
  2546. //request is being recursively resolved by another thread
  2547. if (cachePrefetchOperation)
  2548. return null; //return null as prefetch worker thread does not need valid response and thus does not need to wait
  2549. if (_serveStale)
  2550. {
  2551. int waitTimeout = Math.Min(_serveStaleMaxWaitTime, _clientTimeout - SERVE_STALE_TIME_DIFFERENCE); //200ms before client timeout or max 1800ms [RFC 8767]
  2552. //wait till short timeout for response
  2553. if ((waitTimeout > 0) && (await Task.WhenAny(resolverTask, Task.Delay(waitTimeout)) == resolverTask))
  2554. {
  2555. //resolver signaled
  2556. RecursiveResolveResponse response = await resolverTask;
  2557. if (response is not null)
  2558. return PrepareRecursiveResolveResponse(request, response);
  2559. //resolver had exception
  2560. }
  2561. else
  2562. {
  2563. //wait timed out
  2564. //query cache zone to return stale answer (if available) as per RFC 8767
  2565. DnsDatagram staleResponse = QueryCache(request, true, false);
  2566. if (staleResponse is not null)
  2567. return staleResponse;
  2568. //no stale record was found
  2569. //wait till full timeout before responding as ServerFailure
  2570. int timeout = _clientTimeout - waitTimeout;
  2571. if (await Task.WhenAny(resolverTask, Task.Delay(timeout)) == resolverTask)
  2572. {
  2573. //resolver signaled
  2574. RecursiveResolveResponse response = await resolverTask;
  2575. if (response is not null)
  2576. return PrepareRecursiveResolveResponse(request, response);
  2577. //resolver had exception
  2578. }
  2579. }
  2580. }
  2581. else
  2582. {
  2583. //wait till full client timeout for response
  2584. if (await Task.WhenAny(resolverTask, Task.Delay(_clientTimeout)) == resolverTask)
  2585. {
  2586. //resolver signaled
  2587. RecursiveResolveResponse response = await resolverTask;
  2588. if (response is not null)
  2589. return PrepareRecursiveResolveResponse(request, response);
  2590. //resolver had exception
  2591. }
  2592. }
  2593. //no response available; respond with ServerFailure
  2594. EDnsOption[] options = [new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.Other, "Waiting for resolver. Please try again."))];
  2595. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, request.RecursionDesired, true, false, request.CheckingDisabled, DnsResponseCode.ServerFailure, request.Question, null, null, null, _udpPayloadSize, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, options);
  2596. }
  2597. private async Task RecursiveResolverBackgroundTaskAsync(DnsQuestionRecord question, NetworkAddress eDnsClientSubnet, bool advancedForwardingClientSubnet, IReadOnlyList<DnsResourceRecord> conditionalForwarders, bool dnssecValidation, bool cachePrefetchOperation, bool cacheRefreshOperation, bool skipDnsAppAuthoritativeRequestHandlers, TaskCompletionSource<RecursiveResolveResponse> taskCompletionSource)
  2598. {
  2599. try
  2600. {
  2601. //recursive resolve and update cache
  2602. IDnsCache dnsCache;
  2603. if (cachePrefetchOperation || cacheRefreshOperation)
  2604. dnsCache = new ResolverPrefetchDnsCache(this, skipDnsAppAuthoritativeRequestHandlers, question);
  2605. else if (skipDnsAppAuthoritativeRequestHandlers || advancedForwardingClientSubnet)
  2606. dnsCache = _dnsCacheSkipDnsApps; //to prevent request reaching apps again
  2607. else
  2608. dnsCache = _dnsCache;
  2609. DnsDatagram response;
  2610. if (conditionalForwarders is not null)
  2611. {
  2612. if (conditionalForwarders.Count > 0)
  2613. {
  2614. //do priority based conditional forwarding
  2615. response = await PriorityConditionalForwarderResolveAsync(question, eDnsClientSubnet, advancedForwardingClientSubnet, dnsCache, skipDnsAppAuthoritativeRequestHandlers, conditionalForwarders);
  2616. }
  2617. else
  2618. {
  2619. //do force recursive resolution
  2620. response = await TechnitiumLibrary.TaskExtensions.TimeoutAsync(delegate (CancellationToken cancellationToken1)
  2621. {
  2622. return DnsClient.RecursiveResolveAsync(question, dnsCache, _proxy, _preferIPv6, _udpPayloadSize, _randomizeName, _qnameMinimization, dnssecValidation, eDnsClientSubnet, _resolverRetries, _resolverTimeout, _resolverConcurrency, _resolverMaxStackCount, true, _nsRevalidation, true, cancellationToken: cancellationToken1);
  2623. }, RECURSIVE_RESOLUTION_TIMEOUT);
  2624. }
  2625. }
  2626. else
  2627. {
  2628. //do default recursive resolution
  2629. response = await DefaultRecursiveResolveAsync(question, eDnsClientSubnet, dnsCache, dnssecValidation, skipDnsAppAuthoritativeRequestHandlers);
  2630. }
  2631. switch (response.RCODE)
  2632. {
  2633. case DnsResponseCode.NoError:
  2634. case DnsResponseCode.NxDomain:
  2635. case DnsResponseCode.YXDomain:
  2636. taskCompletionSource.SetResult(new RecursiveResolveResponse(response, response));
  2637. break;
  2638. default:
  2639. throw new DnsServerException("DNS Server received a response for '" + question.ToString() + "' with RCODE=" + response.RCODE.ToString() + " from: " + (response.Metadata is null ? "unknown" : response.Metadata.NameServer));
  2640. }
  2641. }
  2642. catch (Exception ex)
  2643. {
  2644. if (_resolverLog is not null)
  2645. {
  2646. string strForwarders = null;
  2647. if ((conditionalForwarders is not null) && (conditionalForwarders.Count > 0))
  2648. {
  2649. foreach (DnsResourceRecord conditionalForwarder in conditionalForwarders)
  2650. {
  2651. NameServerAddress nameServer = (conditionalForwarder.RDATA as DnsForwarderRecordData).NameServer;
  2652. if (strForwarders is null)
  2653. strForwarders = nameServer.ToString();
  2654. else
  2655. strForwarders += ", " + nameServer.ToString();
  2656. }
  2657. }
  2658. else if ((_forwarders is not null) && (_forwarders.Count > 0))
  2659. {
  2660. foreach (NameServerAddress nameServer in _forwarders)
  2661. {
  2662. if (strForwarders is null)
  2663. strForwarders = nameServer.ToString();
  2664. else
  2665. strForwarders += ", " + nameServer.ToString();
  2666. }
  2667. }
  2668. _resolverLog.Write("DNS Server failed to resolve the request '" + question.ToString() + "'" + (strForwarders is null ? "" : " using forwarders: " + strForwarders) + ".\r\n" + ex.ToString());
  2669. }
  2670. if (_serveStale)
  2671. {
  2672. //fetch and reset stale records
  2673. 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));
  2674. DnsDatagram staleResponse = QueryCache(cacheRequest, true, true);
  2675. if (staleResponse is not null)
  2676. {
  2677. //signal stale response
  2678. if (!dnssecValidation || staleResponse.AuthenticData)
  2679. {
  2680. taskCompletionSource.SetResult(new RecursiveResolveResponse(staleResponse, staleResponse));
  2681. }
  2682. else
  2683. {
  2684. List<EDnsOption> options;
  2685. if ((staleResponse.EDNS is not null) && (staleResponse.EDNS.Options.Count > 0))
  2686. {
  2687. options = new List<EDnsOption>(staleResponse.EDNS.Options.Count);
  2688. foreach (EDnsOption option in staleResponse.EDNS.Options)
  2689. {
  2690. if (option.Code == EDnsOptionCode.EXTENDED_DNS_ERROR)
  2691. options.Add(option);
  2692. }
  2693. }
  2694. else
  2695. {
  2696. options = null;
  2697. }
  2698. 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);
  2699. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, staleResponse));
  2700. }
  2701. return;
  2702. }
  2703. }
  2704. //signal failure response to release waiting tasks
  2705. if (ex is DnsClientResponseDnssecValidationException ex2)
  2706. {
  2707. List<EDnsOption> options;
  2708. if (ex2.Response.DnsClientExtendedErrors.Count > 0)
  2709. {
  2710. options = new List<EDnsOption>(ex2.Response.DnsClientExtendedErrors.Count);
  2711. foreach (EDnsExtendedDnsErrorOptionData dnsError in ex2.Response.DnsClientExtendedErrors)
  2712. options.Add(new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, dnsError));
  2713. }
  2714. else
  2715. {
  2716. options = null;
  2717. }
  2718. 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);
  2719. if ((ex2.Response.Question.Count > 0) && ex2.Response.Question[0].Equals(question))
  2720. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, ex2.Response));
  2721. else
  2722. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, failureResponse));
  2723. }
  2724. else if (ex is DnsClientNoResponseException ex3)
  2725. {
  2726. IReadOnlyList<EDnsOption> options;
  2727. if (ex3.InnerException is SocketException ex3a)
  2728. {
  2729. if (ex3a.SocketErrorCode == SocketError.TimedOut)
  2730. options = [new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NoReachableAuthority, "Request timed out"))];
  2731. else
  2732. options = [new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NetworkError, "Socket error: " + ex3a.SocketErrorCode.ToString()))];
  2733. }
  2734. else
  2735. {
  2736. options = [new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NoReachableAuthority, "No response from name servers for " + question.ToString()))];
  2737. }
  2738. 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);
  2739. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, failureResponse));
  2740. }
  2741. else if (ex is SocketException ex4)
  2742. {
  2743. IReadOnlyList<EDnsOption> options;
  2744. if (ex4.SocketErrorCode == SocketError.TimedOut)
  2745. options = [new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NoReachableAuthority, "Request timed out"))];
  2746. else
  2747. options = [new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NetworkError, "Socket error: " + ex4.SocketErrorCode.ToString()))];
  2748. 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);
  2749. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, failureResponse));
  2750. }
  2751. else if (ex is IOException ex5)
  2752. {
  2753. IReadOnlyList<EDnsOption> options;
  2754. if (ex5.InnerException is SocketException ex5a)
  2755. {
  2756. if (ex5a.SocketErrorCode == SocketError.TimedOut)
  2757. options = [new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NoReachableAuthority, "Request timed out"))];
  2758. else
  2759. options = [new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NetworkError, "Socket error: " + ex5a.SocketErrorCode.ToString()))];
  2760. }
  2761. else
  2762. {
  2763. options = [new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.NetworkError, "IO error: " + ex5.Message))];
  2764. }
  2765. 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);
  2766. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, failureResponse));
  2767. }
  2768. else
  2769. {
  2770. IReadOnlyList<EDnsOption> options = [new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, new EDnsExtendedDnsErrorOptionData(EDnsExtendedDnsErrorCode.Other, "Resolver exception"))];
  2771. 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);
  2772. taskCompletionSource.SetResult(new RecursiveResolveResponse(failureResponse, failureResponse));
  2773. }
  2774. }
  2775. finally
  2776. {
  2777. _resolverTasks.TryRemove(GetResolverQueryKey(question, eDnsClientSubnet), out _);
  2778. }
  2779. }
  2780. private async Task<DnsDatagram> DefaultRecursiveResolveAsync(DnsQuestionRecord question, NetworkAddress eDnsClientSubnet, IDnsCache dnsCache, bool dnssecValidation, bool skipDnsAppAuthoritativeRequestHandlers, CancellationToken cancellationToken = default)
  2781. {
  2782. if ((_forwarders is not null) && (_forwarders.Count > 0))
  2783. {
  2784. //use forwarders
  2785. if (_concurrentForwarding)
  2786. {
  2787. if (_proxy is null)
  2788. {
  2789. //recursive resolve forwarders only when proxy is null else let proxy resolve it to allow using .onion or private domains
  2790. foreach (NameServerAddress forwarder in _forwarders)
  2791. {
  2792. if (forwarder.IsIPEndPointStale)
  2793. {
  2794. //refresh forwarder IPEndPoint if stale
  2795. await TechnitiumLibrary.TaskExtensions.TimeoutAsync(delegate (CancellationToken cancellationToken1)
  2796. {
  2797. return forwarder.RecursiveResolveIPAddressAsync(dnsCache, null, _preferIPv6, _udpPayloadSize, _randomizeName, _resolverRetries, _resolverTimeout, _resolverConcurrency, _resolverMaxStackCount, cancellationToken1);
  2798. }, RECURSIVE_RESOLUTION_TIMEOUT, cancellationToken);
  2799. }
  2800. }
  2801. }
  2802. //query forwarders and update cache
  2803. DnsClient dnsClient = new DnsClient(_forwarders);
  2804. dnsClient.Cache = dnsCache;
  2805. dnsClient.Proxy = _proxy;
  2806. dnsClient.PreferIPv6 = _preferIPv6;
  2807. dnsClient.RandomizeName = _randomizeName;
  2808. dnsClient.Retries = _forwarderRetries;
  2809. dnsClient.Timeout = _forwarderTimeout;
  2810. dnsClient.Concurrency = _forwarderConcurrency;
  2811. dnsClient.UdpPayloadSize = _udpPayloadSize;
  2812. dnsClient.DnssecValidation = dnssecValidation;
  2813. dnsClient.EDnsClientSubnet = eDnsClientSubnet;
  2814. 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
  2815. return await dnsClient.ResolveAsync(question, cancellationToken);
  2816. }
  2817. else
  2818. {
  2819. //do sequentially ordered forwarding
  2820. Exception lastException = null;
  2821. foreach (NameServerAddress forwarder in _forwarders)
  2822. {
  2823. if (_proxy is null)
  2824. {
  2825. //recursive resolve forwarder only when proxy is null else let proxy resolve it to allow using .onion or private domains
  2826. if (forwarder.IsIPEndPointStale)
  2827. {
  2828. //refresh forwarder IPEndPoint if stale
  2829. await TechnitiumLibrary.TaskExtensions.TimeoutAsync(delegate (CancellationToken cancellationToken1)
  2830. {
  2831. return forwarder.RecursiveResolveIPAddressAsync(dnsCache, null, _preferIPv6, _udpPayloadSize, _randomizeName, _resolverRetries, _resolverTimeout, _resolverConcurrency, _resolverMaxStackCount, cancellationToken1);
  2832. }, RECURSIVE_RESOLUTION_TIMEOUT, cancellationToken);
  2833. }
  2834. }
  2835. //query forwarder and update cache
  2836. DnsClient dnsClient = new DnsClient(forwarder);
  2837. dnsClient.Cache = dnsCache;
  2838. dnsClient.Proxy = _proxy;
  2839. dnsClient.PreferIPv6 = _preferIPv6;
  2840. dnsClient.RandomizeName = _randomizeName;
  2841. dnsClient.Retries = _forwarderRetries;
  2842. dnsClient.Timeout = _forwarderTimeout;
  2843. dnsClient.Concurrency = _forwarderConcurrency;
  2844. dnsClient.UdpPayloadSize = _udpPayloadSize;
  2845. dnsClient.DnssecValidation = dnssecValidation;
  2846. dnsClient.EDnsClientSubnet = eDnsClientSubnet;
  2847. 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
  2848. try
  2849. {
  2850. return await dnsClient.ResolveAsync(question, cancellationToken);
  2851. }
  2852. catch (Exception ex)
  2853. {
  2854. lastException = ex;
  2855. }
  2856. if (dnsCache is not ResolverPrefetchDnsCache)
  2857. dnsCache = new ResolverPrefetchDnsCache(this, skipDnsAppAuthoritativeRequestHandlers, question); //to prevent low priority tasks to read failure response from cache
  2858. }
  2859. ExceptionDispatchInfo.Capture(lastException).Throw();
  2860. throw lastException;
  2861. }
  2862. }
  2863. else
  2864. {
  2865. //do recursive resolution
  2866. return await TechnitiumLibrary.TaskExtensions.TimeoutAsync(delegate (CancellationToken cancellationToken1)
  2867. {
  2868. return DnsClient.RecursiveResolveAsync(question, dnsCache, _proxy, _preferIPv6, _udpPayloadSize, _randomizeName, _qnameMinimization, dnssecValidation, eDnsClientSubnet, _resolverRetries, _resolverTimeout, _resolverConcurrency, _resolverMaxStackCount, true, _nsRevalidation, true, null, cancellationToken1);
  2869. }, RECURSIVE_RESOLUTION_TIMEOUT, cancellationToken);
  2870. }
  2871. }
  2872. private async Task<DnsDatagram> PriorityConditionalForwarderResolveAsync(DnsQuestionRecord question, NetworkAddress eDnsClientSubnet, bool advancedForwardingClientSubnet, IDnsCache dnsCache, bool skipDnsAppAuthoritativeRequestHandlers, IReadOnlyList<DnsResourceRecord> conditionalForwarders)
  2873. {
  2874. if (conditionalForwarders.Count == 1)
  2875. {
  2876. DnsResourceRecord conditionalForwarder = conditionalForwarders[0];
  2877. return await ConditionalForwarderResolveAsync(question, eDnsClientSubnet, advancedForwardingClientSubnet, dnsCache, conditionalForwarder.RDATA as DnsForwarderRecordData, conditionalForwarder.Name, skipDnsAppAuthoritativeRequestHandlers);
  2878. }
  2879. //group by priority and check for forwarder name server resolution
  2880. Dictionary<byte, List<DnsResourceRecord>> conditionalForwarderGroups = new Dictionary<byte, List<DnsResourceRecord>>(conditionalForwarders.Count);
  2881. {
  2882. List<Task> resolveTasks = new List<Task>();
  2883. foreach (DnsResourceRecord conditionalForwarder in conditionalForwarders)
  2884. {
  2885. if (conditionalForwarder.Type != DnsResourceRecordType.FWD)
  2886. continue;
  2887. DnsForwarderRecordData forwarder = conditionalForwarder.RDATA as DnsForwarderRecordData;
  2888. if (conditionalForwarderGroups.TryGetValue(forwarder.Priority, out List<DnsResourceRecord> conditionalForwardersEntry))
  2889. {
  2890. conditionalForwardersEntry.Add(conditionalForwarder);
  2891. }
  2892. else
  2893. {
  2894. conditionalForwardersEntry = new List<DnsResourceRecord>(2)
  2895. {
  2896. conditionalForwarder
  2897. };
  2898. conditionalForwarderGroups[forwarder.Priority] = conditionalForwardersEntry;
  2899. }
  2900. if (forwarder.Forwarder.Equals("this-server", StringComparison.OrdinalIgnoreCase))
  2901. continue; //skip resolving
  2902. NetProxy proxy = forwarder.GetProxy(_proxy);
  2903. if (proxy is null)
  2904. {
  2905. //recursive resolve forwarder only when proxy is null else let proxy resolve it to allow using .onion or private domains
  2906. if (forwarder.NameServer.IsIPEndPointStale)
  2907. {
  2908. //refresh forwarder IPEndPoint if stale
  2909. resolveTasks.Add(TechnitiumLibrary.TaskExtensions.TimeoutAsync(delegate (CancellationToken cancellationToken1)
  2910. {
  2911. return forwarder.NameServer.RecursiveResolveIPAddressAsync(dnsCache, null, _preferIPv6, _udpPayloadSize, _randomizeName, _resolverRetries, _resolverTimeout, _resolverConcurrency, _resolverMaxStackCount, cancellationToken1);
  2912. }, RECURSIVE_RESOLUTION_TIMEOUT));
  2913. }
  2914. }
  2915. }
  2916. if (resolveTasks.Count > 0)
  2917. await Task.WhenAll(resolveTasks);
  2918. }
  2919. if (conditionalForwarderGroups.Count == 1)
  2920. {
  2921. foreach (KeyValuePair<byte, List<DnsResourceRecord>> conditionalForwardersEntry in conditionalForwarderGroups)
  2922. return await ConcurrentConditionalForwarderResolveAsync(question, eDnsClientSubnet, advancedForwardingClientSubnet, dnsCache, conditionalForwardersEntry.Value, skipDnsAppAuthoritativeRequestHandlers);
  2923. }
  2924. List<byte> priorities = new List<byte>(conditionalForwarderGroups.Keys);
  2925. priorities.Sort();
  2926. using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource())
  2927. {
  2928. CancellationToken currentCancellationToken = cancellationTokenSource.Token;
  2929. DnsDatagram lastResponse = null;
  2930. Exception lastException = null;
  2931. foreach (byte priority in priorities)
  2932. {
  2933. if (!conditionalForwarderGroups.TryGetValue(priority, out List<DnsResourceRecord> conditionalForwardersEntry))
  2934. continue;
  2935. Task<DnsDatagram> priorityTask = ConcurrentConditionalForwarderResolveAsync(question, eDnsClientSubnet, advancedForwardingClientSubnet, dnsCache, conditionalForwardersEntry, skipDnsAppAuthoritativeRequestHandlers, currentCancellationToken);
  2936. try
  2937. {
  2938. DnsDatagram priorityTaskResponse = await priorityTask; //await to get response
  2939. switch (priorityTaskResponse.RCODE)
  2940. {
  2941. case DnsResponseCode.NoError:
  2942. case DnsResponseCode.NxDomain:
  2943. case DnsResponseCode.YXDomain:
  2944. cancellationTokenSource.Cancel(); //to stop other priority resolver tasks
  2945. return priorityTaskResponse;
  2946. default:
  2947. //keep response
  2948. lastResponse = priorityTaskResponse;
  2949. break;
  2950. }
  2951. }
  2952. catch (OperationCanceledException)
  2953. {
  2954. throw;
  2955. }
  2956. catch (Exception ex)
  2957. {
  2958. lastException = ex;
  2959. if (lastException is AggregateException)
  2960. lastException = lastException.InnerException;
  2961. }
  2962. if (dnsCache is not ResolverPrefetchDnsCache)
  2963. dnsCache = new ResolverPrefetchDnsCache(this, skipDnsAppAuthoritativeRequestHandlers, question); //to prevent low priority tasks to read failure response from cache
  2964. }
  2965. if (lastResponse is not null)
  2966. return lastResponse;
  2967. if (lastException is not null)
  2968. ExceptionDispatchInfo.Capture(lastException).Throw();
  2969. throw new InvalidOperationException();
  2970. }
  2971. }
  2972. private async Task<DnsDatagram> ConcurrentConditionalForwarderResolveAsync(DnsQuestionRecord question, NetworkAddress eDnsClientSubnet, bool advancedForwardingClientSubnet, IDnsCache dnsCache, IReadOnlyList<DnsResourceRecord> conditionalForwarders, bool skipDnsAppAuthoritativeRequestHandlers, CancellationToken cancellationToken = default)
  2973. {
  2974. if (conditionalForwarders.Count == 1)
  2975. {
  2976. DnsResourceRecord conditionalForwarder = conditionalForwarders[0];
  2977. return await ConditionalForwarderResolveAsync(question, eDnsClientSubnet, advancedForwardingClientSubnet, dnsCache, conditionalForwarder.RDATA as DnsForwarderRecordData, conditionalForwarder.Name, skipDnsAppAuthoritativeRequestHandlers, cancellationToken);
  2978. }
  2979. using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource())
  2980. {
  2981. using CancellationTokenRegistration r = cancellationToken.Register(cancellationTokenSource.Cancel);
  2982. CancellationToken currentCancellationToken = cancellationTokenSource.Token;
  2983. List<Task<DnsDatagram>> tasks = new List<Task<DnsDatagram>>(conditionalForwarders.Count);
  2984. //start worker tasks
  2985. foreach (DnsResourceRecord conditionalForwarder in conditionalForwarders)
  2986. {
  2987. if (conditionalForwarder.Type != DnsResourceRecordType.FWD)
  2988. continue;
  2989. DnsForwarderRecordData forwarder = conditionalForwarder.RDATA as DnsForwarderRecordData;
  2990. tasks.Add(Task.Factory.StartNew(delegate ()
  2991. {
  2992. return ConditionalForwarderResolveAsync(question, eDnsClientSubnet, advancedForwardingClientSubnet, dnsCache, forwarder, conditionalForwarder.Name, skipDnsAppAuthoritativeRequestHandlers, currentCancellationToken);
  2993. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Current).Unwrap());
  2994. }
  2995. //wait for first positive response, or for all tasks to fault
  2996. DnsDatagram lastResponse = null;
  2997. Exception lastException = null;
  2998. while (tasks.Count > 0)
  2999. {
  3000. Task<DnsDatagram> completedTask = await Task.WhenAny(tasks);
  3001. try
  3002. {
  3003. DnsDatagram taskResponse = await completedTask; //await to get response
  3004. switch (taskResponse.RCODE)
  3005. {
  3006. case DnsResponseCode.NoError:
  3007. case DnsResponseCode.NxDomain:
  3008. case DnsResponseCode.YXDomain:
  3009. cancellationTokenSource.Cancel(); //to stop other resolver tasks
  3010. return taskResponse;
  3011. default:
  3012. //keep response
  3013. lastResponse = taskResponse;
  3014. break;
  3015. }
  3016. }
  3017. catch (OperationCanceledException)
  3018. {
  3019. throw;
  3020. }
  3021. catch (Exception ex)
  3022. {
  3023. lastException = ex;
  3024. if (lastException is AggregateException)
  3025. lastException = lastException.InnerException;
  3026. }
  3027. tasks.Remove(completedTask);
  3028. }
  3029. if (lastResponse is not null)
  3030. return lastResponse;
  3031. if (lastException is not null)
  3032. ExceptionDispatchInfo.Capture(lastException).Throw();
  3033. throw new InvalidOperationException();
  3034. }
  3035. }
  3036. private Task<DnsDatagram> ConditionalForwarderResolveAsync(DnsQuestionRecord question, NetworkAddress eDnsClientSubnet, bool advancedForwardingClientSubnet, IDnsCache dnsCache, DnsForwarderRecordData forwarder, string conditionalForwardingZoneCut, bool skipDnsAppAuthoritativeRequestHandlers, CancellationToken cancellationToken = default)
  3037. {
  3038. if (forwarder.Forwarder.Equals("this-server", StringComparison.OrdinalIgnoreCase))
  3039. {
  3040. //resolve via default recursive resolver with DNSSEC validation preference
  3041. return DefaultRecursiveResolveAsync(question, eDnsClientSubnet, dnsCache, forwarder.DnssecValidation, skipDnsAppAuthoritativeRequestHandlers, cancellationToken);
  3042. }
  3043. else
  3044. {
  3045. //resolve via conditional forwarder
  3046. DnsClient dnsClient = new DnsClient(forwarder.NameServer);
  3047. dnsClient.Cache = dnsCache;
  3048. dnsClient.Proxy = forwarder.GetProxy(_proxy);
  3049. dnsClient.PreferIPv6 = _preferIPv6;
  3050. dnsClient.RandomizeName = _randomizeName;
  3051. dnsClient.Retries = _forwarderRetries;
  3052. dnsClient.Timeout = _forwarderTimeout;
  3053. dnsClient.Concurrency = _forwarderConcurrency;
  3054. dnsClient.UdpPayloadSize = _udpPayloadSize;
  3055. dnsClient.DnssecValidation = forwarder.DnssecValidation;
  3056. dnsClient.EDnsClientSubnet = eDnsClientSubnet;
  3057. dnsClient.AdvancedForwardingClientSubnet = advancedForwardingClientSubnet;
  3058. dnsClient.ConditionalForwardingZoneCut = conditionalForwardingZoneCut;
  3059. return dnsClient.ResolveAsync(question, cancellationToken);
  3060. }
  3061. }
  3062. private DnsDatagram PrepareRecursiveResolveResponse(DnsDatagram request, RecursiveResolveResponse resolveResponse)
  3063. {
  3064. //get a tailored response for the request
  3065. bool dnssecOk = request.DnssecOk;
  3066. if (dnssecOk && request.CheckingDisabled)
  3067. {
  3068. bool authenticData = false;
  3069. if (dnssecOk)
  3070. {
  3071. if (resolveResponse.CheckingDisabledResponse.Answer.Count > 0)
  3072. {
  3073. authenticData = true;
  3074. foreach (DnsResourceRecord record in resolveResponse.CheckingDisabledResponse.Answer)
  3075. {
  3076. if (record.DnssecStatus != DnssecStatus.Secure)
  3077. {
  3078. authenticData = false;
  3079. break;
  3080. }
  3081. }
  3082. }
  3083. else if (resolveResponse.CheckingDisabledResponse.Authority.Count > 0)
  3084. {
  3085. authenticData = true;
  3086. foreach (DnsResourceRecord record in resolveResponse.CheckingDisabledResponse.Authority)
  3087. {
  3088. if (record.DnssecStatus != DnssecStatus.Secure)
  3089. {
  3090. authenticData = false;
  3091. break;
  3092. }
  3093. }
  3094. }
  3095. }
  3096. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, true, true, authenticData, true, resolveResponse.CheckingDisabledResponse.RCODE, request.Question, resolveResponse.CheckingDisabledResponse.Answer, resolveResponse.CheckingDisabledResponse.Authority, RemoveOPTFromAdditional(resolveResponse.CheckingDisabledResponse.Additional, true), _udpPayloadSize, EDnsHeaderFlags.DNSSEC_OK, resolveResponse.CheckingDisabledResponse.EDNS?.Options);
  3097. }
  3098. DnsDatagram response = resolveResponse.Response;
  3099. IReadOnlyList<DnsResourceRecord> answer = response.Answer;
  3100. IReadOnlyList<DnsResourceRecord> authority = response.Authority;
  3101. IReadOnlyList<DnsResourceRecord> additional = response.Additional;
  3102. //answer section checks
  3103. if (!dnssecOk && (answer.Count > 0) && (response.Question[0].Type != DnsResourceRecordType.ANY))
  3104. {
  3105. //remove RRSIGs from answer
  3106. bool foundRRSIG = false;
  3107. foreach (DnsResourceRecord record in answer)
  3108. {
  3109. if (record.Type == DnsResourceRecordType.RRSIG)
  3110. {
  3111. foundRRSIG = true;
  3112. break;
  3113. }
  3114. }
  3115. if (foundRRSIG)
  3116. {
  3117. List<DnsResourceRecord> newAnswer = new List<DnsResourceRecord>(answer.Count);
  3118. foreach (DnsResourceRecord record in answer)
  3119. {
  3120. if (record.Type == DnsResourceRecordType.RRSIG)
  3121. continue;
  3122. newAnswer.Add(record);
  3123. }
  3124. answer = newAnswer;
  3125. }
  3126. }
  3127. //authority section checks
  3128. if (!dnssecOk && (authority.Count > 0))
  3129. {
  3130. //remove DNSSEC records
  3131. bool foundDnssecRecords = false;
  3132. bool foundOther = false;
  3133. foreach (DnsResourceRecord record in authority)
  3134. {
  3135. switch (record.Type)
  3136. {
  3137. case DnsResourceRecordType.DS:
  3138. case DnsResourceRecordType.DNSKEY:
  3139. case DnsResourceRecordType.RRSIG:
  3140. case DnsResourceRecordType.NSEC:
  3141. case DnsResourceRecordType.NSEC3:
  3142. foundDnssecRecords = true;
  3143. break;
  3144. default:
  3145. foundOther = true;
  3146. break;
  3147. }
  3148. }
  3149. if (foundDnssecRecords)
  3150. {
  3151. if (foundOther)
  3152. {
  3153. List<DnsResourceRecord> newAuthority = new List<DnsResourceRecord>(2);
  3154. foreach (DnsResourceRecord record in authority)
  3155. {
  3156. switch (record.Type)
  3157. {
  3158. case DnsResourceRecordType.DS:
  3159. case DnsResourceRecordType.DNSKEY:
  3160. case DnsResourceRecordType.RRSIG:
  3161. case DnsResourceRecordType.NSEC:
  3162. case DnsResourceRecordType.NSEC3:
  3163. break;
  3164. default:
  3165. newAuthority.Add(record);
  3166. break;
  3167. }
  3168. }
  3169. authority = newAuthority;
  3170. }
  3171. else
  3172. {
  3173. authority = Array.Empty<DnsResourceRecord>();
  3174. }
  3175. }
  3176. }
  3177. //additional section checks
  3178. if (additional.Count > 0)
  3179. {
  3180. if ((response.RCODE != DnsResponseCode.NoError) && (request.EDNS is not null) && (response.EDNS is not null) && ((response.EDNS.Options.Count > 0) || (response.DnsClientExtendedErrors.Count > 0)))
  3181. {
  3182. //only responses with RCODE!=NoError gets cached as a special cache record to preserve EDNS options
  3183. //copy options as new OPT and keep other records
  3184. List<DnsResourceRecord> newAdditional = new List<DnsResourceRecord>(additional.Count);
  3185. foreach (DnsResourceRecord record in additional)
  3186. {
  3187. switch (record.Type)
  3188. {
  3189. case DnsResourceRecordType.OPT:
  3190. continue;
  3191. case DnsResourceRecordType.RRSIG:
  3192. case DnsResourceRecordType.DNSKEY:
  3193. if (dnssecOk)
  3194. break;
  3195. continue;
  3196. }
  3197. newAdditional.Add(record);
  3198. }
  3199. IReadOnlyList<EDnsOption> options;
  3200. if (response.GetEDnsClientSubnetOption(true) is not null)
  3201. {
  3202. //response contains ECS
  3203. if (request.GetEDnsClientSubnetOption(true) is not null)
  3204. {
  3205. //request has ECS and type is supported; keep ECS in response
  3206. options = response.EDNS.Options;
  3207. }
  3208. else
  3209. {
  3210. //cache does not support the qtype so remove ECS from response
  3211. if (response.EDNS.Options.Count == 1)
  3212. {
  3213. options = Array.Empty<EDnsOption>();
  3214. }
  3215. else
  3216. {
  3217. List<EDnsOption> newOptions = new List<EDnsOption>(response.EDNS.Options.Count);
  3218. foreach (EDnsOption option in response.EDNS.Options)
  3219. {
  3220. if (option.Code != EDnsOptionCode.EDNS_CLIENT_SUBNET)
  3221. newOptions.Add(option);
  3222. }
  3223. options = newOptions;
  3224. }
  3225. }
  3226. }
  3227. else
  3228. {
  3229. options = response.EDNS.Options;
  3230. }
  3231. if (response.DnsClientExtendedErrors.Count > 0)
  3232. {
  3233. //add dns client extended errors
  3234. List<EDnsOption> newOptions = new List<EDnsOption>(options.Count + response.DnsClientExtendedErrors.Count);
  3235. newOptions.AddRange(options);
  3236. foreach (EDnsExtendedDnsErrorOptionData ee in response.DnsClientExtendedErrors)
  3237. newOptions.Add(new EDnsOption(EDnsOptionCode.EXTENDED_DNS_ERROR, ee));
  3238. options = newOptions;
  3239. }
  3240. newAdditional.Add(DnsDatagramEdns.GetOPTFor(_udpPayloadSize, response.RCODE, 0, request.DnssecOk ? EDnsHeaderFlags.DNSSEC_OK : EDnsHeaderFlags.None, options));
  3241. additional = newAdditional;
  3242. }
  3243. else if (response.EDNS is not null)
  3244. {
  3245. //remove OPT from additional
  3246. additional = RemoveOPTFromAdditional(additional, dnssecOk);
  3247. }
  3248. }
  3249. {
  3250. bool authenticData = false;
  3251. if (dnssecOk)
  3252. {
  3253. if (answer.Count > 0)
  3254. {
  3255. authenticData = true;
  3256. foreach (DnsResourceRecord record in answer)
  3257. {
  3258. if (record.DnssecStatus != DnssecStatus.Secure)
  3259. {
  3260. authenticData = false;
  3261. break;
  3262. }
  3263. }
  3264. }
  3265. else if (authority.Count > 0)
  3266. {
  3267. authenticData = true;
  3268. foreach (DnsResourceRecord record in authority)
  3269. {
  3270. if (record.DnssecStatus != DnssecStatus.Secure)
  3271. {
  3272. authenticData = false;
  3273. break;
  3274. }
  3275. }
  3276. }
  3277. }
  3278. return new DnsDatagram(request.Identifier, true, DnsOpcode.StandardQuery, false, false, true, true, authenticData, request.CheckingDisabled, response.RCODE, request.Question, answer, authority, additional);
  3279. }
  3280. }
  3281. private static IReadOnlyList<DnsResourceRecord> RemoveOPTFromAdditional(IReadOnlyList<DnsResourceRecord> additional, bool dnssecOk)
  3282. {
  3283. if (additional.Count == 0)
  3284. return additional;
  3285. if ((additional.Count == 1) && (additional[0].Type == DnsResourceRecordType.OPT))
  3286. return Array.Empty<DnsResourceRecord>();
  3287. List<DnsResourceRecord> newAdditional = new List<DnsResourceRecord>(additional.Count - 1);
  3288. foreach (DnsResourceRecord record in additional)
  3289. {
  3290. switch (record.Type)
  3291. {
  3292. case DnsResourceRecordType.OPT:
  3293. continue;
  3294. case DnsResourceRecordType.RRSIG:
  3295. case DnsResourceRecordType.DNSKEY:
  3296. if (dnssecOk)
  3297. break;
  3298. continue;
  3299. }
  3300. newAdditional.Add(record);
  3301. }
  3302. return newAdditional;
  3303. }
  3304. private static string GetResolverQueryKey(DnsQuestionRecord question, NetworkAddress eDnsClientSubnet)
  3305. {
  3306. if (eDnsClientSubnet is null)
  3307. return question.ToString();
  3308. return question.ToString() + " " + eDnsClientSubnet.ToString();
  3309. }
  3310. private DnsDatagram QueryCache(DnsDatagram request, bool serveStale, bool resetExpiry)
  3311. {
  3312. DnsDatagram cacheResponse = _cacheZoneManager.Query(request, serveStale, false, resetExpiry);
  3313. if (cacheResponse is not null)
  3314. {
  3315. if ((cacheResponse.RCODE != DnsResponseCode.NoError) || (cacheResponse.Answer.Count > 0) || (cacheResponse.Authority.Count == 0) || cacheResponse.IsFirstAuthoritySOA())
  3316. {
  3317. cacheResponse.Tag = DnsServerResponseType.Cached;
  3318. return cacheResponse;
  3319. }
  3320. }
  3321. return null;
  3322. }
  3323. private async Task PrefetchCacheAsync(DnsDatagram request, IPEndPoint remoteEP, IReadOnlyList<DnsResourceRecord> conditionalForwarders)
  3324. {
  3325. try
  3326. {
  3327. await RecursiveResolveAsync(request, remoteEP, conditionalForwarders, _dnssecValidation, true, false, false);
  3328. }
  3329. catch (Exception ex)
  3330. {
  3331. _resolverLog?.Write(ex);
  3332. }
  3333. }
  3334. private async Task RefreshCacheAsync(IList<CacheRefreshSample> cacheRefreshSampleList, CacheRefreshSample sample, int sampleQuestionIndex)
  3335. {
  3336. try
  3337. {
  3338. //refresh cache
  3339. DnsDatagram request = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, true, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { sample.SampleQuestion });
  3340. DnsDatagram response = await ProcessRecursiveQueryAsync(request, IPENDPOINT_ANY_0, DnsTransportProtocol.Udp, sample.ConditionalForwarders, _dnssecValidation, true, false);
  3341. bool addBackToSampleList = false;
  3342. DateTime utcNow = DateTime.UtcNow;
  3343. foreach (DnsResourceRecord answer in response.Answer)
  3344. {
  3345. if ((answer.OriginalTtlValue >= _cachePrefetchEligibility) && (utcNow.AddSeconds(answer.TTL) < _cachePrefetchSamplingTimerTriggersOn))
  3346. {
  3347. //answer expires before next sampling so add back to the list to allow refreshing it
  3348. addBackToSampleList = true;
  3349. break;
  3350. }
  3351. }
  3352. if (addBackToSampleList)
  3353. cacheRefreshSampleList[sampleQuestionIndex] = sample; //put back into sample list to allow refreshing it again
  3354. }
  3355. catch (Exception ex)
  3356. {
  3357. _resolverLog?.Write(ex);
  3358. cacheRefreshSampleList[sampleQuestionIndex] = sample; //put back into sample list to allow refreshing it again
  3359. }
  3360. }
  3361. private DnsQuestionRecord GetCacheRefreshNeededQuery(DnsQuestionRecord question, int trigger)
  3362. {
  3363. int queryCount = 0;
  3364. while (true)
  3365. {
  3366. DnsDatagram cacheResponse = QueryCache(new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, true, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { question }), false, false);
  3367. if (cacheResponse is null)
  3368. return question; //cache expired so refresh question
  3369. if (cacheResponse.Answer.Count == 0)
  3370. return null; //dont refresh empty responses
  3371. //inspect response TTL values to decide if refresh is needed
  3372. foreach (DnsResourceRecord answer in cacheResponse.Answer)
  3373. {
  3374. if ((answer.OriginalTtlValue >= _cachePrefetchEligibility) && (answer.TTL <= trigger))
  3375. return question; //TTL eligible and less than trigger so refresh question
  3376. }
  3377. DnsResourceRecord lastRR = cacheResponse.GetLastAnswerRecord();
  3378. if (lastRR.Type == question.Type)
  3379. return null; //answer was resolved
  3380. if (lastRR.Type != DnsResourceRecordType.CNAME)
  3381. return null; //invalid response so ignore question
  3382. queryCount++;
  3383. if (queryCount >= MAX_CNAME_HOPS)
  3384. return null; //too many hops so ignore question
  3385. //follow CNAME chain to inspect TTL further
  3386. question = new DnsQuestionRecord((lastRR.RDATA as DnsCNAMERecordData).Domain, question.Type, question.Class);
  3387. }
  3388. }
  3389. private bool IsCacheRefreshNeeded(DnsQuestionRecord question, int trigger)
  3390. {
  3391. DnsDatagram cacheResponse = QueryCache(new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, true, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { question }), false, false);
  3392. if (cacheResponse is null)
  3393. return true; //cache expired so refresh needed
  3394. if (cacheResponse.Answer.Count == 0)
  3395. return false; //dont refresh empty responses
  3396. //inspect response TTL values to decide if refresh is needed
  3397. foreach (DnsResourceRecord answer in cacheResponse.Answer)
  3398. {
  3399. if ((answer.OriginalTtlValue >= _cachePrefetchEligibility) && (answer.TTL <= trigger))
  3400. return true; //TTL eligible less than trigger so refresh
  3401. }
  3402. return false; //no need to refresh for this query
  3403. }
  3404. private async void CachePrefetchSamplingTimerCallback(object state)
  3405. {
  3406. try
  3407. {
  3408. List<KeyValuePair<DnsQuestionRecord, long>> eligibleQueries = _stats.GetLastHourEligibleQueries(_cachePrefetchSampleEligibilityHitsPerHour);
  3409. List<CacheRefreshSample> cacheRefreshSampleList = new List<CacheRefreshSample>(eligibleQueries.Count);
  3410. int cacheRefreshTrigger = (_cachePrefetchSampleIntervalInMinutes + 1) * 60;
  3411. foreach (KeyValuePair<DnsQuestionRecord, long> eligibleQuery in eligibleQueries)
  3412. {
  3413. DnsQuestionRecord eligibleQuerySample = eligibleQuery.Key;
  3414. if (eligibleQuerySample.Type == DnsResourceRecordType.ANY)
  3415. continue; //dont refresh type ANY queries
  3416. DnsQuestionRecord refreshQuery = null;
  3417. IReadOnlyList<DnsResourceRecord> conditionalForwarders = null;
  3418. //query auth zone for refresh query
  3419. int queryCount = 0;
  3420. bool reQueryAuthZone;
  3421. do
  3422. {
  3423. reQueryAuthZone = false;
  3424. DnsDatagram request = new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, false, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { eligibleQuerySample });
  3425. DnsDatagram response = await AuthoritativeQueryAsync(request, IPENDPOINT_ANY_0, DnsTransportProtocol.Tcp, true, false);
  3426. if (response is null)
  3427. {
  3428. //zone not hosted; do refresh
  3429. refreshQuery = GetCacheRefreshNeededQuery(eligibleQuerySample, cacheRefreshTrigger);
  3430. }
  3431. else
  3432. {
  3433. //zone is hosted; check further
  3434. if (response.Answer.Count > 0)
  3435. {
  3436. DnsResourceRecord lastRR = response.GetLastAnswerRecord();
  3437. if ((lastRR.Type == DnsResourceRecordType.CNAME) && (eligibleQuerySample.Type != DnsResourceRecordType.CNAME))
  3438. {
  3439. eligibleQuerySample = new DnsQuestionRecord((lastRR.RDATA as DnsCNAMERecordData).Domain, eligibleQuerySample.Type, eligibleQuerySample.Class);
  3440. reQueryAuthZone = true;
  3441. }
  3442. }
  3443. else if (response.Authority.Count > 0)
  3444. {
  3445. DnsResourceRecord firstAuthority = response.FindFirstAuthorityRecord();
  3446. switch (firstAuthority.Type)
  3447. {
  3448. case DnsResourceRecordType.NS: //zone is delegated
  3449. refreshQuery = GetCacheRefreshNeededQuery(eligibleQuerySample, cacheRefreshTrigger);
  3450. conditionalForwarders = Array.Empty<DnsResourceRecord>(); //do forced recursive resolution using empty conditional forwarders
  3451. break;
  3452. case DnsResourceRecordType.FWD: //zone is conditional forwarder
  3453. refreshQuery = GetCacheRefreshNeededQuery(eligibleQuerySample, cacheRefreshTrigger);
  3454. conditionalForwarders = response.Authority; //do conditional forwarding
  3455. break;
  3456. }
  3457. }
  3458. }
  3459. }
  3460. while (reQueryAuthZone && (++queryCount < MAX_CNAME_HOPS));
  3461. if (refreshQuery is not null)
  3462. cacheRefreshSampleList.Add(new CacheRefreshSample(refreshQuery, conditionalForwarders));
  3463. }
  3464. _cacheRefreshSampleList = cacheRefreshSampleList;
  3465. }
  3466. catch (Exception ex)
  3467. {
  3468. _log?.Write(ex);
  3469. }
  3470. finally
  3471. {
  3472. lock (_cachePrefetchSamplingTimerLock)
  3473. {
  3474. if (_cachePrefetchSamplingTimer is not null)
  3475. {
  3476. _cachePrefetchSamplingTimer.Change(_cachePrefetchSampleIntervalInMinutes * 60 * 1000, Timeout.Infinite);
  3477. _cachePrefetchSamplingTimerTriggersOn = DateTime.UtcNow.AddMinutes(_cachePrefetchSampleIntervalInMinutes);
  3478. }
  3479. }
  3480. }
  3481. }
  3482. private void CachePrefetchRefreshTimerCallback(object state)
  3483. {
  3484. try
  3485. {
  3486. IList<CacheRefreshSample> cacheRefreshSampleList = _cacheRefreshSampleList;
  3487. if (cacheRefreshSampleList is not null)
  3488. {
  3489. for (int i = 0; i < cacheRefreshSampleList.Count; i++)
  3490. {
  3491. CacheRefreshSample sample = cacheRefreshSampleList[i];
  3492. if (sample is null)
  3493. continue;
  3494. if (!IsCacheRefreshNeeded(sample.SampleQuestion, _cachePrefetchTrigger + 1))
  3495. continue;
  3496. cacheRefreshSampleList[i] = null; //remove from sample list to avoid concurrent refresh attempt
  3497. int sampleQuestionIndex = i;
  3498. _ = Task.Run(delegate () { return RefreshCacheAsync(cacheRefreshSampleList, sample, sampleQuestionIndex); }); //run task in threadpool since its long running
  3499. }
  3500. }
  3501. }
  3502. catch (Exception ex)
  3503. {
  3504. _log?.Write(ex);
  3505. }
  3506. finally
  3507. {
  3508. lock (_cachePrefetchRefreshTimerLock)
  3509. {
  3510. _cachePrefetchRefreshTimer?.Change((_cachePrefetchTrigger + 1) * 1000, Timeout.Infinite);
  3511. }
  3512. }
  3513. }
  3514. private void CacheMaintenanceTimerCallback(object state)
  3515. {
  3516. try
  3517. {
  3518. _cacheZoneManager.RemoveExpiredRecords();
  3519. //force GC collection to remove old cache data from memory quickly
  3520. GC.Collect();
  3521. }
  3522. catch (Exception ex)
  3523. {
  3524. _log?.Write(ex);
  3525. }
  3526. finally
  3527. {
  3528. lock (_cacheMaintenanceTimerLock)
  3529. {
  3530. _cacheMaintenanceTimer?.Change(CACHE_MAINTENANCE_TIMER_PERIODIC_INTERVAL, Timeout.Infinite);
  3531. }
  3532. }
  3533. }
  3534. private void ResetPrefetchTimers()
  3535. {
  3536. if ((_cachePrefetchTrigger == 0) || (_recursion == DnsServerRecursion.Deny))
  3537. {
  3538. lock (_cachePrefetchSamplingTimerLock)
  3539. {
  3540. _cachePrefetchSamplingTimer?.Change(Timeout.Infinite, Timeout.Infinite);
  3541. }
  3542. lock (_cachePrefetchRefreshTimerLock)
  3543. {
  3544. _cachePrefetchRefreshTimer?.Change(Timeout.Infinite, Timeout.Infinite);
  3545. }
  3546. }
  3547. else if (_state == ServiceState.Running)
  3548. {
  3549. lock (_cachePrefetchSamplingTimerLock)
  3550. {
  3551. if (_cachePrefetchSamplingTimer is not null)
  3552. {
  3553. _cachePrefetchSamplingTimer.Change(CACHE_PREFETCH_SAMPLING_TIMER_INITIAL_INTEVAL, Timeout.Infinite);
  3554. _cachePrefetchSamplingTimerTriggersOn = DateTime.UtcNow.AddMilliseconds(CACHE_PREFETCH_SAMPLING_TIMER_INITIAL_INTEVAL);
  3555. }
  3556. }
  3557. lock (_cachePrefetchRefreshTimerLock)
  3558. {
  3559. _cachePrefetchRefreshTimer?.Change(CACHE_PREFETCH_REFRESH_TIMER_INITIAL_INTEVAL, Timeout.Infinite);
  3560. }
  3561. }
  3562. }
  3563. internal bool IsQpmLimitCrossed(IPAddress remoteIP)
  3564. {
  3565. if ((_qpmLimitRequests < 1) && (_qpmLimitErrors < 1))
  3566. return false;
  3567. if (IPAddress.IsLoopback(remoteIP))
  3568. return false;
  3569. if (_qpmLimitBypassList is not null)
  3570. {
  3571. foreach (NetworkAddress networkAddress in _qpmLimitBypassList)
  3572. {
  3573. if (networkAddress.Contains(remoteIP))
  3574. return false;
  3575. }
  3576. }
  3577. IPAddress remoteSubnet;
  3578. switch (remoteIP.AddressFamily)
  3579. {
  3580. case AddressFamily.InterNetwork:
  3581. remoteSubnet = remoteIP.GetNetworkAddress(_qpmLimitIPv4PrefixLength);
  3582. break;
  3583. case AddressFamily.InterNetworkV6:
  3584. remoteSubnet = remoteIP.GetNetworkAddress(_qpmLimitIPv6PrefixLength);
  3585. break;
  3586. default:
  3587. throw new NotSupportedException("AddressFamily not supported.");
  3588. }
  3589. if ((_qpmLimitErrors > 0) && (_qpmLimitErrorClientSubnetStats is not null) && _qpmLimitErrorClientSubnetStats.TryGetValue(remoteSubnet, out long errorCountPerSample))
  3590. {
  3591. long averageErrorCountPerMinute = errorCountPerSample / _qpmLimitSampleMinutes;
  3592. if (averageErrorCountPerMinute >= _qpmLimitErrors)
  3593. return true;
  3594. }
  3595. if ((_qpmLimitRequests > 0) && (_qpmLimitClientSubnetStats is not null) && _qpmLimitClientSubnetStats.TryGetValue(remoteSubnet, out long countPerSample))
  3596. {
  3597. long averageCountPerMinute = countPerSample / _qpmLimitSampleMinutes;
  3598. if (averageCountPerMinute >= _qpmLimitRequests)
  3599. return true;
  3600. }
  3601. return false;
  3602. }
  3603. private void QpmLimitSamplingTimerCallback(object state)
  3604. {
  3605. try
  3606. {
  3607. _stats.GetLatestClientSubnetStats(_qpmLimitSampleMinutes, _qpmLimitIPv4PrefixLength, _qpmLimitIPv6PrefixLength, out IReadOnlyDictionary<IPAddress, long> qpmLimitClientSubnetStats, out IReadOnlyDictionary<IPAddress, long> qpmLimitErrorClientSubnetStats);
  3608. if (_qpmLimitErrors > 0)
  3609. WriteClientSubnetRateLimitLog(_qpmLimitErrorClientSubnetStats, qpmLimitErrorClientSubnetStats, _qpmLimitErrors, "errors");
  3610. if (_qpmLimitRequests > 0)
  3611. WriteClientSubnetRateLimitLog(_qpmLimitClientSubnetStats, qpmLimitClientSubnetStats, _qpmLimitRequests, "requests");
  3612. _qpmLimitClientSubnetStats = qpmLimitClientSubnetStats;
  3613. _qpmLimitErrorClientSubnetStats = qpmLimitErrorClientSubnetStats;
  3614. }
  3615. catch (Exception ex)
  3616. {
  3617. _log?.Write(ex);
  3618. }
  3619. finally
  3620. {
  3621. lock (_qpmLimitSamplingTimerLock)
  3622. {
  3623. _qpmLimitSamplingTimer?.Change(QPM_LIMIT_SAMPLING_TIMER_INTERVAL, Timeout.Infinite);
  3624. }
  3625. }
  3626. }
  3627. private void WriteClientSubnetRateLimitLog(IReadOnlyDictionary<IPAddress, long> oldQpmLimitClientSubnetStats, IReadOnlyDictionary<IPAddress, long> newQpmLimitClientSubnetStats, long qpmLimit, string limitType)
  3628. {
  3629. if (oldQpmLimitClientSubnetStats is not null)
  3630. {
  3631. foreach (KeyValuePair<IPAddress, long> sampleEntry in oldQpmLimitClientSubnetStats)
  3632. {
  3633. long oldAverageCountPerMinute = sampleEntry.Value / _qpmLimitSampleMinutes;
  3634. if (oldAverageCountPerMinute >= qpmLimit)
  3635. {
  3636. //previously over limit
  3637. long averageCountPerMinute = 0;
  3638. if (newQpmLimitClientSubnetStats.TryGetValue(sampleEntry.Key, out long newCountPerSample))
  3639. averageCountPerMinute = newCountPerSample / _qpmLimitSampleMinutes;
  3640. if (averageCountPerMinute < qpmLimit) //currently under limit
  3641. _log?.Write("Client subnet '" + sampleEntry.Key + "/" + (sampleEntry.Key.AddressFamily == AddressFamily.InterNetwork ? _qpmLimitIPv4PrefixLength : _qpmLimitIPv6PrefixLength) + "' is no longer being rate limited (" + averageCountPerMinute + " qpm for " + limitType + ").");
  3642. }
  3643. }
  3644. }
  3645. foreach (KeyValuePair<IPAddress, long> sampleEntry in newQpmLimitClientSubnetStats)
  3646. {
  3647. long averageCountPerMinute = sampleEntry.Value / _qpmLimitSampleMinutes;
  3648. if (averageCountPerMinute >= qpmLimit)
  3649. {
  3650. //currently over limit
  3651. if ((oldQpmLimitClientSubnetStats is not null) && oldQpmLimitClientSubnetStats.TryGetValue(sampleEntry.Key, out long oldCountPerSample))
  3652. {
  3653. long oldAverageCountPerMinute = oldCountPerSample / _qpmLimitSampleMinutes;
  3654. if (oldAverageCountPerMinute >= qpmLimit)
  3655. continue; //previously over limit too
  3656. }
  3657. _log?.Write("Client subnet '" + sampleEntry.Key + "/" + (sampleEntry.Key.AddressFamily == AddressFamily.InterNetwork ? _qpmLimitIPv4PrefixLength : _qpmLimitIPv6PrefixLength) + "' is being rate limited till the query rate limit (" + averageCountPerMinute + " qpm for " + limitType + ") falls below " + qpmLimit + " qpm.");
  3658. }
  3659. }
  3660. }
  3661. private void ResetQpsLimitTimer()
  3662. {
  3663. if ((_qpmLimitRequests < 1) && (_qpmLimitErrors < 1))
  3664. {
  3665. lock (_qpmLimitSamplingTimerLock)
  3666. {
  3667. _qpmLimitSamplingTimer?.Change(Timeout.Infinite, Timeout.Infinite);
  3668. _qpmLimitClientSubnetStats = null;
  3669. _qpmLimitErrorClientSubnetStats = null;
  3670. }
  3671. }
  3672. else if (_state == ServiceState.Running)
  3673. {
  3674. lock (_qpmLimitSamplingTimerLock)
  3675. {
  3676. _qpmLimitSamplingTimer?.Change(0, Timeout.Infinite);
  3677. }
  3678. }
  3679. }
  3680. private void UpdateThisServer()
  3681. {
  3682. if ((_localEndPoints is null) || (_localEndPoints.Count == 0))
  3683. {
  3684. _thisServer = new NameServerAddress(_serverDomain, IPAddress.Loopback);
  3685. }
  3686. else
  3687. {
  3688. foreach (IPEndPoint localEndPoint in _localEndPoints)
  3689. {
  3690. if (localEndPoint.Address.Equals(IPAddress.Any))
  3691. {
  3692. _thisServer = new NameServerAddress(_serverDomain, new IPEndPoint(IPAddress.Loopback, localEndPoint.Port));
  3693. return;
  3694. }
  3695. if (localEndPoint.Address.Equals(IPAddress.IPv6Any))
  3696. {
  3697. _thisServer = new NameServerAddress(_serverDomain, new IPEndPoint(IPAddress.IPv6Loopback, localEndPoint.Port));
  3698. return;
  3699. }
  3700. }
  3701. _thisServer = new NameServerAddress(_serverDomain, _localEndPoints[0]);
  3702. }
  3703. }
  3704. #endregion
  3705. #region doh web service
  3706. private async Task StartDoHAsync()
  3707. {
  3708. IReadOnlyList<IPAddress> localAddresses = GetValidKestralLocalAddresses(_localEndPoints.Convert(delegate (IPEndPoint ep) { return ep.Address; }));
  3709. try
  3710. {
  3711. WebApplicationBuilder builder = WebApplication.CreateBuilder();
  3712. builder.Environment.ContentRootFileProvider = new PhysicalFileProvider(Path.GetDirectoryName(_dohwwwFolder))
  3713. {
  3714. UseActivePolling = true,
  3715. UsePollingFileWatcher = true
  3716. };
  3717. builder.Environment.WebRootFileProvider = new PhysicalFileProvider(_dohwwwFolder)
  3718. {
  3719. UseActivePolling = true,
  3720. UsePollingFileWatcher = true
  3721. };
  3722. builder.WebHost.ConfigureKestrel(delegate (WebHostBuilderContext context, KestrelServerOptions serverOptions)
  3723. {
  3724. //bind to http port
  3725. if (_enableDnsOverHttp)
  3726. {
  3727. foreach (IPAddress localAddress in localAddresses)
  3728. serverOptions.Listen(localAddress, _dnsOverHttpPort);
  3729. }
  3730. //bind to https port
  3731. if (_enableDnsOverHttps && (_certificateCollection is not null))
  3732. {
  3733. foreach (IPAddress localAddress in localAddresses)
  3734. {
  3735. serverOptions.Listen(localAddress, _dnsOverHttpsPort, delegate (ListenOptions listenOptions)
  3736. {
  3737. listenOptions.Protocols = _enableDnsOverHttp3 ? HttpProtocols.Http1AndHttp2AndHttp3 : HttpProtocols.Http1AndHttp2;
  3738. listenOptions.UseHttps(delegate (SslStream stream, SslClientHelloInfo clientHelloInfo, object state, CancellationToken cancellationToken)
  3739. {
  3740. return ValueTask.FromResult(_sslServerAuthenticationOptions);
  3741. }, null);
  3742. });
  3743. }
  3744. }
  3745. serverOptions.AddServerHeader = false;
  3746. serverOptions.Limits.RequestHeadersTimeout = TimeSpan.FromMilliseconds(_tcpReceiveTimeout);
  3747. serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMilliseconds(_tcpReceiveTimeout);
  3748. serverOptions.Limits.MaxRequestHeadersTotalSize = 4096;
  3749. serverOptions.Limits.MaxRequestLineSize = serverOptions.Limits.MaxRequestHeadersTotalSize;
  3750. serverOptions.Limits.MaxRequestBufferSize = serverOptions.Limits.MaxRequestLineSize;
  3751. serverOptions.Limits.MaxRequestBodySize = 64 * 1024;
  3752. serverOptions.Limits.MaxResponseBufferSize = 4096;
  3753. });
  3754. builder.Logging.ClearProviders();
  3755. _dohWebService = builder.Build();
  3756. _dohWebService.UseDefaultFiles();
  3757. _dohWebService.UseStaticFiles(new StaticFileOptions()
  3758. {
  3759. OnPrepareResponse = delegate (StaticFileResponseContext ctx)
  3760. {
  3761. ctx.Context.Response.Headers["X-Robots-Tag"] = "noindex, nofollow";
  3762. ctx.Context.Response.Headers.CacheControl = "private, max-age=300";
  3763. },
  3764. ServeUnknownFileTypes = true
  3765. });
  3766. _dohWebService.UseRouting();
  3767. _dohWebService.MapGet("/dns-query", ProcessDoHRequestAsync);
  3768. _dohWebService.MapPost("/dns-query", ProcessDoHRequestAsync);
  3769. await _dohWebService.StartAsync();
  3770. if (_log is not null)
  3771. {
  3772. foreach (IPAddress localAddress in localAddresses)
  3773. {
  3774. if (_enableDnsOverHttp)
  3775. _log?.Write(new IPEndPoint(localAddress, _dnsOverHttpPort), "Http", "DNS Server was bound successfully.");
  3776. if (_enableDnsOverHttps && (_certificateCollection is not null))
  3777. _log?.Write(new IPEndPoint(localAddress, _dnsOverHttpsPort), "Https", "DNS Server was bound successfully.");
  3778. }
  3779. }
  3780. }
  3781. catch (Exception ex)
  3782. {
  3783. await StopDoHAsync();
  3784. if (_log is not null)
  3785. {
  3786. foreach (IPAddress localAddress in localAddresses)
  3787. {
  3788. if (_enableDnsOverHttp)
  3789. _log?.Write(new IPEndPoint(localAddress, _dnsOverHttpPort), "Http", "DNS Server failed to bind.");
  3790. if (_enableDnsOverHttps && (_certificateCollection is not null))
  3791. _log?.Write(new IPEndPoint(localAddress, _dnsOverHttpsPort), "Https", "DNS Server failed to bind.");
  3792. }
  3793. _log?.Write(ex);
  3794. }
  3795. }
  3796. }
  3797. private async Task StopDoHAsync()
  3798. {
  3799. if (_dohWebService is not null)
  3800. {
  3801. try
  3802. {
  3803. await _dohWebService.DisposeAsync();
  3804. }
  3805. catch (Exception ex)
  3806. {
  3807. _log?.Write(ex);
  3808. }
  3809. _dohWebService = null;
  3810. }
  3811. }
  3812. internal static IReadOnlyList<IPAddress> GetValidKestralLocalAddresses(IReadOnlyList<IPAddress> localAddresses)
  3813. {
  3814. List<IPAddress> supportedLocalAddresses = new List<IPAddress>(localAddresses.Count);
  3815. foreach (IPAddress localAddress in localAddresses)
  3816. {
  3817. switch (localAddress.AddressFamily)
  3818. {
  3819. case AddressFamily.InterNetwork:
  3820. if (Socket.OSSupportsIPv4)
  3821. {
  3822. if (!supportedLocalAddresses.Contains(localAddress))
  3823. supportedLocalAddresses.Add(localAddress);
  3824. }
  3825. break;
  3826. case AddressFamily.InterNetworkV6:
  3827. if (Socket.OSSupportsIPv6)
  3828. {
  3829. if (!supportedLocalAddresses.Contains(localAddress))
  3830. supportedLocalAddresses.Add(localAddress);
  3831. }
  3832. break;
  3833. }
  3834. }
  3835. bool containsUnicastAddress = false;
  3836. foreach (IPAddress localAddress in supportedLocalAddresses)
  3837. {
  3838. if (!localAddress.Equals(IPAddress.Any) && !localAddress.Equals(IPAddress.IPv6Any))
  3839. {
  3840. containsUnicastAddress = true;
  3841. break;
  3842. }
  3843. }
  3844. List<IPAddress> newLocalAddresses = new List<IPAddress>(supportedLocalAddresses.Count);
  3845. if (containsUnicastAddress)
  3846. {
  3847. //replace any with loopback address
  3848. foreach (IPAddress localAddress in supportedLocalAddresses)
  3849. {
  3850. if (localAddress.Equals(IPAddress.Any))
  3851. {
  3852. if (!newLocalAddresses.Contains(IPAddress.Loopback))
  3853. newLocalAddresses.Add(IPAddress.Loopback);
  3854. }
  3855. else if (localAddress.Equals(IPAddress.IPv6Any))
  3856. {
  3857. if (!newLocalAddresses.Contains(IPAddress.IPv6Loopback))
  3858. newLocalAddresses.Add(IPAddress.IPv6Loopback);
  3859. }
  3860. else
  3861. {
  3862. if (!newLocalAddresses.Contains(localAddress))
  3863. newLocalAddresses.Add(localAddress);
  3864. }
  3865. }
  3866. }
  3867. else
  3868. {
  3869. //remove "0.0.0.0" if [::] exists
  3870. foreach (IPAddress localAddress in supportedLocalAddresses)
  3871. {
  3872. if (localAddress.Equals(IPAddress.Any))
  3873. {
  3874. if (!supportedLocalAddresses.Contains(IPAddress.IPv6Any))
  3875. newLocalAddresses.Add(localAddress);
  3876. }
  3877. else
  3878. {
  3879. newLocalAddresses.Add(localAddress);
  3880. }
  3881. }
  3882. }
  3883. return newLocalAddresses;
  3884. }
  3885. #endregion
  3886. #region public
  3887. public async Task StartAsync()
  3888. {
  3889. if (_disposed)
  3890. ObjectDisposedException.ThrowIf(_disposed, this);
  3891. if (_state != ServiceState.Stopped)
  3892. throw new InvalidOperationException("DNS Server is already running.");
  3893. _state = ServiceState.Starting;
  3894. //bind on all local end points
  3895. foreach (IPEndPoint localEP in _localEndPoints)
  3896. {
  3897. Socket udpListener = null;
  3898. try
  3899. {
  3900. udpListener = new Socket(localEP.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
  3901. #region this code ignores ICMP port unreachable responses which creates SocketException in ReceiveFrom()
  3902. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  3903. {
  3904. const uint IOC_IN = 0x80000000;
  3905. const uint IOC_VENDOR = 0x18000000;
  3906. const uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
  3907. udpListener.IOControl((IOControlCode)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
  3908. }
  3909. #endregion
  3910. if (Environment.OSVersion.Platform == PlatformID.Unix)
  3911. udpListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); //to allow binding to same port with different addresses
  3912. udpListener.ReceiveBufferSize = 512 * 1024;
  3913. udpListener.SendBufferSize = 512 * 1024;
  3914. try
  3915. {
  3916. udpListener.Bind(localEP);
  3917. }
  3918. catch (SocketException ex1)
  3919. {
  3920. switch (ex1.ErrorCode)
  3921. {
  3922. case 99: //SocketException (99): Cannot assign requested address
  3923. await Task.Delay(5000); //wait for address to be available before retrying
  3924. udpListener.Bind(localEP);
  3925. break;
  3926. default:
  3927. throw;
  3928. }
  3929. }
  3930. _udpListeners.Add(udpListener);
  3931. _log?.Write(localEP, DnsTransportProtocol.Udp, "DNS Server was bound successfully.");
  3932. }
  3933. catch (Exception ex)
  3934. {
  3935. _log?.Write(localEP, DnsTransportProtocol.Udp, "DNS Server failed to bind.\r\n" + ex.ToString());
  3936. udpListener?.Dispose();
  3937. }
  3938. if (_enableDnsOverUdpProxy)
  3939. {
  3940. IPEndPoint udpProxyEP = new IPEndPoint(localEP.Address, _dnsOverUdpProxyPort);
  3941. Socket udpProxyListener = null;
  3942. try
  3943. {
  3944. udpProxyListener = new Socket(udpProxyEP.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
  3945. #region this code ignores ICMP port unreachable responses which creates SocketException in ReceiveFrom()
  3946. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  3947. {
  3948. const uint IOC_IN = 0x80000000;
  3949. const uint IOC_VENDOR = 0x18000000;
  3950. const uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
  3951. udpProxyListener.IOControl((IOControlCode)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
  3952. }
  3953. #endregion
  3954. udpProxyListener.ReceiveBufferSize = 512 * 1024;
  3955. udpProxyListener.SendBufferSize = 512 * 1024;
  3956. udpProxyListener.Bind(udpProxyEP);
  3957. _udpProxyListeners.Add(udpProxyListener);
  3958. _log?.Write(udpProxyEP, DnsTransportProtocol.UdpProxy, "DNS Server was bound successfully.");
  3959. }
  3960. catch (Exception ex)
  3961. {
  3962. _log?.Write(udpProxyEP, DnsTransportProtocol.UdpProxy, "DNS Server failed to bind.\r\n" + ex.ToString());
  3963. udpProxyListener?.Dispose();
  3964. }
  3965. }
  3966. Socket tcpListener = null;
  3967. try
  3968. {
  3969. tcpListener = new Socket(localEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  3970. tcpListener.Bind(localEP);
  3971. tcpListener.Listen(_listenBacklog);
  3972. _tcpListeners.Add(tcpListener);
  3973. _log?.Write(localEP, DnsTransportProtocol.Tcp, "DNS Server was bound successfully.");
  3974. }
  3975. catch (Exception ex)
  3976. {
  3977. _log?.Write(localEP, DnsTransportProtocol.Tcp, "DNS Server failed to bind.\r\n" + ex.ToString());
  3978. tcpListener?.Dispose();
  3979. }
  3980. if (_enableDnsOverTcpProxy)
  3981. {
  3982. IPEndPoint tcpProxyEP = new IPEndPoint(localEP.Address, _dnsOverTcpProxyPort);
  3983. Socket tcpProxyListner = null;
  3984. try
  3985. {
  3986. tcpProxyListner = new Socket(tcpProxyEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  3987. tcpProxyListner.Bind(tcpProxyEP);
  3988. tcpProxyListner.Listen(_listenBacklog);
  3989. _tcpProxyListeners.Add(tcpProxyListner);
  3990. _log?.Write(tcpProxyEP, DnsTransportProtocol.TcpProxy, "DNS Server was bound successfully.");
  3991. }
  3992. catch (Exception ex)
  3993. {
  3994. _log?.Write(tcpProxyEP, DnsTransportProtocol.TcpProxy, "DNS Server failed to bind.\r\n" + ex.ToString());
  3995. tcpProxyListner?.Dispose();
  3996. }
  3997. }
  3998. if (_enableDnsOverTls && (_certificateCollection is not null))
  3999. {
  4000. IPEndPoint tlsEP = new IPEndPoint(localEP.Address, _dnsOverTlsPort);
  4001. Socket tlsListener = null;
  4002. try
  4003. {
  4004. tlsListener = new Socket(tlsEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  4005. tlsListener.Bind(tlsEP);
  4006. tlsListener.Listen(_listenBacklog);
  4007. _tlsListeners.Add(tlsListener);
  4008. _log?.Write(tlsEP, DnsTransportProtocol.Tls, "DNS Server was bound successfully.");
  4009. }
  4010. catch (Exception ex)
  4011. {
  4012. _log?.Write(tlsEP, DnsTransportProtocol.Tls, "DNS Server failed to bind.\r\n" + ex.ToString());
  4013. tlsListener?.Dispose();
  4014. }
  4015. }
  4016. if (_enableDnsOverQuic && (_certificateCollection is not null))
  4017. {
  4018. IPEndPoint quicEP = new IPEndPoint(localEP.Address, _dnsOverQuicPort);
  4019. QuicListener quicListener = null;
  4020. try
  4021. {
  4022. QuicListenerOptions listenerOptions = new QuicListenerOptions()
  4023. {
  4024. ListenEndPoint = quicEP,
  4025. ListenBacklog = _listenBacklog,
  4026. ApplicationProtocols = quicApplicationProtocols,
  4027. ConnectionOptionsCallback = delegate (QuicConnection quicConnection, SslClientHelloInfo sslClientHello, CancellationToken cancellationToken)
  4028. {
  4029. QuicServerConnectionOptions serverConnectionOptions = new QuicServerConnectionOptions()
  4030. {
  4031. DefaultCloseErrorCode = (long)DnsOverQuicErrorCodes.DOQ_NO_ERROR,
  4032. DefaultStreamErrorCode = (long)DnsOverQuicErrorCodes.DOQ_UNSPECIFIED_ERROR,
  4033. MaxInboundUnidirectionalStreams = 0,
  4034. MaxInboundBidirectionalStreams = _quicMaxInboundStreams,
  4035. IdleTimeout = TimeSpan.FromMilliseconds(_quicIdleTimeout),
  4036. ServerAuthenticationOptions = _quicSslServerAuthenticationOptions
  4037. };
  4038. return ValueTask.FromResult(serverConnectionOptions);
  4039. }
  4040. };
  4041. quicListener = await QuicListener.ListenAsync(listenerOptions);
  4042. _quicListeners.Add(quicListener);
  4043. _log?.Write(quicEP, DnsTransportProtocol.Quic, "DNS Server was bound successfully.");
  4044. }
  4045. catch (Exception ex)
  4046. {
  4047. _log?.Write(quicEP, DnsTransportProtocol.Quic, "DNS Server failed to bind.\r\n" + ex.ToString());
  4048. if (quicListener is not null)
  4049. await quicListener.DisposeAsync();
  4050. }
  4051. }
  4052. }
  4053. //start reading query packets
  4054. int listenerTaskCount = Math.Max(1, Environment.ProcessorCount);
  4055. foreach (Socket udpListener in _udpListeners)
  4056. {
  4057. for (int i = 0; i < listenerTaskCount; i++)
  4058. {
  4059. _ = Task.Factory.StartNew(delegate ()
  4060. {
  4061. return ReadUdpRequestAsync(udpListener, DnsTransportProtocol.Udp);
  4062. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _queryTaskScheduler);
  4063. }
  4064. }
  4065. foreach (Socket udpProxyListener in _udpProxyListeners)
  4066. {
  4067. for (int i = 0; i < listenerTaskCount; i++)
  4068. {
  4069. _ = Task.Factory.StartNew(delegate ()
  4070. {
  4071. return ReadUdpRequestAsync(udpProxyListener, DnsTransportProtocol.UdpProxy);
  4072. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _queryTaskScheduler);
  4073. }
  4074. }
  4075. foreach (Socket tcpListener in _tcpListeners)
  4076. {
  4077. for (int i = 0; i < listenerTaskCount; i++)
  4078. {
  4079. _ = Task.Factory.StartNew(delegate ()
  4080. {
  4081. return AcceptConnectionAsync(tcpListener, DnsTransportProtocol.Tcp);
  4082. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _queryTaskScheduler);
  4083. }
  4084. }
  4085. foreach (Socket tcpProxyListener in _tcpProxyListeners)
  4086. {
  4087. for (int i = 0; i < listenerTaskCount; i++)
  4088. {
  4089. _ = Task.Factory.StartNew(delegate ()
  4090. {
  4091. return AcceptConnectionAsync(tcpProxyListener, DnsTransportProtocol.TcpProxy);
  4092. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _queryTaskScheduler);
  4093. }
  4094. }
  4095. foreach (Socket tlsListener in _tlsListeners)
  4096. {
  4097. for (int i = 0; i < listenerTaskCount; i++)
  4098. {
  4099. _ = Task.Factory.StartNew(delegate ()
  4100. {
  4101. return AcceptConnectionAsync(tlsListener, DnsTransportProtocol.Tls);
  4102. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _queryTaskScheduler);
  4103. }
  4104. }
  4105. foreach (QuicListener quicListener in _quicListeners)
  4106. {
  4107. for (int i = 0; i < listenerTaskCount; i++)
  4108. {
  4109. _ = Task.Factory.StartNew(delegate ()
  4110. {
  4111. return AcceptQuicConnectionAsync(quicListener);
  4112. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _queryTaskScheduler);
  4113. }
  4114. }
  4115. if (_enableDnsOverHttp || (_enableDnsOverHttps && (_certificateCollection is not null)))
  4116. await StartDoHAsync();
  4117. _cachePrefetchSamplingTimer = new Timer(CachePrefetchSamplingTimerCallback, null, Timeout.Infinite, Timeout.Infinite);
  4118. _cachePrefetchRefreshTimer = new Timer(CachePrefetchRefreshTimerCallback, null, Timeout.Infinite, Timeout.Infinite);
  4119. _cacheMaintenanceTimer = new Timer(CacheMaintenanceTimerCallback, null, CACHE_MAINTENANCE_TIMER_INITIAL_INTEVAL, Timeout.Infinite);
  4120. _qpmLimitSamplingTimer = new Timer(QpmLimitSamplingTimerCallback, null, Timeout.Infinite, Timeout.Infinite);
  4121. _state = ServiceState.Running;
  4122. UpdateThisServer();
  4123. ResetPrefetchTimers();
  4124. ResetQpsLimitTimer();
  4125. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  4126. {
  4127. //init udp socket pool async for port randomization
  4128. ThreadPool.QueueUserWorkItem(delegate (object state)
  4129. {
  4130. UdpClientConnection.CreateSocketPool(_preferIPv6);
  4131. });
  4132. }
  4133. }
  4134. public async Task StopAsync()
  4135. {
  4136. if (_state != ServiceState.Running)
  4137. return;
  4138. _state = ServiceState.Stopping;
  4139. lock (_cachePrefetchSamplingTimerLock)
  4140. {
  4141. if (_cachePrefetchSamplingTimer is not null)
  4142. {
  4143. _cachePrefetchSamplingTimer.Dispose();
  4144. _cachePrefetchSamplingTimer = null;
  4145. }
  4146. }
  4147. lock (_cachePrefetchRefreshTimerLock)
  4148. {
  4149. if (_cachePrefetchRefreshTimer is not null)
  4150. {
  4151. _cachePrefetchRefreshTimer.Dispose();
  4152. _cachePrefetchRefreshTimer = null;
  4153. }
  4154. }
  4155. lock (_cacheMaintenanceTimerLock)
  4156. {
  4157. if (_cacheMaintenanceTimer is not null)
  4158. {
  4159. _cacheMaintenanceTimer.Dispose();
  4160. _cacheMaintenanceTimer = null;
  4161. }
  4162. }
  4163. lock (_qpmLimitSamplingTimerLock)
  4164. {
  4165. if (_qpmLimitSamplingTimer is not null)
  4166. {
  4167. _qpmLimitSamplingTimer.Dispose();
  4168. _qpmLimitSamplingTimer = null;
  4169. }
  4170. }
  4171. foreach (Socket udpListener in _udpListeners)
  4172. {
  4173. try
  4174. {
  4175. udpListener.Dispose();
  4176. }
  4177. catch (Exception ex)
  4178. {
  4179. _log?.Write(ex);
  4180. }
  4181. }
  4182. foreach (Socket udpProxyListener in _udpProxyListeners)
  4183. {
  4184. try
  4185. {
  4186. udpProxyListener.Dispose();
  4187. }
  4188. catch (Exception ex)
  4189. {
  4190. _log?.Write(ex);
  4191. }
  4192. }
  4193. foreach (Socket tcpListener in _tcpListeners)
  4194. {
  4195. try
  4196. {
  4197. tcpListener.Dispose();
  4198. }
  4199. catch (Exception ex)
  4200. {
  4201. _log?.Write(ex);
  4202. }
  4203. }
  4204. foreach (Socket tcpProxyListener in _tcpProxyListeners)
  4205. {
  4206. try
  4207. {
  4208. tcpProxyListener.Dispose();
  4209. }
  4210. catch (Exception ex)
  4211. {
  4212. _log?.Write(ex);
  4213. }
  4214. }
  4215. foreach (Socket tlsListener in _tlsListeners)
  4216. {
  4217. try
  4218. {
  4219. tlsListener.Dispose();
  4220. }
  4221. catch (Exception ex)
  4222. {
  4223. _log?.Write(ex);
  4224. }
  4225. }
  4226. foreach (QuicListener quicListener in _quicListeners)
  4227. {
  4228. try
  4229. {
  4230. await quicListener.DisposeAsync();
  4231. }
  4232. catch (Exception ex)
  4233. {
  4234. _log?.Write(ex);
  4235. }
  4236. }
  4237. _udpListeners.Clear();
  4238. _udpProxyListeners.Clear();
  4239. _tcpListeners.Clear();
  4240. _tcpProxyListeners.Clear();
  4241. _tlsListeners.Clear();
  4242. _quicListeners.Clear();
  4243. await StopDoHAsync();
  4244. _state = ServiceState.Stopped;
  4245. }
  4246. public Task<DnsDatagram> DirectQueryAsync(DnsQuestionRecord question, int timeout = 4000, bool skipDnsAppAuthoritativeRequestHandlers = false)
  4247. {
  4248. return DirectQueryAsync(new DnsDatagram(0, false, DnsOpcode.StandardQuery, false, false, true, false, false, false, DnsResponseCode.NoError, new DnsQuestionRecord[] { question }), timeout, skipDnsAppAuthoritativeRequestHandlers);
  4249. }
  4250. public Task<DnsDatagram> DirectQueryAsync(DnsDatagram request, int timeout = 4000, bool skipDnsAppAuthoritativeRequestHandlers = false)
  4251. {
  4252. return TechnitiumLibrary.TaskExtensions.TimeoutAsync(delegate (CancellationToken cancellationToken1)
  4253. {
  4254. return ProcessQueryAsync(request, IPENDPOINT_ANY_0, DnsTransportProtocol.Tcp, true, skipDnsAppAuthoritativeRequestHandlers, null);
  4255. }, timeout);
  4256. }
  4257. Task<DnsDatagram> IDnsClient.ResolveAsync(DnsQuestionRecord question, CancellationToken cancellationToken)
  4258. {
  4259. return DirectQueryAsync(question);
  4260. }
  4261. #endregion
  4262. #region properties
  4263. public string ServerDomain
  4264. {
  4265. get { return _serverDomain; }
  4266. set
  4267. {
  4268. if (!_serverDomain.Equals(value))
  4269. {
  4270. if (DnsClient.IsDomainNameUnicode(value))
  4271. value = DnsClient.ConvertDomainNameToAscii(value);
  4272. DnsClient.IsDomainNameValid(value, true);
  4273. if (IPAddress.TryParse(value, out _))
  4274. throw new DnsServerException("Invalid domain name [" + value + "]: IP address cannot be used for DNS server domain name.");
  4275. _serverDomain = value.ToLowerInvariant();
  4276. _defaultResponsiblePerson = new MailAddress("hostadmin@" + _serverDomain);
  4277. _authZoneManager.UpdateServerDomain();
  4278. _allowedZoneManager.UpdateServerDomain();
  4279. _blockedZoneManager.UpdateServerDomain();
  4280. _blockListZoneManager.UpdateServerDomain();
  4281. UpdateThisServer();
  4282. }
  4283. }
  4284. }
  4285. public string ConfigFolder
  4286. { get { return _configFolder; } }
  4287. public IReadOnlyList<IPEndPoint> LocalEndPoints
  4288. {
  4289. get { return _localEndPoints; }
  4290. set { _localEndPoints = value; }
  4291. }
  4292. public LogManager LogManager
  4293. {
  4294. get { return _log; }
  4295. set { _log = value; }
  4296. }
  4297. internal MailAddress ResponsiblePersonInternal
  4298. {
  4299. get { return _responsiblePerson; }
  4300. set { _responsiblePerson = value; }
  4301. }
  4302. public MailAddress ResponsiblePerson
  4303. {
  4304. get
  4305. {
  4306. if (_responsiblePerson is not null)
  4307. return _responsiblePerson;
  4308. if (_defaultResponsiblePerson is null)
  4309. _defaultResponsiblePerson = new MailAddress("hostadmin@" + _serverDomain);
  4310. return _defaultResponsiblePerson;
  4311. }
  4312. }
  4313. public NameServerAddress ThisServer
  4314. { get { return _thisServer; } }
  4315. public AuthZoneManager AuthZoneManager
  4316. { get { return _authZoneManager; } }
  4317. public AllowedZoneManager AllowedZoneManager
  4318. { get { return _allowedZoneManager; } }
  4319. public BlockedZoneManager BlockedZoneManager
  4320. { get { return _blockedZoneManager; } }
  4321. public BlockListZoneManager BlockListZoneManager
  4322. { get { return _blockListZoneManager; } }
  4323. public CacheZoneManager CacheZoneManager
  4324. { get { return _cacheZoneManager; } }
  4325. public DnsApplicationManager DnsApplicationManager
  4326. { get { return _dnsApplicationManager; } }
  4327. public IDnsCache DnsCache
  4328. { get { return _dnsCache; } }
  4329. public StatsManager StatsManager
  4330. { get { return _stats; } }
  4331. public IReadOnlyCollection<NetworkAddress> ZoneTransferAllowedNetworks
  4332. {
  4333. get { return _zoneTransferAllowedNetworks; }
  4334. set
  4335. {
  4336. if ((value is null) || (value.Count == 0))
  4337. _zoneTransferAllowedNetworks = null;
  4338. else if (value.Count > byte.MaxValue)
  4339. throw new ArgumentOutOfRangeException(nameof(ZoneTransferAllowedNetworks), "Networks cannot have more than 255 entries.");
  4340. else
  4341. _zoneTransferAllowedNetworks = value;
  4342. }
  4343. }
  4344. public IReadOnlyCollection<NetworkAddress> NotifyAllowedNetworks
  4345. {
  4346. get { return _notifyAllowedNetworks; }
  4347. set
  4348. {
  4349. if ((value is null) || (value.Count == 0))
  4350. _notifyAllowedNetworks = null;
  4351. else if (value.Count > byte.MaxValue)
  4352. throw new ArgumentOutOfRangeException(nameof(NotifyAllowedNetworks), "Networks cannot have more than 255 entries.");
  4353. else
  4354. _notifyAllowedNetworks = value;
  4355. }
  4356. }
  4357. public bool PreferIPv6
  4358. {
  4359. get { return _preferIPv6; }
  4360. set
  4361. {
  4362. if (_preferIPv6 != value)
  4363. {
  4364. _preferIPv6 = value;
  4365. //init udp socket pool async for port randomization
  4366. ThreadPool.QueueUserWorkItem(delegate (object state)
  4367. {
  4368. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  4369. UdpClientConnection.CreateSocketPool(_preferIPv6);
  4370. });
  4371. }
  4372. }
  4373. }
  4374. public ushort UdpPayloadSize
  4375. {
  4376. get { return _udpPayloadSize; }
  4377. set
  4378. {
  4379. if ((value < 512) || (value > 4096))
  4380. throw new ArgumentOutOfRangeException(nameof(UdpPayloadSize), "Invalid EDNS UDP payload size: valid range is 512-4096 bytes.");
  4381. _udpPayloadSize = value;
  4382. }
  4383. }
  4384. public bool DnssecValidation
  4385. {
  4386. get { return _dnssecValidation; }
  4387. set
  4388. {
  4389. if (_dnssecValidation != value)
  4390. {
  4391. if (!_dnssecValidation)
  4392. _cacheZoneManager.Flush(); //flush cache to remove non validated data
  4393. _dnssecValidation = value;
  4394. }
  4395. }
  4396. }
  4397. public bool EDnsClientSubnet
  4398. {
  4399. get { return _eDnsClientSubnet; }
  4400. set
  4401. {
  4402. if (_eDnsClientSubnet != value)
  4403. {
  4404. _eDnsClientSubnet = value;
  4405. if (!_eDnsClientSubnet)
  4406. {
  4407. ThreadPool.QueueUserWorkItem(delegate (object state)
  4408. {
  4409. _cacheZoneManager.DeleteEDnsClientSubnetData();
  4410. });
  4411. }
  4412. }
  4413. }
  4414. }
  4415. public byte EDnsClientSubnetIPv4PrefixLength
  4416. {
  4417. get { return _eDnsClientSubnetIPv4PrefixLength; }
  4418. set
  4419. {
  4420. if (value > 32)
  4421. throw new ArgumentOutOfRangeException(nameof(EDnsClientSubnetIPv4PrefixLength), "EDNS Client Subnet IPv4 prefix length cannot be greater than 32.");
  4422. _eDnsClientSubnetIPv4PrefixLength = value;
  4423. }
  4424. }
  4425. public byte EDnsClientSubnetIPv6PrefixLength
  4426. {
  4427. get { return _eDnsClientSubnetIPv6PrefixLength; }
  4428. set
  4429. {
  4430. if (value > 64)
  4431. throw new ArgumentOutOfRangeException(nameof(EDnsClientSubnetIPv6PrefixLength), "EDNS Client Subnet IPv6 prefix length cannot be greater than 64.");
  4432. _eDnsClientSubnetIPv6PrefixLength = value;
  4433. }
  4434. }
  4435. public NetworkAddress EDnsClientSubnetIpv4Override
  4436. {
  4437. get { return _eDnsClientSubnetIpv4Override; }
  4438. set
  4439. {
  4440. if (value is not null)
  4441. {
  4442. if (value.AddressFamily != AddressFamily.InterNetwork)
  4443. throw new ArgumentException("EDNS Client Subnet IPv4 Override must be an IPv4 network address.", nameof(EDnsClientSubnetIpv4Override));
  4444. if (value.IsHostAddress)
  4445. value = new NetworkAddress(value.Address, _eDnsClientSubnetIPv4PrefixLength);
  4446. }
  4447. _eDnsClientSubnetIpv4Override = value;
  4448. }
  4449. }
  4450. public NetworkAddress EDnsClientSubnetIpv6Override
  4451. {
  4452. get { return _eDnsClientSubnetIpv6Override; }
  4453. set
  4454. {
  4455. if (value is not null)
  4456. {
  4457. if (value.AddressFamily != AddressFamily.InterNetworkV6)
  4458. throw new ArgumentException("EDNS Client Subnet IPv6 Override must be an IPv6 network address.", nameof(EDnsClientSubnetIpv6Override));
  4459. if (value.IsHostAddress)
  4460. value = new NetworkAddress(value.Address, _eDnsClientSubnetIPv6PrefixLength);
  4461. }
  4462. _eDnsClientSubnetIpv6Override = value;
  4463. }
  4464. }
  4465. public int QpmLimitRequests
  4466. {
  4467. get { return _qpmLimitRequests; }
  4468. set
  4469. {
  4470. if (value < 0)
  4471. throw new ArgumentOutOfRangeException(nameof(QpmLimitRequests), "Value cannot be less than 0.");
  4472. if (_qpmLimitRequests != value)
  4473. {
  4474. if ((_qpmLimitRequests == 0) || (value == 0))
  4475. {
  4476. _qpmLimitRequests = value;
  4477. ResetQpsLimitTimer();
  4478. }
  4479. else
  4480. {
  4481. _qpmLimitRequests = value;
  4482. }
  4483. }
  4484. }
  4485. }
  4486. public int QpmLimitErrors
  4487. {
  4488. get { return _qpmLimitErrors; }
  4489. set
  4490. {
  4491. if (value < 0)
  4492. throw new ArgumentOutOfRangeException(nameof(QpmLimitErrors), "Value cannot be less than 0.");
  4493. if (_qpmLimitErrors != value)
  4494. {
  4495. if ((_qpmLimitErrors == 0) || (value == 0))
  4496. {
  4497. _qpmLimitErrors = value;
  4498. ResetQpsLimitTimer();
  4499. }
  4500. else
  4501. {
  4502. _qpmLimitErrors = value;
  4503. }
  4504. }
  4505. }
  4506. }
  4507. public int QpmLimitSampleMinutes
  4508. {
  4509. get { return _qpmLimitSampleMinutes; }
  4510. set
  4511. {
  4512. if ((value < 1) || (value > 60))
  4513. throw new ArgumentOutOfRangeException(nameof(QpmLimitSampleMinutes), "Valid range is between 1 and 60 minutes.");
  4514. _qpmLimitSampleMinutes = value;
  4515. }
  4516. }
  4517. public int QpmLimitIPv4PrefixLength
  4518. {
  4519. get { return _qpmLimitIPv4PrefixLength; }
  4520. set
  4521. {
  4522. if ((value < 0) || (value > 32))
  4523. throw new ArgumentOutOfRangeException(nameof(QpmLimitIPv4PrefixLength), "Valid range is between 0 and 32.");
  4524. _qpmLimitIPv4PrefixLength = value;
  4525. }
  4526. }
  4527. public int QpmLimitIPv6PrefixLength
  4528. {
  4529. get { return _qpmLimitIPv6PrefixLength; }
  4530. set
  4531. {
  4532. if ((value < 0) || (value > 64))
  4533. throw new ArgumentOutOfRangeException(nameof(QpmLimitIPv6PrefixLength), "Valid range is between 0 and 64.");
  4534. _qpmLimitIPv6PrefixLength = value;
  4535. }
  4536. }
  4537. public IReadOnlyCollection<NetworkAddress> QpmLimitBypassList
  4538. {
  4539. get { return _qpmLimitBypassList; }
  4540. set
  4541. {
  4542. if ((value is null) || (value.Count == 0))
  4543. _qpmLimitBypassList = null;
  4544. else if (value.Count > byte.MaxValue)
  4545. throw new ArgumentOutOfRangeException(nameof(QpmLimitBypassList), "Networks cannot have more than 255 entries.");
  4546. else
  4547. _qpmLimitBypassList = value;
  4548. }
  4549. }
  4550. public int ClientTimeout
  4551. {
  4552. get { return _clientTimeout; }
  4553. set
  4554. {
  4555. if ((value < 1000) || (value > 10000))
  4556. throw new ArgumentOutOfRangeException(nameof(ClientTimeout), "Valid range is from 1000 to 10000.");
  4557. _clientTimeout = value;
  4558. }
  4559. }
  4560. public int TcpSendTimeout
  4561. {
  4562. get { return _tcpSendTimeout; }
  4563. set
  4564. {
  4565. if ((value < 1000) || (value > 90000))
  4566. throw new ArgumentOutOfRangeException(nameof(TcpSendTimeout), "Valid range is from 1000 to 90000.");
  4567. _tcpSendTimeout = value;
  4568. }
  4569. }
  4570. public int TcpReceiveTimeout
  4571. {
  4572. get { return _tcpReceiveTimeout; }
  4573. set
  4574. {
  4575. if ((value < 1000) || (value > 90000))
  4576. throw new ArgumentOutOfRangeException(nameof(TcpReceiveTimeout), "Valid range is from 1000 to 90000.");
  4577. _tcpReceiveTimeout = value;
  4578. }
  4579. }
  4580. public int QuicIdleTimeout
  4581. {
  4582. get { return _quicIdleTimeout; }
  4583. set
  4584. {
  4585. if ((value < 1000) || (value > 90000))
  4586. throw new ArgumentOutOfRangeException(nameof(QuicIdleTimeout), "Valid range is from 1000 to 90000.");
  4587. _quicIdleTimeout = value;
  4588. }
  4589. }
  4590. public int QuicMaxInboundStreams
  4591. {
  4592. get { return _quicMaxInboundStreams; }
  4593. set
  4594. {
  4595. if ((value < 0) || (value > 1000))
  4596. throw new ArgumentOutOfRangeException(nameof(QuicMaxInboundStreams), "Valid range is from 1 to 1000.");
  4597. _quicMaxInboundStreams = value;
  4598. }
  4599. }
  4600. public int ListenBacklog
  4601. {
  4602. get { return _listenBacklog; }
  4603. set { _listenBacklog = value; }
  4604. }
  4605. public bool EnableDnsOverUdpProxy
  4606. {
  4607. get { return _enableDnsOverUdpProxy; }
  4608. set { _enableDnsOverUdpProxy = value; }
  4609. }
  4610. public bool EnableDnsOverTcpProxy
  4611. {
  4612. get { return _enableDnsOverTcpProxy; }
  4613. set { _enableDnsOverTcpProxy = value; }
  4614. }
  4615. public bool EnableDnsOverHttp
  4616. {
  4617. get { return _enableDnsOverHttp; }
  4618. set { _enableDnsOverHttp = value; }
  4619. }
  4620. public bool EnableDnsOverTls
  4621. {
  4622. get { return _enableDnsOverTls; }
  4623. set { _enableDnsOverTls = value; }
  4624. }
  4625. public bool EnableDnsOverHttps
  4626. {
  4627. get { return _enableDnsOverHttps; }
  4628. set { _enableDnsOverHttps = value; }
  4629. }
  4630. public bool EnableDnsOverHttp3
  4631. {
  4632. get { return _enableDnsOverHttp3; }
  4633. set { _enableDnsOverHttp3 = value; }
  4634. }
  4635. public bool EnableDnsOverQuic
  4636. {
  4637. get { return _enableDnsOverQuic; }
  4638. set { _enableDnsOverQuic = value; }
  4639. }
  4640. public int DnsOverUdpProxyPort
  4641. {
  4642. get { return _dnsOverUdpProxyPort; }
  4643. set
  4644. {
  4645. if ((value < ushort.MinValue) || (value > ushort.MaxValue))
  4646. throw new ArgumentOutOfRangeException(nameof(DnsOverUdpProxyPort), "Port number valid range is from 0 to 65535.");
  4647. _dnsOverUdpProxyPort = value;
  4648. }
  4649. }
  4650. public int DnsOverTcpProxyPort
  4651. {
  4652. get { return _dnsOverTcpProxyPort; }
  4653. set
  4654. {
  4655. if ((value < ushort.MinValue) || (value > ushort.MaxValue))
  4656. throw new ArgumentOutOfRangeException(nameof(DnsOverTcpProxyPort), "Port number valid range is from 0 to 65535.");
  4657. _dnsOverTcpProxyPort = value;
  4658. }
  4659. }
  4660. public int DnsOverHttpPort
  4661. {
  4662. get { return _dnsOverHttpPort; }
  4663. set
  4664. {
  4665. if ((value < ushort.MinValue) || (value > ushort.MaxValue))
  4666. throw new ArgumentOutOfRangeException(nameof(DnsOverHttpPort), "Port number valid range is from 0 to 65535.");
  4667. _dnsOverHttpPort = value;
  4668. }
  4669. }
  4670. public int DnsOverTlsPort
  4671. {
  4672. get { return _dnsOverTlsPort; }
  4673. set
  4674. {
  4675. if ((value < ushort.MinValue) || (value > ushort.MaxValue))
  4676. throw new ArgumentOutOfRangeException(nameof(DnsOverTlsPort), "Port number valid range is from 0 to 65535.");
  4677. _dnsOverTlsPort = value;
  4678. }
  4679. }
  4680. public int DnsOverHttpsPort
  4681. {
  4682. get { return _dnsOverHttpsPort; }
  4683. set
  4684. {
  4685. if ((value < ushort.MinValue) || (value > ushort.MaxValue))
  4686. throw new ArgumentOutOfRangeException(nameof(DnsOverHttpsPort), "Port number valid range is from 0 to 65535.");
  4687. _dnsOverHttpsPort = value;
  4688. }
  4689. }
  4690. public int DnsOverQuicPort
  4691. {
  4692. get { return _dnsOverQuicPort; }
  4693. set
  4694. {
  4695. if ((value < ushort.MinValue) || (value > ushort.MaxValue))
  4696. throw new ArgumentOutOfRangeException(nameof(DnsOverQuicPort), "Port number valid range is from 0 to 65535.");
  4697. _dnsOverQuicPort = value;
  4698. }
  4699. }
  4700. public X509Certificate2Collection CertificateCollection
  4701. {
  4702. get { return _certificateCollection; }
  4703. set
  4704. {
  4705. if (value is null)
  4706. {
  4707. _certificateCollection = null;
  4708. _sslServerAuthenticationOptions = null;
  4709. _quicSslServerAuthenticationOptions = null;
  4710. }
  4711. else
  4712. {
  4713. X509Certificate2 serverCertificate = null;
  4714. foreach (X509Certificate2 certificate in value)
  4715. {
  4716. if (certificate.HasPrivateKey)
  4717. {
  4718. serverCertificate = certificate;
  4719. break;
  4720. }
  4721. }
  4722. if (serverCertificate is null)
  4723. throw new ArgumentException("DNS Server TLS certificate file must contain a certificate with private key.");
  4724. _certificateCollection = value;
  4725. SslStreamCertificateContext certificateContext = SslStreamCertificateContext.Create(serverCertificate, _certificateCollection, false);
  4726. _sslServerAuthenticationOptions = new SslServerAuthenticationOptions()
  4727. {
  4728. ServerCertificateContext = certificateContext
  4729. };
  4730. _quicSslServerAuthenticationOptions = new SslServerAuthenticationOptions()
  4731. {
  4732. ApplicationProtocols = quicApplicationProtocols,
  4733. ServerCertificateContext = certificateContext
  4734. };
  4735. }
  4736. }
  4737. }
  4738. public string DnsOverHttpRealIpHeader
  4739. {
  4740. get { return _dnsOverHttpRealIpHeader; }
  4741. set
  4742. {
  4743. if (string.IsNullOrEmpty(value))
  4744. _dnsOverHttpRealIpHeader = "X-Real-IP";
  4745. else if (value.Length > 255)
  4746. throw new ArgumentException("DNS-over-HTTP Real IP header name cannot exceed 255 characters.", nameof(DnsOverHttpRealIpHeader));
  4747. else if (value.Contains(' '))
  4748. throw new ArgumentException("DNS-over-HTTP Real IP header name cannot contain invalid characters.", nameof(DnsOverHttpRealIpHeader));
  4749. else
  4750. _dnsOverHttpRealIpHeader = value;
  4751. }
  4752. }
  4753. public IReadOnlyDictionary<string, TsigKey> TsigKeys
  4754. {
  4755. get { return _tsigKeys; }
  4756. set
  4757. {
  4758. if ((value is null) || (value.Count == 0))
  4759. _tsigKeys = null;
  4760. else if (value.Count > byte.MaxValue)
  4761. throw new ArgumentOutOfRangeException(nameof(TsigKeys), "TSIG keys cannot have more than 255 entries.");
  4762. else
  4763. _tsigKeys = value;
  4764. }
  4765. }
  4766. public DnsServerRecursion Recursion
  4767. {
  4768. get { return _recursion; }
  4769. set
  4770. {
  4771. if (_recursion != value)
  4772. {
  4773. if ((_recursion == DnsServerRecursion.Deny) || (value == DnsServerRecursion.Deny))
  4774. {
  4775. _recursion = value;
  4776. ResetPrefetchTimers();
  4777. }
  4778. else
  4779. {
  4780. _recursion = value;
  4781. }
  4782. }
  4783. }
  4784. }
  4785. public IReadOnlyCollection<NetworkAccessControl> RecursionNetworkACL
  4786. {
  4787. get { return _recursionNetworkACL; }
  4788. set
  4789. {
  4790. if ((value is null) || (value.Count == 0))
  4791. _recursionNetworkACL = null;
  4792. else if (value.Count > byte.MaxValue)
  4793. throw new ArgumentOutOfRangeException(nameof(RecursionNetworkACL), "Network Access Control List cannot have more than 255 entries.");
  4794. else
  4795. _recursionNetworkACL = value;
  4796. }
  4797. }
  4798. public bool RandomizeName
  4799. {
  4800. get { return _randomizeName; }
  4801. set { _randomizeName = value; }
  4802. }
  4803. public bool QnameMinimization
  4804. {
  4805. get { return _qnameMinimization; }
  4806. set { _qnameMinimization = value; }
  4807. }
  4808. public bool NsRevalidation
  4809. {
  4810. get { return _nsRevalidation; }
  4811. set { _nsRevalidation = value; }
  4812. }
  4813. public int ResolverRetries
  4814. {
  4815. get { return _resolverRetries; }
  4816. set
  4817. {
  4818. if ((value < 1) || (value > 10))
  4819. throw new ArgumentOutOfRangeException(nameof(ResolverRetries), "Valid range is from 1 to 10.");
  4820. _resolverRetries = value;
  4821. }
  4822. }
  4823. public int ResolverTimeout
  4824. {
  4825. get { return _resolverTimeout; }
  4826. set
  4827. {
  4828. if ((value < 1000) || (value > 10000))
  4829. throw new ArgumentOutOfRangeException(nameof(ResolverTimeout), "Valid range is from 1000 to 10000.");
  4830. _resolverTimeout = value;
  4831. }
  4832. }
  4833. public int ResolverConcurrency
  4834. {
  4835. get { return _resolverConcurrency; }
  4836. set
  4837. {
  4838. if ((value < 1) || (value > 4))
  4839. throw new ArgumentOutOfRangeException(nameof(ResolverConcurrency), "Valid range is from 1 to 4.");
  4840. _resolverConcurrency = value;
  4841. }
  4842. }
  4843. public int ResolverMaxStackCount
  4844. {
  4845. get { return _resolverMaxStackCount; }
  4846. set
  4847. {
  4848. if ((value < 10) || (value > 30))
  4849. throw new ArgumentOutOfRangeException(nameof(ResolverMaxStackCount), "Valid range is from 10 to 30.");
  4850. _resolverMaxStackCount = value;
  4851. }
  4852. }
  4853. public bool ServeStale
  4854. {
  4855. get { return _serveStale; }
  4856. set { _serveStale = value; }
  4857. }
  4858. public int ServeStaleMaxWaitTime
  4859. {
  4860. get { return _serveStaleMaxWaitTime; }
  4861. set
  4862. {
  4863. if ((value < 0) || (value > 1800))
  4864. throw new ArgumentOutOfRangeException(nameof(ServeStaleMaxWaitTime), "Serve stale max wait time valid range is 0 to 1800 milliseconds. Default value is 1800 milliseconds.");
  4865. _serveStaleMaxWaitTime = value;
  4866. }
  4867. }
  4868. public int CachePrefetchEligibility
  4869. {
  4870. get { return _cachePrefetchEligibility; }
  4871. set
  4872. {
  4873. if (value < 2)
  4874. throw new ArgumentOutOfRangeException(nameof(CachePrefetchEligibility), "Valid value is greater that or equal to 2.");
  4875. _cachePrefetchEligibility = value;
  4876. }
  4877. }
  4878. public int CachePrefetchTrigger
  4879. {
  4880. get { return _cachePrefetchTrigger; }
  4881. set
  4882. {
  4883. if (value < 0)
  4884. throw new ArgumentOutOfRangeException(nameof(CachePrefetchTrigger), "Valid value is greater that or equal to 0.");
  4885. if (_cachePrefetchTrigger != value)
  4886. {
  4887. if ((_cachePrefetchTrigger == 0) || (value == 0))
  4888. {
  4889. _cachePrefetchTrigger = value;
  4890. ResetPrefetchTimers();
  4891. }
  4892. else
  4893. {
  4894. _cachePrefetchTrigger = value;
  4895. }
  4896. }
  4897. }
  4898. }
  4899. public int CachePrefetchSampleIntervalInMinutes
  4900. {
  4901. get { return _cachePrefetchSampleIntervalInMinutes; }
  4902. set
  4903. {
  4904. if ((value < 1) || (value > 60))
  4905. throw new ArgumentOutOfRangeException(nameof(CachePrefetchSampleIntervalInMinutes), "Valid range is between 1 and 60 minutes.");
  4906. _cachePrefetchSampleIntervalInMinutes = value;
  4907. }
  4908. }
  4909. public int CachePrefetchSampleEligibilityHitsPerHour
  4910. {
  4911. get { return _cachePrefetchSampleEligibilityHitsPerHour; }
  4912. set
  4913. {
  4914. if (value < 1)
  4915. throw new ArgumentOutOfRangeException(nameof(CachePrefetchSampleEligibilityHitsPerHour), "Valid value is greater than or equal to 1.");
  4916. _cachePrefetchSampleEligibilityHitsPerHour = value;
  4917. }
  4918. }
  4919. public bool EnableBlocking
  4920. {
  4921. get { return _enableBlocking; }
  4922. set { _enableBlocking = value; }
  4923. }
  4924. public bool AllowTxtBlockingReport
  4925. {
  4926. get { return _allowTxtBlockingReport; }
  4927. set { _allowTxtBlockingReport = value; }
  4928. }
  4929. public IReadOnlyCollection<NetworkAddress> BlockingBypassList
  4930. {
  4931. get { return _blockingBypassList; }
  4932. set
  4933. {
  4934. if ((value is null) || (value.Count == 0))
  4935. _blockingBypassList = null;
  4936. else if (value.Count > byte.MaxValue)
  4937. throw new ArgumentOutOfRangeException(nameof(BlockingBypassList), "Networks cannot have more than 255 entries.");
  4938. else
  4939. _blockingBypassList = value;
  4940. }
  4941. }
  4942. public DnsServerBlockingType BlockingType
  4943. {
  4944. get { return _blockingType; }
  4945. set { _blockingType = value; }
  4946. }
  4947. public uint BlockingAnswerTtl
  4948. {
  4949. get { return _blockingAnswerTtl; }
  4950. set
  4951. {
  4952. if (_blockingAnswerTtl != value)
  4953. {
  4954. _blockingAnswerTtl = value;
  4955. //update SOA MINIMUM values
  4956. _blockedZoneManager.UpdateServerDomain();
  4957. _blockListZoneManager.UpdateServerDomain();
  4958. }
  4959. }
  4960. }
  4961. public IReadOnlyCollection<DnsARecordData> CustomBlockingARecords
  4962. {
  4963. get { return _customBlockingARecords; }
  4964. set
  4965. {
  4966. if (value is null)
  4967. value = Array.Empty<DnsARecordData>();
  4968. _customBlockingARecords = value;
  4969. }
  4970. }
  4971. public IReadOnlyCollection<DnsAAAARecordData> CustomBlockingAAAARecords
  4972. {
  4973. get { return _customBlockingAAAARecords; }
  4974. set
  4975. {
  4976. if (value is null)
  4977. value = Array.Empty<DnsAAAARecordData>();
  4978. _customBlockingAAAARecords = value;
  4979. }
  4980. }
  4981. public NetProxy Proxy
  4982. {
  4983. get { return _proxy; }
  4984. set { _proxy = value; }
  4985. }
  4986. public IReadOnlyList<NameServerAddress> Forwarders
  4987. {
  4988. get { return _forwarders; }
  4989. set { _forwarders = value; }
  4990. }
  4991. public bool ConcurrentForwarding
  4992. {
  4993. get { return _concurrentForwarding; }
  4994. set { _concurrentForwarding = value; }
  4995. }
  4996. public int ForwarderRetries
  4997. {
  4998. get { return _forwarderRetries; }
  4999. set
  5000. {
  5001. if ((value < 1) || (value > 10))
  5002. throw new ArgumentOutOfRangeException(nameof(ForwarderRetries), "Valid range is from 1 to 10.");
  5003. _forwarderRetries = value;
  5004. }
  5005. }
  5006. public int ForwarderTimeout
  5007. {
  5008. get { return _forwarderTimeout; }
  5009. set
  5010. {
  5011. if ((value < 1000) || (value > 10000))
  5012. throw new ArgumentOutOfRangeException(nameof(ForwarderTimeout), "Valid range is from 1000 to 10000.");
  5013. _forwarderTimeout = value;
  5014. }
  5015. }
  5016. public int ForwarderConcurrency
  5017. {
  5018. get { return _forwarderConcurrency; }
  5019. set
  5020. {
  5021. if ((value < 1) || (value > 10))
  5022. throw new ArgumentOutOfRangeException(nameof(ForwarderConcurrency), "Valid range is from 1 to 10.");
  5023. _forwarderConcurrency = value;
  5024. }
  5025. }
  5026. public LogManager ResolverLogManager
  5027. {
  5028. get { return _resolverLog; }
  5029. set { _resolverLog = value; }
  5030. }
  5031. public LogManager QueryLogManager
  5032. {
  5033. get { return _queryLog; }
  5034. set { _queryLog = value; }
  5035. }
  5036. #endregion
  5037. class CacheRefreshSample
  5038. {
  5039. public CacheRefreshSample(DnsQuestionRecord sampleQuestion, IReadOnlyList<DnsResourceRecord> conditionalForwarders)
  5040. {
  5041. SampleQuestion = sampleQuestion;
  5042. ConditionalForwarders = conditionalForwarders;
  5043. }
  5044. public DnsQuestionRecord SampleQuestion { get; }
  5045. public IReadOnlyList<DnsResourceRecord> ConditionalForwarders { get; }
  5046. }
  5047. class RecursiveResolveResponse
  5048. {
  5049. public RecursiveResolveResponse(DnsDatagram response, DnsDatagram checkingDisabledResponse)
  5050. {
  5051. Response = response;
  5052. CheckingDisabledResponse = checkingDisabledResponse;
  5053. }
  5054. public DnsDatagram Response { get; }
  5055. public DnsDatagram CheckingDisabledResponse { get; }
  5056. }
  5057. }
  5058. #pragma warning restore CA2252 // This API requires opting into preview features
  5059. #pragma warning restore CA1416 // Validate platform compatibility
  5060. }