12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649 |
- /*
- Technitium DNS Server
- Copyright (C) 2022 Shreyas Zare (shreyas@technitium.com)
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
- using DnsServerCore.Dhcp;
- using DnsServerCore.Dns;
- using DnsServerCore.Dns.ResourceRecords;
- using DnsServerCore.Dns.ZoneManagers;
- using DnsServerCore.Dns.Zones;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Converters;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.IO;
- using System.IO.Compression;
- using System.Net;
- using System.Net.Http;
- using System.Net.Security;
- using System.Net.Sockets;
- using System.Reflection;
- using System.Security.Cryptography;
- using System.Security.Cryptography.X509Certificates;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using TechnitiumLibrary;
- using TechnitiumLibrary.IO;
- using TechnitiumLibrary.Net;
- using TechnitiumLibrary.Net.Dns;
- using TechnitiumLibrary.Net.Dns.ResourceRecords;
- using TechnitiumLibrary.Net.Http;
- using TechnitiumLibrary.Net.Proxy;
- namespace DnsServerCore
- {
- public sealed class DnsWebService : IDisposable
- {
- #region enum
- enum ServiceState
- {
- Stopped = 0,
- Starting = 1,
- Running = 2,
- Stopping = 3
- }
- #endregion
- #region variables
- readonly static RandomNumberGenerator _rng = RandomNumberGenerator.Create();
- readonly WebServiceDashboardApi _dashboardApi;
- readonly WebServiceZonesApi _zonesApi;
- readonly WebServiceOtherZonesApi _otherZonesApi;
- readonly WebServiceAppsApi _appsApi;
- readonly WebServiceDhcpApi _dhcpApi;
- readonly WebServiceLogsApi _logsApi;
- readonly Version _currentVersion;
- readonly string _appFolder;
- readonly string _configFolder;
- readonly Uri _updateCheckUri;
- readonly LogManager _log;
- DnsServer _dnsServer;
- DhcpServer _dhcpServer;
- IReadOnlyList<IPAddress> _webServiceLocalAddresses = new IPAddress[] { IPAddress.Any, IPAddress.IPv6Any };
- int _webServiceHttpPort = 5380;
- int _webServiceTlsPort = 53443;
- bool _webServiceEnableTls;
- bool _webServiceHttpToTlsRedirect;
- bool _webServiceUseSelfSignedTlsCertificate;
- string _webServiceTlsCertificatePath;
- string _webServiceTlsCertificatePassword;
- DateTime _webServiceTlsCertificateLastModifiedOn;
- HttpListener _webService;
- IReadOnlyList<Socket> _webServiceTlsListeners;
- X509Certificate2 _webServiceTlsCertificate;
- readonly IndependentTaskScheduler _webServiceTaskScheduler = new IndependentTaskScheduler(ThreadPriority.AboveNormal);
- string _webServiceHostname;
- IPEndPoint _webServiceHttpEP;
- string _dnsTlsCertificatePath;
- string _dnsTlsCertificatePassword;
- DateTime _dnsTlsCertificateLastModifiedOn;
- Timer _tlsCertificateUpdateTimer;
- const int TLS_CERTIFICATE_UPDATE_TIMER_INITIAL_INTERVAL = 60000;
- const int TLS_CERTIFICATE_UPDATE_TIMER_INTERVAL = 60000;
- const int MAX_LOGIN_ATTEMPTS = 5;
- const int BLOCK_ADDRESS_INTERVAL = 5 * 60 * 1000;
- readonly ConcurrentDictionary<IPAddress, int> _failedLoginAttempts = new ConcurrentDictionary<IPAddress, int>();
- readonly ConcurrentDictionary<IPAddress, DateTime> _blockedAddresses = new ConcurrentDictionary<IPAddress, DateTime>();
- readonly ConcurrentDictionary<string, string> _credentials = new ConcurrentDictionary<string, string>();
- readonly ConcurrentDictionary<string, UserSession> _sessions = new ConcurrentDictionary<string, UserSession>();
- volatile ServiceState _state = ServiceState.Stopped;
- Timer _blockListUpdateTimer;
- DateTime _blockListLastUpdatedOn;
- int _blockListUpdateIntervalHours = 24;
- const int BLOCK_LIST_UPDATE_TIMER_INITIAL_INTERVAL = 5000;
- const int BLOCK_LIST_UPDATE_TIMER_PERIODIC_INTERVAL = 900000;
- Timer _temporaryDisableBlockingTimer;
- DateTime _temporaryDisableBlockingTill;
- List<string> _configDisabledZones;
- #endregion
- #region constructor
- public DnsWebService(string configFolder = null, Uri updateCheckUri = null, Uri appStoreUri = null)
- {
- _dashboardApi = new WebServiceDashboardApi(this);
- _zonesApi = new WebServiceZonesApi(this);
- _otherZonesApi = new WebServiceOtherZonesApi(this);
- _appsApi = new WebServiceAppsApi(this, appStoreUri);
- _dhcpApi = new WebServiceDhcpApi(this);
- _logsApi = new WebServiceLogsApi(this);
- Assembly assembly = Assembly.GetExecutingAssembly();
- AssemblyName assemblyName = assembly.GetName();
- _currentVersion = assemblyName.Version;
- _appFolder = Path.GetDirectoryName(assembly.Location);
- if (configFolder == null)
- _configFolder = Path.Combine(_appFolder, "config");
- else
- _configFolder = configFolder;
- if (!Directory.Exists(_configFolder))
- Directory.CreateDirectory(_configFolder);
- _updateCheckUri = updateCheckUri;
- _log = new LogManager(_configFolder);
- string blockListsFolder = Path.Combine(_configFolder, "blocklists");
- if (!Directory.Exists(blockListsFolder))
- Directory.CreateDirectory(blockListsFolder);
- }
- #endregion
- #region IDisposable
- bool _disposed;
- public void Dispose()
- {
- if (_disposed)
- return;
- Stop();
- if (_webService != null)
- _webService.Close();
- if (_dnsServer != null)
- _dnsServer.Dispose();
- if (_dhcpServer != null)
- _dhcpServer.Dispose();
- if (_log != null)
- _log.Dispose();
- _disposed = true;
- }
- #endregion
- #region private
- #region web service
- private async Task AcceptWebRequestAsync()
- {
- try
- {
- while (true)
- {
- HttpListenerContext context = await _webService.GetContextAsync();
- if ((_webServiceTlsListeners != null) && (_webServiceTlsListeners.Count > 0) && _webServiceHttpToTlsRedirect)
- {
- IPEndPoint remoteEP = context.Request.RemoteEndPoint;
- if ((remoteEP != null) && !IPAddress.IsLoopback(remoteEP.Address))
- {
- string domain = _webServiceTlsCertificate.GetNameInfo(X509NameType.DnsName, false);
- string redirectUri = "https://" + domain + ":" + _webServiceTlsPort + context.Request.Url.PathAndQuery;
- context.Response.Redirect(redirectUri);
- context.Response.Close();
- continue;
- }
- }
- _ = ProcessRequestAsync(context.Request, context.Response);
- }
- }
- catch (HttpListenerException ex)
- {
- if (ex.ErrorCode == 995)
- return; //web service stopping
- _log.Write(ex);
- }
- catch (ObjectDisposedException)
- {
- //web service stopped
- }
- catch (Exception ex)
- {
- if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
- return; //web service stopping
- _log.Write(ex);
- }
- }
- private async Task AcceptTlsWebRequestAsync(Socket tlsListener)
- {
- try
- {
- while (true)
- {
- Socket socket = await tlsListener.AcceptAsync();
- _ = TlsToHttpTunnelAsync(socket);
- }
- }
- catch (SocketException ex)
- {
- if (ex.SocketErrorCode == SocketError.OperationAborted)
- return; //web service stopping
- _log.Write(ex);
- }
- catch (ObjectDisposedException)
- {
- //web service stopped
- }
- catch (Exception ex)
- {
- if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
- return; //web service stopping
- _log.Write(ex);
- }
- }
- private async Task TlsToHttpTunnelAsync(Socket socket)
- {
- Socket tunnel = null;
- try
- {
- if (_webServiceLocalAddresses.Count < 1)
- return;
- string remoteIP = (socket.RemoteEndPoint as IPEndPoint).Address.ToString();
- SslStream sslStream = new SslStream(new NetworkStream(socket, true));
- await sslStream.AuthenticateAsServerAsync(_webServiceTlsCertificate);
- tunnel = new Socket(_webServiceHttpEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- tunnel.Connect(_webServiceHttpEP);
- NetworkStream tunnelStream = new NetworkStream(tunnel, true);
- //copy tunnel to ssl
- _ = tunnelStream.CopyToAsync(sslStream).ContinueWith(delegate (Task prevTask) { sslStream.Dispose(); tunnelStream.Dispose(); });
- //copy ssl to tunnel
- try
- {
- while (true)
- {
- HttpRequest httpRequest = await HttpRequest.ReadRequestAsync(sslStream);
- if (httpRequest == null)
- return; //connection closed gracefully by client
- //inject X-Real-IP & host header
- httpRequest.Headers.Add("X-Real-IP", remoteIP);
- httpRequest.Headers[HttpRequestHeader.Host] = "localhost:" + _webServiceHttpPort.ToString();
- //relay request
- await tunnelStream.WriteAsync(Encoding.ASCII.GetBytes(httpRequest.HttpMethod + " " + httpRequest.RequestPathAndQuery + " " + httpRequest.Protocol + "\r\n"));
- await tunnelStream.WriteAsync(httpRequest.Headers.ToByteArray());
- if (httpRequest.InputStream != null)
- await httpRequest.InputStream.CopyToAsync(tunnelStream);
- await tunnelStream.FlushAsync();
- }
- }
- finally
- {
- sslStream.Dispose();
- tunnelStream.Dispose();
- }
- }
- catch (IOException)
- {
- //ignore
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- finally
- {
- socket.Dispose();
- if (tunnel != null)
- tunnel.Dispose();
- }
- }
- private async Task ProcessRequestAsync(HttpListenerRequest request, HttpListenerResponse response)
- {
- response.AddHeader("Server", "");
- response.AddHeader("X-Robots-Tag", "noindex, nofollow");
- try
- {
- Uri url = request.Url;
- string path = url.AbsolutePath;
- if (!path.StartsWith("/") || path.Contains("/../") || path.Contains("/.../"))
- {
- await SendErrorAsync(response, 404);
- return;
- }
- if (path.StartsWith("/api/"))
- {
- using (MemoryStream mS = new MemoryStream())
- {
- try
- {
- JsonTextWriter jsonWriter = new JsonTextWriter(new StreamWriter(mS));
- jsonWriter.WriteStartObject();
- switch (path)
- {
- case "/api/login":
- await LoginAsync(request, jsonWriter);
- break;
- case "/api/logout":
- Logout(request);
- break;
- default:
- if (!IsSessionValid(request))
- throw new InvalidTokenWebServiceException("Invalid token or session expired.");
- jsonWriter.WritePropertyName("response");
- jsonWriter.WriteStartObject();
- try
- {
- switch (path)
- {
- case "/api/changePassword":
- ChangePassword(request);
- break;
- case "/api/checkForUpdate":
- await CheckForUpdateAsync(request, jsonWriter);
- break;
- case "/api/getDnsSettings":
- GetDnsSettings(jsonWriter);
- break;
- case "/api/setDnsSettings":
- SetDnsSettings(request, jsonWriter);
- break;
- case "/api/forceUpdateBlockLists":
- ForceUpdateBlockLists(request);
- break;
- case "/api/temporaryDisableBlocking":
- TemporaryDisableBlocking(request, jsonWriter);
- break;
- case "/api/backupSettings":
- await BackupSettingsAsync(request, response);
- return;
- case "/api/restoreSettings":
- await RestoreSettingsAsync(request, jsonWriter);
- break;
- case "/api/getStats":
- await _dashboardApi.GetStats(request, jsonWriter);
- break;
- case "/api/getTopStats":
- await _dashboardApi.GetTopStats(request, jsonWriter);
- break;
- case "/api/flushDnsCache":
- _otherZonesApi.FlushCache(request);
- break;
- case "/api/listCachedZones":
- _otherZonesApi.ListCachedZones(request, jsonWriter);
- break;
- case "/api/deleteCachedZone":
- _otherZonesApi.DeleteCachedZone(request);
- break;
- case "/api/listAllowedZones":
- _otherZonesApi.ListAllowedZones(request, jsonWriter);
- break;
- case "/api/importAllowedZones":
- _otherZonesApi.ImportAllowedZones(request);
- break;
- case "/api/exportAllowedZones":
- _otherZonesApi.ExportAllowedZones(response);
- return;
- case "/api/deleteAllowedZone":
- _otherZonesApi.DeleteAllowedZone(request);
- break;
- case "/api/flushAllowedZone":
- _otherZonesApi.FlushAllowedZone(request);
- break;
- case "/api/allowZone":
- _otherZonesApi.AllowZone(request);
- break;
- case "/api/listBlockedZones":
- _otherZonesApi.ListBlockedZones(request, jsonWriter);
- break;
- case "/api/importBlockedZones":
- _otherZonesApi.ImportBlockedZones(request);
- break;
- case "/api/exportBlockedZones":
- _otherZonesApi.ExportBlockedZones(response);
- return;
- case "/api/deleteBlockedZone":
- _otherZonesApi.DeleteBlockedZone(request);
- break;
- case "/api/flushBlockedZone":
- _otherZonesApi.FlushBlockedZone(request);
- break;
- case "/api/blockZone":
- _otherZonesApi.BlockZone(request);
- break;
- case "/api/zone/list":
- case "/api/listZones":
- _zonesApi.ListZones(jsonWriter);
- break;
- case "/api/zone/create":
- case "/api/createZone":
- await _zonesApi.CreateZoneAsync(request, jsonWriter);
- break;
- case "/api/zone/dnssec/sign":
- _zonesApi.SignPrimaryZone(request);
- break;
- case "/api/zone/dnssec/unsign":
- _zonesApi.UnsignPrimaryZone(request);
- break;
- case "/api/zone/dnssec/getProperties":
- _zonesApi.GetPrimaryZoneDnssecProperties(request, jsonWriter);
- break;
- case "/api/zone/dnssec/convertToNSEC":
- _zonesApi.ConvertPrimaryZoneToNSEC(request);
- break;
- case "/api/zone/dnssec/convertToNSEC3":
- _zonesApi.ConvertPrimaryZoneToNSEC3(request);
- break;
- case "/api/zone/dnssec/updateNSEC3Params":
- _zonesApi.UpdatePrimaryZoneNSEC3Parameters(request);
- break;
- case "/api/zone/dnssec/updateDnsKeyTtl":
- _zonesApi.UpdatePrimaryZoneDnssecDnsKeyTtl(request);
- break;
- case "/api/zone/dnssec/generatePrivateKey":
- _zonesApi.GenerateAndAddPrimaryZoneDnssecPrivateKey(request);
- break;
- case "/api/zone/dnssec/updatePrivateKey":
- _zonesApi.UpdatePrimaryZoneDnssecPrivateKey(request);
- break;
- case "/api/zone/dnssec/deletePrivateKey":
- _zonesApi.DeletePrimaryZoneDnssecPrivateKey(request);
- break;
- case "/api/zone/dnssec/publishAllPrivateKeys":
- _zonesApi.PublishAllGeneratedPrimaryZoneDnssecPrivateKeys(request);
- break;
- case "/api/zone/dnssec/rolloverDnsKey":
- _zonesApi.RolloverPrimaryZoneDnsKey(request);
- break;
- case "/api/zone/dnssec/retireDnsKey":
- _zonesApi.RetirePrimaryZoneDnsKey(request);
- break;
- case "/api/zone/delete":
- case "/api/deleteZone":
- _zonesApi.DeleteZone(request);
- break;
- case "/api/zone/enable":
- case "/api/enableZone":
- _zonesApi.EnableZone(request);
- break;
- case "/api/zone/disable":
- case "/api/disableZone":
- _zonesApi.DisableZone(request);
- break;
- case "/api/zone/options/get":
- _zonesApi.GetZoneOptions(request, jsonWriter);
- break;
- case "/api/zone/options/set":
- _zonesApi.SetZoneOptions(request);
- break;
- case "/api/zone/resync":
- _zonesApi.ResyncZone(request);
- break;
- case "/api/zone/addRecord":
- case "/api/addRecord":
- _zonesApi.AddRecord(request);
- break;
- case "/api/zone/getRecords":
- case "/api/getRecords":
- _zonesApi.GetRecords(request, jsonWriter);
- break;
- case "/api/zone/deleteRecord":
- case "/api/deleteRecord":
- _zonesApi.DeleteRecord(request);
- break;
- case "/api/zone/updateRecord":
- case "/api/updateRecord":
- _zonesApi.UpdateRecord(request);
- break;
- case "/api/apps/list":
- await _appsApi.ListInstalledAppsAsync(jsonWriter);
- break;
- case "/api/apps/listStoreApps":
- await _appsApi.ListStoreApps(jsonWriter);
- break;
- case "/api/apps/downloadAndInstall":
- await _appsApi.DownloadAndInstallAppAsync(request);
- break;
- case "/api/apps/downloadAndUpdate":
- await _appsApi.DownloadAndUpdateAppAsync(request);
- break;
- case "/api/apps/install":
- await _appsApi.InstallAppAsync(request);
- break;
- case "/api/apps/update":
- await _appsApi.UpdateAppAsync(request);
- break;
- case "/api/apps/uninstall":
- _appsApi.UninstallApp(request);
- break;
- case "/api/apps/getConfig":
- await _appsApi.GetAppConfigAsync(request, jsonWriter);
- break;
- case "/api/apps/setConfig":
- await _appsApi.SetAppConfigAsync(request);
- break;
- case "/api/resolveQuery":
- await ResolveQuery(request, jsonWriter);
- break;
- case "/api/listLogs":
- _logsApi.ListLogs(jsonWriter);
- break;
- case "/api/deleteLog":
- _logsApi.DeleteLog(request);
- break;
- case "/api/deleteAllLogs":
- _logsApi.DeleteAllLogs(request);
- break;
- case "/api/deleteAllStats":
- _logsApi.DeleteAllStats(request);
- break;
- case "/api/queryLogs":
- await _logsApi.QueryLogsAsync(request, jsonWriter);
- break;
- case "/api/listDhcpScopes":
- _dhcpApi.ListDhcpScopes(jsonWriter);
- break;
- case "/api/listDhcpLeases":
- _dhcpApi.ListDhcpLeases(jsonWriter);
- break;
- case "/api/getDhcpScope":
- _dhcpApi.GetDhcpScope(request, jsonWriter);
- break;
- case "/api/setDhcpScope":
- await _dhcpApi.SetDhcpScopeAsync(request);
- break;
- case "/api/enableDhcpScope":
- await _dhcpApi.EnableDhcpScopeAsync(request);
- break;
- case "/api/disableDhcpScope":
- _dhcpApi.DisableDhcpScope(request);
- break;
- case "/api/deleteDhcpScope":
- _dhcpApi.DeleteDhcpScope(request);
- break;
- case "/api/removeDhcpLease":
- _dhcpApi.RemoveDhcpLease(request);
- break;
- case "/api/convertToReservedLease":
- _dhcpApi.ConvertToReservedLease(request);
- break;
- case "/api/convertToDynamicLease":
- _dhcpApi.ConvertToDynamicLease(request);
- break;
- default:
- await SendErrorAsync(response, 404);
- return;
- }
- }
- finally
- {
- jsonWriter.WriteEndObject();
- }
- break;
- }
- jsonWriter.WritePropertyName("status");
- jsonWriter.WriteValue("ok");
- jsonWriter.WriteEndObject();
- jsonWriter.Flush();
- }
- catch (InvalidTokenWebServiceException ex)
- {
- mS.SetLength(0);
- JsonTextWriter jsonWriter = new JsonTextWriter(new StreamWriter(mS));
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("status");
- jsonWriter.WriteValue("invalid-token");
- jsonWriter.WritePropertyName("errorMessage");
- jsonWriter.WriteValue(ex.Message);
- jsonWriter.WriteEndObject();
- jsonWriter.Flush();
- }
- catch (Exception ex)
- {
- _log.Write(GetRequestRemoteEndPoint(request), ex);
- mS.SetLength(0);
- JsonTextWriter jsonWriter = new JsonTextWriter(new StreamWriter(mS));
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("status");
- jsonWriter.WriteValue("error");
- jsonWriter.WritePropertyName("errorMessage");
- jsonWriter.WriteValue(ex.Message);
- jsonWriter.WritePropertyName("stackTrace");
- jsonWriter.WriteValue(ex.StackTrace);
- if (ex.InnerException != null)
- {
- jsonWriter.WritePropertyName("innerErrorMessage");
- jsonWriter.WriteValue(ex.InnerException.Message);
- }
- jsonWriter.WriteEndObject();
- jsonWriter.Flush();
- }
- response.ContentType = "application/json; charset=utf-8";
- response.ContentEncoding = Encoding.UTF8;
- response.ContentLength64 = mS.Length;
- mS.Position = 0;
- using (Stream stream = response.OutputStream)
- {
- await mS.CopyToAsync(stream);
- }
- }
- }
- else if (path.StartsWith("/log/"))
- {
- if (!IsSessionValid(request))
- {
- await SendErrorAsync(response, 403, "Invalid token or session expired.");
- return;
- }
- string[] pathParts = path.Split('/');
- string logFileName = pathParts[2];
- int limit = 0;
- string strLimit = request.QueryString["limit"];
- if (!string.IsNullOrEmpty(strLimit))
- limit = int.Parse(strLimit);
- await _log.DownloadLogAsync(request, response, logFileName, limit * 1024 * 1024);
- }
- else
- {
- if (path == "/")
- {
- path = "/index.html";
- }
- else if ((path == "/blocklist.txt") && !IPAddress.IsLoopback(GetRequestRemoteEndPoint(request).Address))
- {
- await SendErrorAsync(response, 403);
- return;
- }
- string wwwroot = Path.Combine(_appFolder, "www");
- path = Path.GetFullPath(wwwroot + path.Replace('/', Path.DirectorySeparatorChar));
- if (!path.StartsWith(wwwroot) || !File.Exists(path))
- {
- await SendErrorAsync(response, 404);
- return;
- }
- await SendFileAsync(request, response, path);
- }
- }
- catch (Exception ex)
- {
- if ((_state == ServiceState.Stopping) || (_state == ServiceState.Stopped))
- return; //web service stopping
- _log.Write(GetRequestRemoteEndPoint(request), ex);
- await SendError(response, ex);
- }
- }
- internal static IPEndPoint GetRequestRemoteEndPoint(HttpListenerRequest request)
- {
- try
- {
- if (request.RemoteEndPoint == null)
- return new IPEndPoint(IPAddress.Any, 0);
- if (NetUtilities.IsPrivateIP(request.RemoteEndPoint.Address))
- {
- string xRealIp = request.Headers["X-Real-IP"];
- if (IPAddress.TryParse(xRealIp, out IPAddress address))
- {
- //get the real IP address of the requesting client from X-Real-IP header set in nginx proxy_pass block
- return new IPEndPoint(address, 0);
- }
- }
- return request.RemoteEndPoint;
- }
- catch
- {
- return new IPEndPoint(IPAddress.Any, 0);
- }
- }
- public static Stream GetOutputStream(HttpListenerRequest request, HttpListenerResponse response)
- {
- string strAcceptEncoding = request.Headers["Accept-Encoding"];
- if (string.IsNullOrEmpty(strAcceptEncoding))
- {
- return response.OutputStream;
- }
- else
- {
- if (strAcceptEncoding.Contains("gzip"))
- {
- response.AddHeader("Content-Encoding", "gzip");
- return new GZipStream(response.OutputStream, CompressionMode.Compress);
- }
- else if (strAcceptEncoding.Contains("deflate"))
- {
- response.AddHeader("Content-Encoding", "deflate");
- return new DeflateStream(response.OutputStream, CompressionMode.Compress);
- }
- else
- {
- return response.OutputStream;
- }
- }
- }
- private static Task SendError(HttpListenerResponse response, Exception ex)
- {
- return SendErrorAsync(response, 500, ex.ToString());
- }
- private static async Task SendErrorAsync(HttpListenerResponse response, int statusCode, string message = null)
- {
- try
- {
- string statusString = statusCode + " " + DnsServer.GetHttpStatusString((HttpStatusCode)statusCode);
- byte[] buffer = Encoding.UTF8.GetBytes("<html><head><title>" + statusString + "</title></head><body><h1>" + statusString + "</h1>" + (message == null ? "" : "<p>" + message + "</p>") + "</body></html>");
- response.StatusCode = statusCode;
- response.ContentType = "text/html";
- response.ContentLength64 = buffer.Length;
- using (Stream stream = response.OutputStream)
- {
- await stream.WriteAsync(buffer);
- }
- }
- catch
- { }
- }
- private static async Task SendFileAsync(HttpListenerRequest request, HttpListenerResponse response, string filePath)
- {
- using (FileStream fS = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
- {
- response.ContentType = WebUtilities.GetContentType(filePath).MediaType;
- response.AddHeader("Cache-Control", "private, max-age=300");
- using (Stream stream = GetOutputStream(request, response))
- {
- try
- {
- await fS.CopyToAsync(stream);
- }
- catch (HttpListenerException)
- {
- //ignore this error
- }
- }
- }
- }
- #endregion
- #region user session
- private string CreateSession(string username)
- {
- string token = BinaryNumber.GenerateRandomNumber256().ToString();
- if (!_sessions.TryAdd(token, new UserSession(username)))
- throw new DnsWebServiceException("Error while creating session. Please try again.");
- return token;
- }
- private UserSession GetSession(string token)
- {
- if (_sessions.TryGetValue(token, out UserSession session))
- return session;
- return null;
- }
- internal UserSession GetSession(HttpListenerRequest request)
- {
- string strToken = request.QueryString["token"];
- if (string.IsNullOrEmpty(strToken))
- throw new DnsWebServiceException("Parameter 'token' missing.");
- return GetSession(strToken);
- }
- private UserSession DeleteSession(string token)
- {
- if (_sessions.TryRemove(token, out UserSession session))
- return session;
- return null;
- }
- private UserSession DeleteSession(HttpListenerRequest request)
- {
- string strToken = request.QueryString["token"];
- if (string.IsNullOrEmpty(strToken))
- throw new DnsWebServiceException("Parameter 'token' missing.");
- return DeleteSession(strToken);
- }
- private void FailedLoginAttempt(IPAddress address)
- {
- _failedLoginAttempts.AddOrUpdate(address, 1, delegate (IPAddress key, int attempts)
- {
- return attempts + 1;
- });
- }
- private bool LoginAttemptsExceedLimit(IPAddress address, int limit)
- {
- if (!_failedLoginAttempts.TryGetValue(address, out int attempts))
- return false;
- return attempts >= limit;
- }
- private void ResetFailedLoginAttempt(IPAddress address)
- {
- _failedLoginAttempts.TryRemove(address, out _);
- }
- private void BlockAddress(IPAddress address, int interval)
- {
- _blockedAddresses.TryAdd(address, DateTime.UtcNow.AddMilliseconds(interval));
- }
- private bool IsAddressBlocked(IPAddress address)
- {
- if (!_blockedAddresses.TryGetValue(address, out DateTime expiry))
- return false;
- if (expiry > DateTime.UtcNow)
- {
- return true;
- }
- else
- {
- UnblockAddress(address);
- ResetFailedLoginAttempt(address);
- return false;
- }
- }
- private void UnblockAddress(IPAddress address)
- {
- _blockedAddresses.TryRemove(address, out _);
- }
- #endregion
- #region auth api
- private async Task LoginAsync(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string strUsername = request.QueryString["user"];
- if (string.IsNullOrEmpty(strUsername))
- throw new DnsWebServiceException("Parameter 'user' missing.");
- string strPassword = request.QueryString["pass"];
- if (string.IsNullOrEmpty(strPassword))
- throw new DnsWebServiceException("Parameter 'pass' missing.");
- IPEndPoint remoteEP = GetRequestRemoteEndPoint(request);
- if (IsAddressBlocked(remoteEP.Address))
- throw new DnsWebServiceException("Max limit of " + MAX_LOGIN_ATTEMPTS + " attempts exceeded. Access blocked for " + (BLOCK_ADDRESS_INTERVAL / 1000) + " seconds.");
- strUsername = strUsername.Trim().ToLower();
- string strPasswordHash = GetPasswordHash(strUsername, strPassword);
- if (!_credentials.TryGetValue(strUsername, out string passwordHash) || (passwordHash != strPasswordHash))
- {
- if (strPassword != "admin") //exception for default password
- {
- FailedLoginAttempt(remoteEP.Address);
- if (LoginAttemptsExceedLimit(remoteEP.Address, MAX_LOGIN_ATTEMPTS))
- BlockAddress(remoteEP.Address, BLOCK_ADDRESS_INTERVAL);
- await Task.Delay(1000);
- }
- throw new DnsWebServiceException("Invalid username or password for user: " + strUsername);
- }
- ResetFailedLoginAttempt(remoteEP.Address);
- _log.Write(remoteEP, "[" + strUsername + "] User logged in.");
- string token = CreateSession(strUsername);
- jsonWriter.WritePropertyName("token");
- jsonWriter.WriteValue(token);
- }
- private bool IsSessionValid(HttpListenerRequest request)
- {
- UserSession session = GetSession(request);
- if (session == null)
- return false;
- if (session.HasExpired())
- {
- DeleteSession(request);
- return false;
- }
- session.UpdateLastSeen();
- return true;
- }
- private void ChangePassword(HttpListenerRequest request)
- {
- string strToken = request.QueryString["token"];
- if (string.IsNullOrEmpty(strToken))
- throw new DnsWebServiceException("Parameter 'token' missing.");
- string strPassword = request.QueryString["pass"];
- if (string.IsNullOrEmpty(strPassword))
- throw new DnsWebServiceException("Parameter 'pass' missing.");
- UserSession session = GetSession(strToken);
- if (session == null)
- throw new DnsWebServiceException("User session does not exists.");
- SetCredentials(session.Username, strPassword);
- SaveConfigFile();
- _log.Write(GetRequestRemoteEndPoint(request), "[" + session.Username + "] Password was changed for user.");
- }
- private void Logout(HttpListenerRequest request)
- {
- string strToken = request.QueryString["token"];
- if (string.IsNullOrEmpty(strToken))
- throw new DnsWebServiceException("Parameter 'token' missing.");
- UserSession session = DeleteSession(strToken);
- if (session != null)
- _log.Write(GetRequestRemoteEndPoint(request), "[" + session.Username + "] User logged out.");
- }
- #endregion
- #region update api
- private async Task CheckForUpdateAsync(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- if (_updateCheckUri is null)
- {
- jsonWriter.WritePropertyName("updateAvailable");
- jsonWriter.WriteValue(false);
- return;
- }
- try
- {
- SocketsHttpHandler handler = new SocketsHttpHandler();
- handler.Proxy = _dnsServer.Proxy;
- using (HttpClient http = new HttpClient(handler))
- {
- string response = await http.GetStringAsync(_updateCheckUri);
- dynamic jsonResponse = JsonConvert.DeserializeObject(response);
- string updateVersion = jsonResponse.updateVersion.Value;
- string updateTitle = jsonResponse.updateTitle?.Value;
- string updateMessage = jsonResponse.updateMessage?.Value;
- string downloadLink = jsonResponse.downloadLink?.Value;
- string instructionsLink = jsonResponse.instructionsLink?.Value;
- string changeLogLink = jsonResponse.changeLogLink?.Value;
- bool updateAvailable = new Version(updateVersion) > _currentVersion;
- jsonWriter.WritePropertyName("updateAvailable");
- jsonWriter.WriteValue(updateAvailable);
- jsonWriter.WritePropertyName("updateVersion");
- jsonWriter.WriteValue(updateVersion);
- jsonWriter.WritePropertyName("currentVersion");
- jsonWriter.WriteValue(GetCleanVersion(_currentVersion));
- if (updateAvailable)
- {
- jsonWriter.WritePropertyName("updateTitle");
- jsonWriter.WriteValue(updateTitle);
- jsonWriter.WritePropertyName("updateMessage");
- jsonWriter.WriteValue(updateMessage);
- jsonWriter.WritePropertyName("downloadLink");
- jsonWriter.WriteValue(downloadLink);
- jsonWriter.WritePropertyName("instructionsLink");
- jsonWriter.WriteValue(instructionsLink);
- jsonWriter.WritePropertyName("changeLogLink");
- jsonWriter.WriteValue(changeLogLink);
- }
- string strLog = "Check for update was done {updateAvailable: " + updateAvailable + "; updateVersion: " + updateVersion + ";";
- if (!string.IsNullOrEmpty(updateTitle))
- strLog += " updateTitle: " + updateTitle + ";";
- if (!string.IsNullOrEmpty(updateMessage))
- strLog += " updateMessage: " + updateMessage + ";";
- if (!string.IsNullOrEmpty(downloadLink))
- strLog += " downloadLink: " + downloadLink + ";";
- if (!string.IsNullOrEmpty(instructionsLink))
- strLog += " instructionsLink: " + instructionsLink + ";";
- if (!string.IsNullOrEmpty(changeLogLink))
- strLog += " changeLogLink: " + changeLogLink + ";";
- strLog += "}";
- _log.Write(GetRequestRemoteEndPoint(request), strLog);
- }
- }
- catch (Exception ex)
- {
- _log.Write(GetRequestRemoteEndPoint(request), "Check for update was done {updateAvailable: False;}\r\n" + ex.ToString());
- jsonWriter.WritePropertyName("updateAvailable");
- jsonWriter.WriteValue(false);
- }
- }
- internal static string GetCleanVersion(Version version)
- {
- string strVersion = version.Major + "." + version.Minor;
- if (version.Build > 0)
- strVersion += "." + version.Build;
- if (version.Revision > 0)
- strVersion += "." + version.Revision;
- return strVersion;
- }
- #endregion
- #region settings api
- private void GetDnsSettings(JsonTextWriter jsonWriter)
- {
- jsonWriter.WritePropertyName("version");
- jsonWriter.WriteValue(GetCleanVersion(_currentVersion));
- jsonWriter.WritePropertyName("dnsServerDomain");
- jsonWriter.WriteValue(_dnsServer.ServerDomain);
- jsonWriter.WritePropertyName("dnsServerLocalEndPoints");
- jsonWriter.WriteStartArray();
- foreach (IPEndPoint localEP in _dnsServer.LocalEndPoints)
- jsonWriter.WriteValue(localEP.ToString());
- jsonWriter.WriteEndArray();
- jsonWriter.WritePropertyName("webServiceLocalAddresses");
- jsonWriter.WriteStartArray();
- foreach (IPAddress localAddress in _webServiceLocalAddresses)
- {
- if (localAddress.AddressFamily == AddressFamily.InterNetworkV6)
- jsonWriter.WriteValue("[" + localAddress.ToString() + "]");
- else
- jsonWriter.WriteValue(localAddress.ToString());
- }
- jsonWriter.WriteEndArray();
- jsonWriter.WritePropertyName("webServiceHttpPort");
- jsonWriter.WriteValue(_webServiceHttpPort);
- jsonWriter.WritePropertyName("webServiceEnableTls");
- jsonWriter.WriteValue(_webServiceEnableTls);
- jsonWriter.WritePropertyName("webServiceHttpToTlsRedirect");
- jsonWriter.WriteValue(_webServiceHttpToTlsRedirect);
- jsonWriter.WritePropertyName("webServiceTlsPort");
- jsonWriter.WriteValue(_webServiceTlsPort);
- jsonWriter.WritePropertyName("webServiceUseSelfSignedTlsCertificate");
- jsonWriter.WriteValue(_webServiceUseSelfSignedTlsCertificate);
- jsonWriter.WritePropertyName("webServiceTlsCertificatePath");
- jsonWriter.WriteValue(_webServiceTlsCertificatePath);
- jsonWriter.WritePropertyName("webServiceTlsCertificatePassword");
- jsonWriter.WriteValue("************");
- jsonWriter.WritePropertyName("enableDnsOverHttp");
- jsonWriter.WriteValue(_dnsServer.EnableDnsOverHttp);
- jsonWriter.WritePropertyName("enableDnsOverTls");
- jsonWriter.WriteValue(_dnsServer.EnableDnsOverTls);
- jsonWriter.WritePropertyName("enableDnsOverHttps");
- jsonWriter.WriteValue(_dnsServer.EnableDnsOverHttps);
- jsonWriter.WritePropertyName("dnsTlsCertificatePath");
- jsonWriter.WriteValue(_dnsTlsCertificatePath);
- jsonWriter.WritePropertyName("dnsTlsCertificatePassword");
- jsonWriter.WriteValue("************");
- jsonWriter.WritePropertyName("tsigKeys");
- {
- jsonWriter.WriteStartArray();
- if (_dnsServer.TsigKeys is not null)
- {
- foreach (KeyValuePair<string, TsigKey> tsigKey in _dnsServer.TsigKeys)
- {
- jsonWriter.WriteStartObject();
- jsonWriter.WritePropertyName("keyName");
- jsonWriter.WriteValue(tsigKey.Key);
- jsonWriter.WritePropertyName("sharedSecret");
- jsonWriter.WriteValue(tsigKey.Value.SharedSecret);
- jsonWriter.WritePropertyName("algorithmName");
- jsonWriter.WriteValue(tsigKey.Value.AlgorithmName);
- jsonWriter.WriteEndObject();
- }
- }
- jsonWriter.WriteEndArray();
- }
- jsonWriter.WritePropertyName("defaultRecordTtl");
- jsonWriter.WriteValue(_zonesApi.DefaultRecordTtl);
- jsonWriter.WritePropertyName("preferIPv6");
- jsonWriter.WriteValue(_dnsServer.PreferIPv6);
- jsonWriter.WritePropertyName("udpPayloadSize");
- jsonWriter.WriteValue(_dnsServer.UdpPayloadSize);
- jsonWriter.WritePropertyName("dnssecValidation");
- jsonWriter.WriteValue(_dnsServer.DnssecValidation);
- jsonWriter.WritePropertyName("resolverRetries");
- jsonWriter.WriteValue(_dnsServer.ResolverRetries);
- jsonWriter.WritePropertyName("resolverTimeout");
- jsonWriter.WriteValue(_dnsServer.ResolverTimeout);
- jsonWriter.WritePropertyName("resolverMaxStackCount");
- jsonWriter.WriteValue(_dnsServer.ResolverMaxStackCount);
- jsonWriter.WritePropertyName("forwarderRetries");
- jsonWriter.WriteValue(_dnsServer.ForwarderRetries);
- jsonWriter.WritePropertyName("forwarderTimeout");
- jsonWriter.WriteValue(_dnsServer.ForwarderTimeout);
- jsonWriter.WritePropertyName("forwarderConcurrency");
- jsonWriter.WriteValue(_dnsServer.ForwarderConcurrency);
- jsonWriter.WritePropertyName("clientTimeout");
- jsonWriter.WriteValue(_dnsServer.ClientTimeout);
- jsonWriter.WritePropertyName("tcpSendTimeout");
- jsonWriter.WriteValue(_dnsServer.TcpSendTimeout);
- jsonWriter.WritePropertyName("tcpReceiveTimeout");
- jsonWriter.WriteValue(_dnsServer.TcpReceiveTimeout);
- jsonWriter.WritePropertyName("enableLogging");
- jsonWriter.WriteValue(_log.EnableLogging);
- jsonWriter.WritePropertyName("logQueries");
- jsonWriter.WriteValue(_dnsServer.QueryLogManager != null);
- jsonWriter.WritePropertyName("useLocalTime");
- jsonWriter.WriteValue(_log.UseLocalTime);
- jsonWriter.WritePropertyName("logFolder");
- jsonWriter.WriteValue(_log.LogFolder);
- jsonWriter.WritePropertyName("maxLogFileDays");
- jsonWriter.WriteValue(_log.MaxLogFileDays);
- jsonWriter.WritePropertyName("maxStatFileDays");
- jsonWriter.WriteValue(_dnsServer.StatsManager.MaxStatFileDays);
- jsonWriter.WritePropertyName("recursion");
- jsonWriter.WriteValue(_dnsServer.Recursion.ToString());
- jsonWriter.WritePropertyName("recursionDeniedNetworks");
- {
- jsonWriter.WriteStartArray();
- if (_dnsServer.RecursionDeniedNetworks is not null)
- {
- foreach (NetworkAddress networkAddress in _dnsServer.RecursionDeniedNetworks)
- jsonWriter.WriteValue(networkAddress.ToString());
- }
- jsonWriter.WriteEndArray();
- }
- jsonWriter.WritePropertyName("recursionAllowedNetworks");
- {
- jsonWriter.WriteStartArray();
- if (_dnsServer.RecursionAllowedNetworks is not null)
- {
- foreach (NetworkAddress networkAddress in _dnsServer.RecursionAllowedNetworks)
- jsonWriter.WriteValue(networkAddress.ToString());
- }
- jsonWriter.WriteEndArray();
- }
- jsonWriter.WritePropertyName("randomizeName");
- jsonWriter.WriteValue(_dnsServer.RandomizeName);
- jsonWriter.WritePropertyName("qnameMinimization");
- jsonWriter.WriteValue(_dnsServer.QnameMinimization);
- jsonWriter.WritePropertyName("nsRevalidation");
- jsonWriter.WriteValue(_dnsServer.NsRevalidation);
- jsonWriter.WritePropertyName("qpmLimitRequests");
- jsonWriter.WriteValue(_dnsServer.QpmLimitRequests);
- jsonWriter.WritePropertyName("qpmLimitErrors");
- jsonWriter.WriteValue(_dnsServer.QpmLimitErrors);
- jsonWriter.WritePropertyName("qpmLimitSampleMinutes");
- jsonWriter.WriteValue(_dnsServer.QpmLimitSampleMinutes);
- jsonWriter.WritePropertyName("qpmLimitIPv4PrefixLength");
- jsonWriter.WriteValue(_dnsServer.QpmLimitIPv4PrefixLength);
- jsonWriter.WritePropertyName("qpmLimitIPv6PrefixLength");
- jsonWriter.WriteValue(_dnsServer.QpmLimitIPv6PrefixLength);
- jsonWriter.WritePropertyName("serveStale");
- jsonWriter.WriteValue(_dnsServer.ServeStale);
- jsonWriter.WritePropertyName("serveStaleTtl");
- jsonWriter.WriteValue(_dnsServer.CacheZoneManager.ServeStaleTtl);
- jsonWriter.WritePropertyName("cacheMinimumRecordTtl");
- jsonWriter.WriteValue(_dnsServer.CacheZoneManager.MinimumRecordTtl);
- jsonWriter.WritePropertyName("cacheMaximumRecordTtl");
- jsonWriter.WriteValue(_dnsServer.CacheZoneManager.MaximumRecordTtl);
- jsonWriter.WritePropertyName("cacheNegativeRecordTtl");
- jsonWriter.WriteValue(_dnsServer.CacheZoneManager.NegativeRecordTtl);
- jsonWriter.WritePropertyName("cacheFailureRecordTtl");
- jsonWriter.WriteValue(_dnsServer.CacheZoneManager.FailureRecordTtl);
- jsonWriter.WritePropertyName("cachePrefetchEligibility");
- jsonWriter.WriteValue(_dnsServer.CachePrefetchEligibility);
- jsonWriter.WritePropertyName("cachePrefetchTrigger");
- jsonWriter.WriteValue(_dnsServer.CachePrefetchTrigger);
- jsonWriter.WritePropertyName("cachePrefetchSampleIntervalInMinutes");
- jsonWriter.WriteValue(_dnsServer.CachePrefetchSampleIntervalInMinutes);
- jsonWriter.WritePropertyName("cachePrefetchSampleEligibilityHitsPerHour");
- jsonWriter.WriteValue(_dnsServer.CachePrefetchSampleEligibilityHitsPerHour);
- jsonWriter.WritePropertyName("proxy");
- if (_dnsServer.Proxy == null)
- {
- jsonWriter.WriteNull();
- }
- else
- {
- jsonWriter.WriteStartObject();
- NetProxy proxy = _dnsServer.Proxy;
- jsonWriter.WritePropertyName("type");
- jsonWriter.WriteValue(proxy.Type.ToString());
- jsonWriter.WritePropertyName("address");
- jsonWriter.WriteValue(proxy.Address);
- jsonWriter.WritePropertyName("port");
- jsonWriter.WriteValue(proxy.Port);
- NetworkCredential credential = proxy.Credential;
- if (credential != null)
- {
- jsonWriter.WritePropertyName("username");
- jsonWriter.WriteValue(credential.UserName);
- jsonWriter.WritePropertyName("password");
- jsonWriter.WriteValue(credential.Password);
- }
- jsonWriter.WritePropertyName("bypass");
- jsonWriter.WriteStartArray();
- foreach (NetProxyBypassItem item in proxy.BypassList)
- jsonWriter.WriteValue(item.Value);
- jsonWriter.WriteEndArray();
- jsonWriter.WriteEndObject();
- }
- jsonWriter.WritePropertyName("forwarders");
- DnsTransportProtocol forwarderProtocol = DnsTransportProtocol.Udp;
- if (_dnsServer.Forwarders == null)
- {
- jsonWriter.WriteNull();
- }
- else
- {
- forwarderProtocol = _dnsServer.Forwarders[0].Protocol;
- jsonWriter.WriteStartArray();
- foreach (NameServerAddress forwarder in _dnsServer.Forwarders)
- jsonWriter.WriteValue(forwarder.OriginalAddress);
- jsonWriter.WriteEndArray();
- }
- jsonWriter.WritePropertyName("forwarderProtocol");
- jsonWriter.WriteValue(forwarderProtocol.ToString());
- jsonWriter.WritePropertyName("enableBlocking");
- jsonWriter.WriteValue(_dnsServer.EnableBlocking);
- jsonWriter.WritePropertyName("allowTxtBlockingReport");
- jsonWriter.WriteValue(_dnsServer.AllowTxtBlockingReport);
- if (!_dnsServer.EnableBlocking && (DateTime.UtcNow < _temporaryDisableBlockingTill))
- {
- jsonWriter.WritePropertyName("temporaryDisableBlockingTill");
- jsonWriter.WriteValue(_temporaryDisableBlockingTill);
- }
- jsonWriter.WritePropertyName("blockingType");
- jsonWriter.WriteValue(_dnsServer.BlockingType.ToString());
- jsonWriter.WritePropertyName("customBlockingAddresses");
- jsonWriter.WriteStartArray();
- foreach (DnsARecordData record in _dnsServer.CustomBlockingARecords)
- jsonWriter.WriteValue(record.Address.ToString());
- foreach (DnsAAAARecordData record in _dnsServer.CustomBlockingAAAARecords)
- jsonWriter.WriteValue(record.Address.ToString());
- jsonWriter.WriteEndArray();
- jsonWriter.WritePropertyName("blockListUrls");
- if ((_dnsServer.BlockListZoneManager.AllowListUrls.Count == 0) && (_dnsServer.BlockListZoneManager.BlockListUrls.Count == 0))
- {
- jsonWriter.WriteNull();
- }
- else
- {
- jsonWriter.WriteStartArray();
- foreach (Uri allowListUrl in _dnsServer.BlockListZoneManager.AllowListUrls)
- jsonWriter.WriteValue("!" + allowListUrl.AbsoluteUri);
- foreach (Uri blockListUrl in _dnsServer.BlockListZoneManager.BlockListUrls)
- jsonWriter.WriteValue(blockListUrl.AbsoluteUri);
- jsonWriter.WriteEndArray();
- }
- jsonWriter.WritePropertyName("blockListUpdateIntervalHours");
- jsonWriter.WriteValue(_blockListUpdateIntervalHours);
- if (_blockListUpdateTimer is not null)
- {
- DateTime blockListNextUpdatedOn = _blockListLastUpdatedOn.AddHours(_blockListUpdateIntervalHours);
- jsonWriter.WritePropertyName("blockListNextUpdatedOn");
- jsonWriter.WriteValue(blockListNextUpdatedOn);
- }
- }
- private void SetDnsSettings(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- bool restartDnsService = false;
- bool restartWebService = false;
- string strDnsServerDomain = request.QueryString["dnsServerDomain"];
- if (!string.IsNullOrEmpty(strDnsServerDomain))
- _dnsServer.ServerDomain = strDnsServerDomain;
- string strDnsServerLocalEndPoints = request.QueryString["dnsServerLocalEndPoints"];
- if (strDnsServerLocalEndPoints != null)
- {
- if (string.IsNullOrEmpty(strDnsServerLocalEndPoints))
- strDnsServerLocalEndPoints = "0.0.0.0:53,[::]:53";
- string[] strLocalEndPoints = strDnsServerLocalEndPoints.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- List<IPEndPoint> localEndPoints = new List<IPEndPoint>(strLocalEndPoints.Length);
- for (int i = 0; i < strLocalEndPoints.Length; i++)
- {
- NameServerAddress nameServer = new NameServerAddress(strLocalEndPoints[i]);
- if (nameServer.IPEndPoint != null)
- localEndPoints.Add(nameServer.IPEndPoint);
- }
- if (localEndPoints.Count > 0)
- {
- if (_dnsServer.LocalEndPoints.Count != localEndPoints.Count)
- {
- restartDnsService = true;
- }
- else
- {
- foreach (IPEndPoint currentLocalEP in _dnsServer.LocalEndPoints)
- {
- if (!localEndPoints.Contains(currentLocalEP))
- {
- restartDnsService = true;
- break;
- }
- }
- }
- _dnsServer.LocalEndPoints = localEndPoints;
- }
- }
- string strWebServiceLocalAddresses = request.QueryString["webServiceLocalAddresses"];
- if (strWebServiceLocalAddresses != null)
- {
- if (string.IsNullOrEmpty(strWebServiceLocalAddresses))
- strWebServiceLocalAddresses = "0.0.0.0,[::]";
- string[] strLocalAddresses = strWebServiceLocalAddresses.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- List<IPAddress> localAddresses = new List<IPAddress>(strLocalAddresses.Length);
- for (int i = 0; i < strLocalAddresses.Length; i++)
- {
- if (IPAddress.TryParse(strLocalAddresses[i], out IPAddress localAddress))
- localAddresses.Add(localAddress);
- }
- if (localAddresses.Count > 0)
- {
- if (_webServiceLocalAddresses.Count != localAddresses.Count)
- {
- restartWebService = true;
- }
- else
- {
- foreach (IPAddress currentlocalAddress in _webServiceLocalAddresses)
- {
- if (!localAddresses.Contains(currentlocalAddress))
- {
- restartWebService = true;
- break;
- }
- }
- }
- _webServiceLocalAddresses = localAddresses;
- }
- }
- int oldWebServiceHttpPort = _webServiceHttpPort;
- string strWebServiceHttpPort = request.QueryString["webServiceHttpPort"];
- if (!string.IsNullOrEmpty(strWebServiceHttpPort))
- {
- _webServiceHttpPort = int.Parse(strWebServiceHttpPort);
- if (oldWebServiceHttpPort != _webServiceHttpPort)
- restartWebService = true;
- }
- string strWebServiceEnableTls = request.QueryString["webServiceEnableTls"];
- if (!string.IsNullOrEmpty(strWebServiceEnableTls))
- {
- bool oldWebServiceEnableTls = _webServiceEnableTls;
- _webServiceEnableTls = bool.Parse(strWebServiceEnableTls);
- if (oldWebServiceEnableTls != _webServiceEnableTls)
- restartWebService = true;
- }
- string strWebServiceHttpToTlsRedirect = request.QueryString["webServiceHttpToTlsRedirect"];
- if (!string.IsNullOrEmpty(strWebServiceHttpToTlsRedirect))
- _webServiceHttpToTlsRedirect = bool.Parse(strWebServiceHttpToTlsRedirect);
- string strWebServiceTlsPort = request.QueryString["webServiceTlsPort"];
- if (!string.IsNullOrEmpty(strWebServiceTlsPort))
- {
- int oldWebServiceTlsPort = _webServiceTlsPort;
- _webServiceTlsPort = int.Parse(strWebServiceTlsPort);
- if (oldWebServiceTlsPort != _webServiceTlsPort)
- restartWebService = true;
- }
- string strWebServiceUseSelfSignedTlsCertificate = request.QueryString["webServiceUseSelfSignedTlsCertificate"];
- if (!string.IsNullOrEmpty(strWebServiceUseSelfSignedTlsCertificate))
- _webServiceUseSelfSignedTlsCertificate = bool.Parse(strWebServiceUseSelfSignedTlsCertificate);
- string strWebServiceTlsCertificatePath = request.QueryString["webServiceTlsCertificatePath"];
- string strWebServiceTlsCertificatePassword = request.QueryString["webServiceTlsCertificatePassword"];
- if (string.IsNullOrEmpty(strWebServiceTlsCertificatePath))
- {
- _webServiceTlsCertificatePath = null;
- _webServiceTlsCertificatePassword = "";
- }
- else
- {
- if (strWebServiceTlsCertificatePassword == "************")
- strWebServiceTlsCertificatePassword = _webServiceTlsCertificatePassword;
- if ((strWebServiceTlsCertificatePath != _webServiceTlsCertificatePath) || (strWebServiceTlsCertificatePassword != _webServiceTlsCertificatePassword))
- {
- LoadWebServiceTlsCertificate(strWebServiceTlsCertificatePath, strWebServiceTlsCertificatePassword);
- _webServiceTlsCertificatePath = strWebServiceTlsCertificatePath;
- _webServiceTlsCertificatePassword = strWebServiceTlsCertificatePassword;
- StartTlsCertificateUpdateTimer();
- }
- }
- string enableDnsOverHttp = request.QueryString["enableDnsOverHttp"];
- if (!string.IsNullOrEmpty(enableDnsOverHttp))
- {
- bool oldEnableDnsOverHttp = _dnsServer.EnableDnsOverHttp;
- _dnsServer.EnableDnsOverHttp = bool.Parse(enableDnsOverHttp);
- if (oldEnableDnsOverHttp != _dnsServer.EnableDnsOverHttp)
- restartDnsService = true;
- }
- string strEnableDnsOverTls = request.QueryString["enableDnsOverTls"];
- if (!string.IsNullOrEmpty(strEnableDnsOverTls))
- {
- bool oldEnableDnsOverTls = _dnsServer.EnableDnsOverTls;
- _dnsServer.EnableDnsOverTls = bool.Parse(strEnableDnsOverTls);
- if (oldEnableDnsOverTls != _dnsServer.EnableDnsOverTls)
- restartDnsService = true;
- }
- string strEnableDnsOverHttps = request.QueryString["enableDnsOverHttps"];
- if (!string.IsNullOrEmpty(strEnableDnsOverHttps))
- {
- bool oldEnableDnsOverHttps = _dnsServer.EnableDnsOverHttps;
- _dnsServer.EnableDnsOverHttps = bool.Parse(strEnableDnsOverHttps);
- if (oldEnableDnsOverHttps != _dnsServer.EnableDnsOverHttps)
- restartDnsService = true;
- }
- string strDnsTlsCertificatePath = request.QueryString["dnsTlsCertificatePath"];
- string strDnsTlsCertificatePassword = request.QueryString["dnsTlsCertificatePassword"];
- if (string.IsNullOrEmpty(strDnsTlsCertificatePath))
- {
- _dnsTlsCertificatePath = null;
- _dnsTlsCertificatePassword = "";
- }
- else
- {
- if (strDnsTlsCertificatePassword == "************")
- strDnsTlsCertificatePassword = _dnsTlsCertificatePassword;
- if ((strDnsTlsCertificatePath != _dnsTlsCertificatePath) || (strDnsTlsCertificatePassword != _dnsTlsCertificatePassword))
- {
- LoadDnsTlsCertificate(strDnsTlsCertificatePath, strDnsTlsCertificatePassword);
- _dnsTlsCertificatePath = strDnsTlsCertificatePath;
- _dnsTlsCertificatePassword = strDnsTlsCertificatePassword;
- StartTlsCertificateUpdateTimer();
- }
- }
- string strTsigKeys = request.QueryString["tsigKeys"];
- if (!string.IsNullOrEmpty(strTsigKeys))
- {
- if (strTsigKeys == "false")
- {
- _dnsServer.TsigKeys = null;
- }
- else
- {
- string[] strTsigKeyParts = strTsigKeys.Split('|');
- Dictionary<string, TsigKey> tsigKeys = new Dictionary<string, TsigKey>(strTsigKeyParts.Length);
- for (int i = 0; i < strTsigKeyParts.Length; i += 3)
- {
- string keyName = strTsigKeyParts[i + 0].ToLower();
- string sharedSecret = strTsigKeyParts[i + 1];
- string algorithmName = strTsigKeyParts[i + 2];
- if (sharedSecret.Length == 0)
- {
- byte[] key = new byte[32];
- _rng.GetBytes(key);
- tsigKeys.Add(keyName, new TsigKey(keyName, Convert.ToBase64String(key), algorithmName));
- }
- else
- {
- tsigKeys.Add(keyName, new TsigKey(keyName, sharedSecret, algorithmName));
- }
- }
- _dnsServer.TsigKeys = tsigKeys;
- }
- }
- string strDefaultRecordTtl = request.QueryString["defaultRecordTtl"];
- if (!string.IsNullOrEmpty(strDefaultRecordTtl))
- _zonesApi.DefaultRecordTtl = uint.Parse(strDefaultRecordTtl);
- string strPreferIPv6 = request.QueryString["preferIPv6"];
- if (!string.IsNullOrEmpty(strPreferIPv6))
- _dnsServer.PreferIPv6 = bool.Parse(strPreferIPv6);
- string strUdpPayloadSize = request.QueryString["udpPayloadSize"];
- if (!string.IsNullOrEmpty(strUdpPayloadSize))
- _dnsServer.UdpPayloadSize = ushort.Parse(strUdpPayloadSize);
- string strDnssecValidation = request.QueryString["dnssecValidation"];
- if (!string.IsNullOrEmpty(strDnssecValidation))
- _dnsServer.DnssecValidation = bool.Parse(strDnssecValidation);
- string strResolverRetries = request.QueryString["resolverRetries"];
- if (!string.IsNullOrEmpty(strResolverRetries))
- _dnsServer.ResolverRetries = int.Parse(strResolverRetries);
- string strResolverTimeout = request.QueryString["resolverTimeout"];
- if (!string.IsNullOrEmpty(strResolverTimeout))
- _dnsServer.ResolverTimeout = int.Parse(strResolverTimeout);
- string strResolverMaxStackCount = request.QueryString["resolverMaxStackCount"];
- if (!string.IsNullOrEmpty(strResolverMaxStackCount))
- _dnsServer.ResolverMaxStackCount = int.Parse(strResolverMaxStackCount);
- string strForwarderRetries = request.QueryString["forwarderRetries"];
- if (!string.IsNullOrEmpty(strForwarderRetries))
- _dnsServer.ForwarderRetries = int.Parse(strForwarderRetries);
- string strForwarderTimeout = request.QueryString["forwarderTimeout"];
- if (!string.IsNullOrEmpty(strForwarderTimeout))
- _dnsServer.ForwarderTimeout = int.Parse(strForwarderTimeout);
- string strForwarderConcurrency = request.QueryString["forwarderConcurrency"];
- if (!string.IsNullOrEmpty(strForwarderConcurrency))
- _dnsServer.ForwarderConcurrency = int.Parse(strForwarderConcurrency);
- string strClientTimeout = request.QueryString["clientTimeout"];
- if (!string.IsNullOrEmpty(strClientTimeout))
- _dnsServer.ClientTimeout = int.Parse(strClientTimeout);
- string strTcpSendTimeout = request.QueryString["tcpSendTimeout"];
- if (!string.IsNullOrEmpty(strTcpSendTimeout))
- _dnsServer.TcpSendTimeout = int.Parse(strTcpSendTimeout);
- string strTcpReceiveTimeout = request.QueryString["tcpReceiveTimeout"];
- if (!string.IsNullOrEmpty(strTcpReceiveTimeout))
- _dnsServer.TcpReceiveTimeout = int.Parse(strTcpReceiveTimeout);
- string strEnableLogging = request.QueryString["enableLogging"];
- if (!string.IsNullOrEmpty(strEnableLogging))
- _log.EnableLogging = bool.Parse(strEnableLogging);
- string strLogQueries = request.QueryString["logQueries"];
- if (!string.IsNullOrEmpty(strLogQueries))
- {
- if (bool.Parse(strLogQueries))
- _dnsServer.QueryLogManager = _log;
- else
- _dnsServer.QueryLogManager = null;
- }
- string strUseLocalTime = request.QueryString["useLocalTime"];
- if (!string.IsNullOrEmpty(strUseLocalTime))
- _log.UseLocalTime = bool.Parse(strUseLocalTime);
- string strLogFolder = request.QueryString["logFolder"];
- if (!string.IsNullOrEmpty(strLogFolder))
- _log.LogFolder = strLogFolder;
- string strMaxLogFileDays = request.QueryString["maxLogFileDays"];
- if (!string.IsNullOrEmpty(strMaxLogFileDays))
- _log.MaxLogFileDays = int.Parse(strMaxLogFileDays);
- string strMaxStatFileDays = request.QueryString["maxStatFileDays"];
- if (!string.IsNullOrEmpty(strMaxStatFileDays))
- _dnsServer.StatsManager.MaxStatFileDays = int.Parse(strMaxStatFileDays);
- string strRecursion = request.QueryString["recursion"];
- if (!string.IsNullOrEmpty(strRecursion))
- _dnsServer.Recursion = Enum.Parse<DnsServerRecursion>(strRecursion, true);
- string strRecursionDeniedNetworks = request.QueryString["recursionDeniedNetworks"];
- if (!string.IsNullOrEmpty(strRecursionDeniedNetworks))
- {
- if (strRecursionDeniedNetworks == "false")
- {
- _dnsServer.RecursionDeniedNetworks = null;
- }
- else
- {
- string[] strNetworks = strRecursionDeniedNetworks.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- NetworkAddress[] networks = new NetworkAddress[strNetworks.Length];
- for (int i = 0; i < networks.Length; i++)
- networks[i] = NetworkAddress.Parse(strNetworks[i]);
- _dnsServer.RecursionDeniedNetworks = networks;
- }
- }
- string strRecursionAllowedNetworks = request.QueryString["recursionAllowedNetworks"];
- if (!string.IsNullOrEmpty(strRecursionAllowedNetworks))
- {
- if (strRecursionAllowedNetworks == "false")
- {
- _dnsServer.RecursionAllowedNetworks = null;
- }
- else
- {
- string[] strNetworks = strRecursionAllowedNetworks.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- NetworkAddress[] networks = new NetworkAddress[strNetworks.Length];
- for (int i = 0; i < networks.Length; i++)
- networks[i] = NetworkAddress.Parse(strNetworks[i]);
- _dnsServer.RecursionAllowedNetworks = networks;
- }
- }
- string strRandomizeName = request.QueryString["randomizeName"];
- if (!string.IsNullOrEmpty(strRandomizeName))
- _dnsServer.RandomizeName = bool.Parse(strRandomizeName);
- string strQnameMinimization = request.QueryString["qnameMinimization"];
- if (!string.IsNullOrEmpty(strQnameMinimization))
- _dnsServer.QnameMinimization = bool.Parse(strQnameMinimization);
- string strNsRevalidation = request.QueryString["nsRevalidation"];
- if (!string.IsNullOrEmpty(strNsRevalidation))
- _dnsServer.NsRevalidation = bool.Parse(strNsRevalidation);
- string strQpmLimitRequests = request.QueryString["qpmLimitRequests"];
- if (!string.IsNullOrEmpty(strQpmLimitRequests))
- _dnsServer.QpmLimitRequests = int.Parse(strQpmLimitRequests);
- string strQpmLimitErrors = request.QueryString["qpmLimitErrors"];
- if (!string.IsNullOrEmpty(strQpmLimitErrors))
- _dnsServer.QpmLimitErrors = int.Parse(strQpmLimitErrors);
- string strQpmLimitSampleMinutes = request.QueryString["qpmLimitSampleMinutes"];
- if (!string.IsNullOrEmpty(strQpmLimitSampleMinutes))
- _dnsServer.QpmLimitSampleMinutes = int.Parse(strQpmLimitSampleMinutes);
- string strQpmLimitIPv4PrefixLength = request.QueryString["qpmLimitIPv4PrefixLength"];
- if (!string.IsNullOrEmpty(strQpmLimitIPv4PrefixLength))
- _dnsServer.QpmLimitIPv4PrefixLength = int.Parse(strQpmLimitIPv4PrefixLength);
- string strQpmLimitIPv6PrefixLength = request.QueryString["qpmLimitIPv6PrefixLength"];
- if (!string.IsNullOrEmpty(strQpmLimitIPv6PrefixLength))
- _dnsServer.QpmLimitIPv6PrefixLength = int.Parse(strQpmLimitIPv6PrefixLength);
- string strServeStale = request.QueryString["serveStale"];
- if (!string.IsNullOrEmpty(strServeStale))
- _dnsServer.ServeStale = bool.Parse(strServeStale);
- string strServeStaleTtl = request.QueryString["serveStaleTtl"];
- if (!string.IsNullOrEmpty(strServeStaleTtl))
- _dnsServer.CacheZoneManager.ServeStaleTtl = uint.Parse(strServeStaleTtl);
- string strCacheMinimumRecordTtl = request.QueryString["cacheMinimumRecordTtl"];
- if (!string.IsNullOrEmpty(strCacheMinimumRecordTtl))
- _dnsServer.CacheZoneManager.MinimumRecordTtl = uint.Parse(strCacheMinimumRecordTtl);
- string strCacheMaximumRecordTtl = request.QueryString["cacheMaximumRecordTtl"];
- if (!string.IsNullOrEmpty(strCacheMaximumRecordTtl))
- _dnsServer.CacheZoneManager.MaximumRecordTtl = uint.Parse(strCacheMaximumRecordTtl);
- string strCacheNegativeRecordTtl = request.QueryString["cacheNegativeRecordTtl"];
- if (!string.IsNullOrEmpty(strCacheNegativeRecordTtl))
- _dnsServer.CacheZoneManager.NegativeRecordTtl = uint.Parse(strCacheNegativeRecordTtl);
- string strCacheFailureRecordTtl = request.QueryString["cacheFailureRecordTtl"];
- if (!string.IsNullOrEmpty(strCacheFailureRecordTtl))
- _dnsServer.CacheZoneManager.FailureRecordTtl = uint.Parse(strCacheFailureRecordTtl);
- string strCachePrefetchEligibility = request.QueryString["cachePrefetchEligibility"];
- if (!string.IsNullOrEmpty(strCachePrefetchEligibility))
- _dnsServer.CachePrefetchEligibility = int.Parse(strCachePrefetchEligibility);
- string strCachePrefetchTrigger = request.QueryString["cachePrefetchTrigger"];
- if (!string.IsNullOrEmpty(strCachePrefetchTrigger))
- _dnsServer.CachePrefetchTrigger = int.Parse(strCachePrefetchTrigger);
- string strCachePrefetchSampleIntervalInMinutes = request.QueryString["cachePrefetchSampleIntervalInMinutes"];
- if (!string.IsNullOrEmpty(strCachePrefetchSampleIntervalInMinutes))
- _dnsServer.CachePrefetchSampleIntervalInMinutes = int.Parse(strCachePrefetchSampleIntervalInMinutes);
- string strCachePrefetchSampleEligibilityHitsPerHour = request.QueryString["cachePrefetchSampleEligibilityHitsPerHour"];
- if (!string.IsNullOrEmpty(strCachePrefetchSampleEligibilityHitsPerHour))
- _dnsServer.CachePrefetchSampleEligibilityHitsPerHour = int.Parse(strCachePrefetchSampleEligibilityHitsPerHour);
- string strProxyType = request.QueryString["proxyType"];
- if (!string.IsNullOrEmpty(strProxyType))
- {
- NetProxyType proxyType = Enum.Parse<NetProxyType>(strProxyType, true);
- if (proxyType == NetProxyType.None)
- {
- _dnsServer.Proxy = null;
- }
- else
- {
- NetworkCredential credential = null;
- string strUsername = request.QueryString["proxyUsername"];
- if (!string.IsNullOrEmpty(strUsername))
- credential = new NetworkCredential(strUsername, request.QueryString["proxyPassword"]);
- _dnsServer.Proxy = NetProxy.CreateProxy(proxyType, request.QueryString["proxyAddress"], int.Parse(request.QueryString["proxyPort"]), credential);
- string strProxyBypass = request.QueryString["proxyBypass"];
- if (!string.IsNullOrEmpty(strProxyBypass))
- {
- string[] strBypassList = strProxyBypass.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- List<NetProxyBypassItem> bypassList = new List<NetProxyBypassItem>(strBypassList.Length);
- for (int i = 0; i < strBypassList.Length; i++)
- bypassList.Add(new NetProxyBypassItem(strBypassList[i]));
- _dnsServer.Proxy.BypassList = bypassList;
- }
- }
- }
- DnsTransportProtocol forwarderProtocol = DnsTransportProtocol.Udp;
- string strForwarderProtocol = request.QueryString["forwarderProtocol"];
- if (!string.IsNullOrEmpty(strForwarderProtocol))
- forwarderProtocol = Enum.Parse<DnsTransportProtocol>(strForwarderProtocol, true);
- string strForwarders = request.QueryString["forwarders"];
- if (!string.IsNullOrEmpty(strForwarders))
- {
- if (strForwarders == "false")
- {
- _dnsServer.Forwarders = null;
- }
- else
- {
- string[] strForwardersList = strForwarders.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- NameServerAddress[] forwarders = new NameServerAddress[strForwardersList.Length];
- for (int i = 0; i < strForwardersList.Length; i++)
- {
- NameServerAddress forwarder = new NameServerAddress(strForwardersList[i]);
- if (forwarder.Protocol != forwarderProtocol)
- forwarder = forwarder.ChangeProtocol(forwarderProtocol);
- forwarders[i] = forwarder;
- }
- _dnsServer.Forwarders = forwarders;
- }
- }
- string strEnableBlocking = request.QueryString["enableBlocking"];
- if (!string.IsNullOrEmpty(strEnableBlocking))
- {
- _dnsServer.EnableBlocking = bool.Parse(strEnableBlocking);
- if (_dnsServer.EnableBlocking)
- {
- if (_temporaryDisableBlockingTimer is not null)
- _temporaryDisableBlockingTimer.Dispose();
- }
- }
- string strAllowTxtBlockingReport = request.QueryString["allowTxtBlockingReport"];
- if (!string.IsNullOrEmpty(strAllowTxtBlockingReport))
- _dnsServer.AllowTxtBlockingReport = bool.Parse(strAllowTxtBlockingReport);
- string strBlockingType = request.QueryString["blockingType"];
- if (!string.IsNullOrEmpty(strBlockingType))
- _dnsServer.BlockingType = Enum.Parse<DnsServerBlockingType>(strBlockingType, true);
- string strCustomBlockingAddresses = request.QueryString["customBlockingAddresses"];
- if (!string.IsNullOrEmpty(strCustomBlockingAddresses))
- {
- if (strCustomBlockingAddresses == "false")
- {
- _dnsServer.CustomBlockingARecords = null;
- _dnsServer.CustomBlockingAAAARecords = null;
- }
- else
- {
- string[] strAddresses = strCustomBlockingAddresses.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- List<DnsARecordData> dnsARecords = new List<DnsARecordData>();
- List<DnsAAAARecordData> dnsAAAARecords = new List<DnsAAAARecordData>();
- foreach (string strAddress in strAddresses)
- {
- if (IPAddress.TryParse(strAddress, out IPAddress customAddress))
- {
- switch (customAddress.AddressFamily)
- {
- case AddressFamily.InterNetwork:
- dnsARecords.Add(new DnsARecordData(customAddress));
- break;
- case AddressFamily.InterNetworkV6:
- dnsAAAARecords.Add(new DnsAAAARecordData(customAddress));
- break;
- }
- }
- }
- _dnsServer.CustomBlockingARecords = dnsARecords;
- _dnsServer.CustomBlockingAAAARecords = dnsAAAARecords;
- }
- }
- string strBlockListUrls = request.QueryString["blockListUrls"];
- if (!string.IsNullOrEmpty(strBlockListUrls))
- {
- if (strBlockListUrls == "false")
- {
- StopBlockListUpdateTimer();
- _dnsServer.BlockListZoneManager.AllowListUrls.Clear();
- _dnsServer.BlockListZoneManager.BlockListUrls.Clear();
- _dnsServer.BlockListZoneManager.Flush();
- }
- else
- {
- bool updated = false;
- string[] strBlockListUrlList = strBlockListUrls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- if (oldWebServiceHttpPort != _webServiceHttpPort)
- {
- for (int i = 0; i < strBlockListUrlList.Length; i++)
- {
- if (strBlockListUrlList[i].Contains("http://localhost:" + oldWebServiceHttpPort + "/blocklist.txt"))
- {
- strBlockListUrlList[i] = "http://localhost:" + _webServiceHttpPort + "/blocklist.txt";
- updated = true;
- break;
- }
- }
- }
- if (!updated)
- {
- if (strBlockListUrlList.Length != (_dnsServer.BlockListZoneManager.AllowListUrls.Count + _dnsServer.BlockListZoneManager.BlockListUrls.Count))
- {
- updated = true;
- }
- else
- {
- foreach (string strBlockListUrl in strBlockListUrlList)
- {
- if (strBlockListUrl.StartsWith("!"))
- {
- string strAllowListUrl = strBlockListUrl.Substring(1);
- if (!_dnsServer.BlockListZoneManager.AllowListUrls.Contains(new Uri(strAllowListUrl)))
- {
- updated = true;
- break;
- }
- }
- else
- {
- if (!_dnsServer.BlockListZoneManager.BlockListUrls.Contains(new Uri(strBlockListUrl)))
- {
- updated = true;
- break;
- }
- }
- }
- }
- }
- if (updated)
- {
- _dnsServer.BlockListZoneManager.AllowListUrls.Clear();
- _dnsServer.BlockListZoneManager.BlockListUrls.Clear();
- foreach (string strBlockListUrl in strBlockListUrlList)
- {
- if (strBlockListUrl.StartsWith("!"))
- {
- Uri allowListUrl = new Uri(strBlockListUrl.Substring(1));
- if (!_dnsServer.BlockListZoneManager.AllowListUrls.Contains(allowListUrl))
- _dnsServer.BlockListZoneManager.AllowListUrls.Add(allowListUrl);
- }
- else
- {
- Uri blockListUrl = new Uri(strBlockListUrl);
- if (!_dnsServer.BlockListZoneManager.BlockListUrls.Contains(blockListUrl))
- _dnsServer.BlockListZoneManager.BlockListUrls.Add(blockListUrl);
- }
- }
- ForceUpdateBlockLists();
- }
- }
- }
- string strBlockListUpdateIntervalHours = request.QueryString["blockListUpdateIntervalHours"];
- if (!string.IsNullOrEmpty(strBlockListUpdateIntervalHours))
- {
- int blockListUpdateIntervalHours = int.Parse(strBlockListUpdateIntervalHours);
- if ((blockListUpdateIntervalHours < 1) || (blockListUpdateIntervalHours > 168))
- throw new DnsWebServiceException("Parameter `blockListUpdateIntervalHours` must be between 1 hour and 168 hours (7 days).");
- _blockListUpdateIntervalHours = blockListUpdateIntervalHours;
- }
- if ((_webServiceTlsCertificatePath == null) && (_dnsTlsCertificatePath == null))
- StopTlsCertificateUpdateTimer();
- SelfSignedCertCheck(true);
- if (_webServiceEnableTls && string.IsNullOrEmpty(_webServiceTlsCertificatePath) && !_webServiceUseSelfSignedTlsCertificate)
- {
- //disable TLS
- _webServiceEnableTls = false;
- restartWebService = true;
- }
- SaveConfigFile();
- _log.Save();
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS Settings were updated {dnsServerDomain: " + _dnsServer.ServerDomain + "; dnsServerLocalEndPoints: " + strDnsServerLocalEndPoints + "; webServiceLocalAddresses: " + strWebServiceLocalAddresses + "; webServiceHttpPort: " + _webServiceHttpPort + "; webServiceEnableTls: " + strWebServiceEnableTls + "; webServiceHttpToTlsRedirect: " + strWebServiceHttpToTlsRedirect + "; webServiceTlsPort: " + strWebServiceTlsPort + "; webServiceUseSelfSignedTlsCertificate: " + _webServiceUseSelfSignedTlsCertificate + "; webServiceTlsCertificatePath: " + strWebServiceTlsCertificatePath + "; enableDnsOverHttp: " + _dnsServer.EnableDnsOverHttp + "; enableDnsOverTls: " + _dnsServer.EnableDnsOverTls + "; enableDnsOverHttps: " + _dnsServer.EnableDnsOverHttps + "; dnsTlsCertificatePath: " + _dnsTlsCertificatePath + "; defaultRecordTtl: " + _zonesApi.DefaultRecordTtl + "; preferIPv6: " + _dnsServer.PreferIPv6 + "; enableLogging: " + strEnableLogging + "; logQueries: " + (_dnsServer.QueryLogManager != null) + "; useLocalTime: " + strUseLocalTime + "; logFolder: " + strLogFolder + "; maxLogFileDays: " + strMaxLogFileDays + "; recursion: " + _dnsServer.Recursion.ToString() + "; randomizeName: " + strRandomizeName + "; qnameMinimization: " + strQnameMinimization + "; serveStale: " + strServeStale + "; serveStaleTtl: " + strServeStaleTtl + "; cachePrefetchEligibility: " + strCachePrefetchEligibility + "; cachePrefetchTrigger: " + strCachePrefetchTrigger + "; cachePrefetchSampleIntervalInMinutes: " + strCachePrefetchSampleIntervalInMinutes + "; cachePrefetchSampleEligibilityHitsPerHour: " + strCachePrefetchSampleEligibilityHitsPerHour + "; proxyType: " + strProxyType + "; forwarders: " + strForwarders + "; forwarderProtocol: " + strForwarderProtocol + "; enableBlocking: " + _dnsServer.EnableBlocking + "; allowTxtBlockingReport: " + _dnsServer.AllowTxtBlockingReport + "; blockingType: " + _dnsServer.BlockingType.ToString() + "; blockListUrl: " + strBlockListUrls + "; blockListUpdateIntervalHours: " + strBlockListUpdateIntervalHours + ";}");
- GetDnsSettings(jsonWriter);
- RestartService(restartDnsService, restartWebService);
- }
- private void SelfSignedCertCheck(bool throwException)
- {
- string selfSignedCertificateFilePath = Path.Combine(_configFolder, "cert.pfx");
- if (_webServiceUseSelfSignedTlsCertificate)
- {
- if (!File.Exists(selfSignedCertificateFilePath))
- {
- RSA rsa = RSA.Create(2048);
- CertificateRequest req = new CertificateRequest("cn=" + _dnsServer.ServerDomain, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
- X509Certificate2 cert = req.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddYears(5));
- File.WriteAllBytes(selfSignedCertificateFilePath, cert.Export(X509ContentType.Pkcs12, null as string));
- }
- if (_webServiceEnableTls && string.IsNullOrEmpty(_webServiceTlsCertificatePath))
- {
- try
- {
- LoadWebServiceTlsCertificate(selfSignedCertificateFilePath, null);
- }
- catch (Exception ex)
- {
- _log.Write("DNS Server encountered an error while loading self signed Web Service TLS certificate: " + selfSignedCertificateFilePath + "\r\n" + ex.ToString());
- if (throwException)
- throw;
- }
- }
- }
- else
- {
- File.Delete(selfSignedCertificateFilePath);
- }
- }
- private void RestartService(bool restartDnsService, bool restartWebService)
- {
- if (restartDnsService)
- {
- _ = Task.Run(delegate ()
- {
- _log.Write("Attempting to restart DNS service.");
- try
- {
- _dnsServer.Stop();
- _dnsServer.Start();
- _log.Write("DNS service was restarted successfully.");
- }
- catch (Exception ex)
- {
- _log.Write("Failed to restart DNS service.");
- _log.Write(ex);
- }
- });
- }
- if (restartWebService)
- {
- _ = Task.Run(async delegate ()
- {
- await Task.Delay(2000); //wait for this HTTP response to be delivered before stopping web server
- _log.Write("Attempting to restart web service.");
- try
- {
- StopDnsWebService();
- StartDnsWebService();
- _log.Write("Web service was restarted successfully.");
- }
- catch (Exception ex)
- {
- _log.Write("Failed to restart web service.");
- _log.Write(ex);
- }
- });
- }
- }
- private async Task BackupSettingsAsync(HttpListenerRequest request, HttpListenerResponse response)
- {
- bool blockLists = false;
- bool logs = false;
- bool scopes = false;
- bool apps = false;
- bool stats = false;
- bool zones = false;
- bool allowedZones = false;
- bool blockedZones = false;
- bool dnsSettings = false;
- bool logSettings = false;
- string strBlockLists = request.QueryString["blockLists"];
- if (!string.IsNullOrEmpty(strBlockLists))
- blockLists = bool.Parse(strBlockLists);
- string strLogs = request.QueryString["logs"];
- if (!string.IsNullOrEmpty(strLogs))
- logs = bool.Parse(strLogs);
- string strScopes = request.QueryString["scopes"];
- if (!string.IsNullOrEmpty(strScopes))
- scopes = bool.Parse(strScopes);
- string strApps = request.QueryString["apps"];
- if (!string.IsNullOrEmpty(strApps))
- apps = bool.Parse(strApps);
- string strStats = request.QueryString["stats"];
- if (!string.IsNullOrEmpty(strStats))
- stats = bool.Parse(strStats);
- string strZones = request.QueryString["zones"];
- if (!string.IsNullOrEmpty(strZones))
- zones = bool.Parse(strZones);
- string strAllowedZones = request.QueryString["allowedZones"];
- if (!string.IsNullOrEmpty(strAllowedZones))
- allowedZones = bool.Parse(strAllowedZones);
- string strBlockedZones = request.QueryString["blockedZones"];
- if (!string.IsNullOrEmpty(strBlockedZones))
- blockedZones = bool.Parse(strBlockedZones);
- string strDnsSettings = request.QueryString["dnsSettings"];
- if (!string.IsNullOrEmpty(strDnsSettings))
- dnsSettings = bool.Parse(strDnsSettings);
- string strLogSettings = request.QueryString["logSettings"];
- if (!string.IsNullOrEmpty(strLogSettings))
- logSettings = bool.Parse(strLogSettings);
- string tmpFile = Path.GetTempFileName();
- try
- {
- using (FileStream backupZipStream = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
- {
- //create backup zip
- using (ZipArchive backupZip = new ZipArchive(backupZipStream, ZipArchiveMode.Create, true, Encoding.UTF8))
- {
- if (blockLists)
- {
- string[] blockListFiles = Directory.GetFiles(Path.Combine(_configFolder, "blocklists"), "*", SearchOption.TopDirectoryOnly);
- foreach (string blockListFile in blockListFiles)
- {
- string entryName = "blocklists/" + Path.GetFileName(blockListFile);
- backupZip.CreateEntryFromFile(blockListFile, entryName);
- }
- }
- if (logs)
- {
- string[] logFiles = Directory.GetFiles(_log.LogFolderAbsolutePath, "*.log", SearchOption.TopDirectoryOnly);
- foreach (string logFile in logFiles)
- {
- string entryName = "logs/" + Path.GetFileName(logFile);
- if (logFile.Equals(_log.CurrentLogFile, StringComparison.OrdinalIgnoreCase))
- {
- using (FileStream fS = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
- {
- ZipArchiveEntry entry = backupZip.CreateEntry(entryName);
- using (Stream s = entry.Open())
- {
- await fS.CopyToAsync(s);
- }
- }
- }
- else
- {
- backupZip.CreateEntryFromFile(logFile, entryName);
- }
- }
- }
- if (scopes)
- {
- string[] scopeFiles = Directory.GetFiles(Path.Combine(_configFolder, "scopes"), "*.scope", SearchOption.TopDirectoryOnly);
- foreach (string scopeFile in scopeFiles)
- {
- string entryName = "scopes/" + Path.GetFileName(scopeFile);
- backupZip.CreateEntryFromFile(scopeFile, entryName);
- }
- }
- if (apps)
- {
- string[] appFiles = Directory.GetFiles(Path.Combine(_configFolder, "apps"), "*", SearchOption.AllDirectories);
- foreach (string appFile in appFiles)
- {
- string entryName = appFile.Substring(_configFolder.Length);
- if (Path.DirectorySeparatorChar != '/')
- entryName = entryName.Replace(Path.DirectorySeparatorChar, '/');
- entryName = entryName.TrimStart('/');
- backupZip.CreateEntryFromFile(appFile, entryName);
- }
- }
- if (stats)
- {
- string[] hourlyStatsFiles = Directory.GetFiles(Path.Combine(_configFolder, "stats"), "*.stat", SearchOption.TopDirectoryOnly);
- foreach (string hourlyStatsFile in hourlyStatsFiles)
- {
- string entryName = "stats/" + Path.GetFileName(hourlyStatsFile);
- backupZip.CreateEntryFromFile(hourlyStatsFile, entryName);
- }
- string[] dailyStatsFiles = Directory.GetFiles(Path.Combine(_configFolder, "stats"), "*.dstat", SearchOption.TopDirectoryOnly);
- foreach (string dailyStatsFile in dailyStatsFiles)
- {
- string entryName = "stats/" + Path.GetFileName(dailyStatsFile);
- backupZip.CreateEntryFromFile(dailyStatsFile, entryName);
- }
- }
- if (zones)
- {
- string[] zoneFiles = Directory.GetFiles(Path.Combine(_configFolder, "zones"), "*.zone", SearchOption.TopDirectoryOnly);
- foreach (string zoneFile in zoneFiles)
- {
- string entryName = "zones/" + Path.GetFileName(zoneFile);
- backupZip.CreateEntryFromFile(zoneFile, entryName);
- }
- }
- if (allowedZones)
- {
- string allowedZonesFile = Path.Combine(_configFolder, "allowed.config");
- if (File.Exists(allowedZonesFile))
- backupZip.CreateEntryFromFile(allowedZonesFile, "allowed.config");
- }
- if (blockedZones)
- {
- string blockedZonesFile = Path.Combine(_configFolder, "blocked.config");
- if (File.Exists(blockedZonesFile))
- backupZip.CreateEntryFromFile(blockedZonesFile, "blocked.config");
- }
- if (dnsSettings)
- {
- string dnsSettingsFile = Path.Combine(_configFolder, "dns.config");
- if (File.Exists(dnsSettingsFile))
- backupZip.CreateEntryFromFile(dnsSettingsFile, "dns.config");
- }
- if (logSettings)
- {
- string logSettingsFile = Path.Combine(_configFolder, "log.config");
- if (File.Exists(logSettingsFile))
- backupZip.CreateEntryFromFile(logSettingsFile, "log.config");
- }
- }
- //send zip file
- backupZipStream.Position = 0;
- response.ContentType = "application/zip";
- response.ContentLength64 = backupZipStream.Length;
- response.AddHeader("Content-Disposition", "attachment;filename=DnsServerBackup.zip");
- using (Stream output = response.OutputStream)
- {
- await backupZipStream.CopyToAsync(output);
- }
- }
- }
- finally
- {
- try
- {
- File.Delete(tmpFile);
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- }
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Settings backup zip file was exported.");
- }
- private async Task RestoreSettingsAsync(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- bool blockLists = false;
- bool logs = false;
- bool scopes = false;
- bool apps = false;
- bool stats = false;
- bool zones = false;
- bool allowedZones = false;
- bool blockedZones = false;
- bool dnsSettings = false;
- bool logSettings = false;
- bool deleteExistingFiles = false;
- string strBlockLists = request.QueryString["blockLists"];
- if (!string.IsNullOrEmpty(strBlockLists))
- blockLists = bool.Parse(strBlockLists);
- string strLogs = request.QueryString["logs"];
- if (!string.IsNullOrEmpty(strLogs))
- logs = bool.Parse(strLogs);
- string strScopes = request.QueryString["scopes"];
- if (!string.IsNullOrEmpty(strScopes))
- scopes = bool.Parse(strScopes);
- string strApps = request.QueryString["apps"];
- if (!string.IsNullOrEmpty(strApps))
- apps = bool.Parse(strApps);
- string strStats = request.QueryString["stats"];
- if (!string.IsNullOrEmpty(strStats))
- stats = bool.Parse(strStats);
- string strZones = request.QueryString["zones"];
- if (!string.IsNullOrEmpty(strZones))
- zones = bool.Parse(strZones);
- string strAllowedZones = request.QueryString["allowedZones"];
- if (!string.IsNullOrEmpty(strAllowedZones))
- allowedZones = bool.Parse(strAllowedZones);
- string strBlockedZones = request.QueryString["blockedZones"];
- if (!string.IsNullOrEmpty(strBlockedZones))
- blockedZones = bool.Parse(strBlockedZones);
- string strDnsSettings = request.QueryString["dnsSettings"];
- if (!string.IsNullOrEmpty(strDnsSettings))
- dnsSettings = bool.Parse(strDnsSettings);
- string strLogSettings = request.QueryString["logSettings"];
- if (!string.IsNullOrEmpty(strLogSettings))
- logSettings = bool.Parse(strLogSettings);
- string strDeleteExistingFiles = request.QueryString["deleteExistingFiles"];
- if (!string.IsNullOrEmpty(strDeleteExistingFiles))
- deleteExistingFiles = bool.Parse(strDeleteExistingFiles);
- #region skip to content
- int crlfCount = 0;
- int byteRead;
- while (crlfCount != 4)
- {
- byteRead = request.InputStream.ReadByte();
- switch (byteRead)
- {
- case -1:
- throw new EndOfStreamException();
- case 13: //CR
- case 10: //LF
- crlfCount++;
- break;
- default:
- crlfCount = 0;
- break;
- }
- }
- #endregion
- //write to temp file
- string tmpFile = Path.GetTempFileName();
- try
- {
- using (FileStream fS = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite))
- {
- await request.InputStream.CopyToAsync(fS);
- fS.Position = 0;
- using (ZipArchive backupZip = new ZipArchive(fS, ZipArchiveMode.Read, false, Encoding.UTF8))
- {
- if (logSettings || logs)
- {
- //stop logging
- _log.StopLogging();
- }
- try
- {
- if (logSettings)
- {
- ZipArchiveEntry entry = backupZip.GetEntry("log.config");
- if (entry != null)
- entry.ExtractToFile(Path.Combine(_configFolder, entry.Name), true);
- //reload config
- _log.LoadConfig();
- }
- if (logs)
- {
- if (deleteExistingFiles)
- {
- //delete existing log files
- string[] logFiles = Directory.GetFiles(_log.LogFolderAbsolutePath, "*.log", SearchOption.TopDirectoryOnly);
- foreach (string logFile in logFiles)
- {
- File.Delete(logFile);
- }
- }
- //extract log files from backup
- foreach (ZipArchiveEntry entry in backupZip.Entries)
- {
- if (entry.FullName.StartsWith("logs/"))
- entry.ExtractToFile(Path.Combine(_log.LogFolderAbsolutePath, entry.Name), true);
- }
- }
- }
- finally
- {
- if (logSettings || logs)
- {
- //start logging
- if (_log.EnableLogging)
- _log.StartLogging();
- }
- }
- if (blockLists)
- {
- if (deleteExistingFiles)
- {
- //delete existing block list files
- string[] blockListFiles = Directory.GetFiles(Path.Combine(_configFolder, "blocklists"), "*", SearchOption.TopDirectoryOnly);
- foreach (string blockListFile in blockListFiles)
- {
- File.Delete(blockListFile);
- }
- }
- //extract block list files from backup
- foreach (ZipArchiveEntry entry in backupZip.Entries)
- {
- if (entry.FullName.StartsWith("blocklists/"))
- entry.ExtractToFile(Path.Combine(_configFolder, "blocklists", entry.Name), true);
- }
- }
- if (scopes)
- {
- //stop dhcp server
- _dhcpServer.Stop();
- try
- {
- if (deleteExistingFiles)
- {
- //delete existing scope files
- string[] scopeFiles = Directory.GetFiles(Path.Combine(_configFolder, "scopes"), "*.scope", SearchOption.TopDirectoryOnly);
- foreach (string scopeFile in scopeFiles)
- {
- File.Delete(scopeFile);
- }
- }
- //extract scope files from backup
- foreach (ZipArchiveEntry entry in backupZip.Entries)
- {
- if (entry.FullName.StartsWith("scopes/"))
- entry.ExtractToFile(Path.Combine(_configFolder, "scopes", entry.Name), true);
- }
- }
- finally
- {
- //start dhcp server
- _dhcpServer.Start();
- }
- }
- if (apps)
- {
- //unload apps
- _dnsServer.DnsApplicationManager.UnloadAllApplications();
- if (deleteExistingFiles)
- {
- //delete existing apps
- string appFolder = Path.Combine(_configFolder, "apps");
- if (Directory.Exists(appFolder))
- Directory.Delete(appFolder, true);
- //create apps folder
- Directory.CreateDirectory(appFolder);
- }
- //extract apps files from backup
- foreach (ZipArchiveEntry entry in backupZip.Entries)
- {
- if (entry.FullName.StartsWith("apps/"))
- {
- string entryPath = entry.FullName;
- if (Path.DirectorySeparatorChar != '/')
- entryPath = entryPath.Replace('/', '\\');
- string filePath = Path.Combine(_configFolder, entryPath);
- Directory.CreateDirectory(Path.GetDirectoryName(filePath));
- entry.ExtractToFile(filePath, true);
- }
- }
- //reload apps
- _dnsServer.DnsApplicationManager.LoadAllApplications();
- }
- if (stats)
- {
- if (deleteExistingFiles)
- {
- //delete existing stats files
- string[] hourlyStatsFiles = Directory.GetFiles(Path.Combine(_configFolder, "stats"), "*.stat", SearchOption.TopDirectoryOnly);
- foreach (string hourlyStatsFile in hourlyStatsFiles)
- {
- File.Delete(hourlyStatsFile);
- }
- string[] dailyStatsFiles = Directory.GetFiles(Path.Combine(_configFolder, "stats"), "*.dstat", SearchOption.TopDirectoryOnly);
- foreach (string dailyStatsFile in dailyStatsFiles)
- {
- File.Delete(dailyStatsFile);
- }
- }
- //extract stats files from backup
- foreach (ZipArchiveEntry entry in backupZip.Entries)
- {
- if (entry.FullName.StartsWith("stats/"))
- entry.ExtractToFile(Path.Combine(_configFolder, "stats", entry.Name), true);
- }
- //reload stats
- _dnsServer.StatsManager.ReloadStats();
- }
- if (zones)
- {
- if (deleteExistingFiles)
- {
- //delete existing zone files
- string[] zoneFiles = Directory.GetFiles(Path.Combine(_configFolder, "zones"), "*.zone", SearchOption.TopDirectoryOnly);
- foreach (string zoneFile in zoneFiles)
- {
- File.Delete(zoneFile);
- }
- }
- //extract zone files from backup
- foreach (ZipArchiveEntry entry in backupZip.Entries)
- {
- if (entry.FullName.StartsWith("zones/"))
- entry.ExtractToFile(Path.Combine(_configFolder, "zones", entry.Name), true);
- }
- //reload zones
- _dnsServer.AuthZoneManager.LoadAllZoneFiles();
- }
- if (allowedZones)
- {
- ZipArchiveEntry entry = backupZip.GetEntry("allowed.config");
- if (entry == null)
- {
- string fileName = Path.Combine(_configFolder, "allowed.config");
- if (File.Exists(fileName))
- File.Delete(fileName);
- }
- else
- {
- entry.ExtractToFile(Path.Combine(_configFolder, entry.Name), true);
- }
- //reload
- _dnsServer.AllowedZoneManager.LoadAllowedZoneFile();
- }
- if (blockedZones)
- {
- ZipArchiveEntry entry = backupZip.GetEntry("blocked.config");
- if (entry == null)
- {
- string fileName = Path.Combine(_configFolder, "allowed.config");
- if (File.Exists(fileName))
- File.Delete(fileName);
- }
- else
- {
- entry.ExtractToFile(Path.Combine(_configFolder, entry.Name), true);
- }
- //reload
- _dnsServer.BlockedZoneManager.LoadBlockedZoneFile();
- }
- if (dnsSettings)
- {
- ZipArchiveEntry entry = backupZip.GetEntry("dns.config");
- if (entry != null)
- entry.ExtractToFile(Path.Combine(_configFolder, entry.Name), true);
- //reload settings and block list zone
- LoadConfigFile();
- _dnsServer.BlockListZoneManager.LoadBlockLists();
- }
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Settings backup zip file was restored.");
- }
- }
- }
- finally
- {
- try
- {
- File.Delete(tmpFile);
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- }
- if (dnsSettings)
- RestartService(true, true);
- GetDnsSettings(jsonWriter);
- }
- private void ForceUpdateBlockLists(HttpListenerRequest request)
- {
- if (ForceUpdateBlockLists())
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Block list update was triggered.");
- }
- private void TemporaryDisableBlocking(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string strMinutes = request.QueryString["minutes"];
- if (string.IsNullOrEmpty(strMinutes))
- throw new DnsWebServiceException("Parameter 'minutes' missing.");
- int minutes = int.Parse(strMinutes);
- Timer temporaryDisableBlockingTimer = _temporaryDisableBlockingTimer;
- if (temporaryDisableBlockingTimer is not null)
- temporaryDisableBlockingTimer.Dispose();
- Timer newTemporaryDisableBlockingTimer = new Timer(delegate (object state)
- {
- try
- {
- _dnsServer.EnableBlocking = true;
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Blocking was enabled after " + minutes + " minute(s) being temporarily disabled.");
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- });
- Timer originalTimer = Interlocked.CompareExchange(ref _temporaryDisableBlockingTimer, newTemporaryDisableBlockingTimer, temporaryDisableBlockingTimer);
- if (ReferenceEquals(originalTimer, temporaryDisableBlockingTimer))
- {
- newTemporaryDisableBlockingTimer.Change(minutes * 60 * 1000, Timeout.Infinite);
- _dnsServer.EnableBlocking = false;
- _temporaryDisableBlockingTill = DateTime.UtcNow.AddMinutes(minutes);
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] Blocking was temporarily disabled for " + minutes + " minute(s).");
- }
- else
- {
- newTemporaryDisableBlockingTimer.Dispose();
- }
- jsonWriter.WritePropertyName("temporaryDisableBlockingTill");
- jsonWriter.WriteValue(_temporaryDisableBlockingTill);
- }
- #endregion
- #region dns client api
- private async Task ResolveQuery(HttpListenerRequest request, JsonTextWriter jsonWriter)
- {
- string server = request.QueryString["server"];
- if (string.IsNullOrEmpty(server))
- throw new DnsWebServiceException("Parameter 'server' missing.");
- string domain = request.QueryString["domain"];
- if (string.IsNullOrEmpty(domain))
- throw new DnsWebServiceException("Parameter 'domain' missing.");
- domain = domain.Trim(new char[] { '\t', ' ', '.' });
- string strType = request.QueryString["type"];
- if (string.IsNullOrEmpty(strType))
- throw new DnsWebServiceException("Parameter 'type' missing.");
- DnsResourceRecordType type = (DnsResourceRecordType)Enum.Parse(typeof(DnsResourceRecordType), strType);
- string strProtocol = request.QueryString["protocol"];
- if (string.IsNullOrEmpty(strProtocol))
- strProtocol = "Udp";
- bool dnssecValidation = false;
- string strDnssecValidation = request.QueryString["dnssec"];
- if (!string.IsNullOrEmpty(strDnssecValidation))
- dnssecValidation = bool.Parse(strDnssecValidation);
- bool importResponse = false;
- string strImport = request.QueryString["import"];
- if (!string.IsNullOrEmpty(strImport))
- importResponse = bool.Parse(strImport);
- NetProxy proxy = _dnsServer.Proxy;
- bool preferIPv6 = _dnsServer.PreferIPv6;
- ushort udpPayloadSize = _dnsServer.UdpPayloadSize;
- bool randomizeName = false;
- bool qnameMinimization = _dnsServer.QnameMinimization;
- DnsTransportProtocol protocol = Enum.Parse<DnsTransportProtocol>(strProtocol, true);
- const int RETRIES = 1;
- const int TIMEOUT = 10000;
- DnsDatagram dnsResponse;
- string dnssecErrorMessage = null;
- if (server.Equals("recursive-resolver", StringComparison.OrdinalIgnoreCase))
- {
- if (type == DnsResourceRecordType.AXFR)
- throw new DnsServerException("Cannot do zone transfer (AXFR) for 'recursive-resolver'.");
- DnsQuestionRecord question;
- if ((type == DnsResourceRecordType.PTR) && IPAddress.TryParse(domain, out IPAddress address))
- question = new DnsQuestionRecord(address, DnsClass.IN);
- else
- question = new DnsQuestionRecord(domain, type, DnsClass.IN);
- DnsCache dnsCache = new DnsCache();
- dnsCache.MinimumRecordTtl = 0;
- dnsCache.MaximumRecordTtl = 7 * 24 * 60 * 60;
- try
- {
- dnsResponse = await DnsClient.RecursiveResolveAsync(question, dnsCache, proxy, preferIPv6, udpPayloadSize, randomizeName, qnameMinimization, false, dnssecValidation, RETRIES, TIMEOUT);
- }
- catch (DnsClientResponseDnssecValidationException ex)
- {
- dnsResponse = ex.Response;
- dnssecErrorMessage = ex.Message;
- importResponse = false;
- }
- }
- else
- {
- if ((type == DnsResourceRecordType.AXFR) && (protocol == DnsTransportProtocol.Udp))
- protocol = DnsTransportProtocol.Tcp;
- NameServerAddress nameServer;
- if (server.Equals("this-server", StringComparison.OrdinalIgnoreCase))
- {
- switch (protocol)
- {
- case DnsTransportProtocol.Udp:
- nameServer = _dnsServer.ThisServer;
- break;
- case DnsTransportProtocol.Tcp:
- nameServer = _dnsServer.ThisServer.ChangeProtocol(DnsTransportProtocol.Tcp);
- break;
- case DnsTransportProtocol.Tls:
- throw new DnsServerException("Cannot use DNS-over-TLS protocol for 'this-server'. Please use the TLS certificate domain name as the server.");
- case DnsTransportProtocol.Https:
- throw new DnsServerException("Cannot use DNS-over-HTTPS protocol for 'this-server'. Please use the TLS certificate domain name with a url as the server.");
- case DnsTransportProtocol.HttpsJson:
- throw new DnsServerException("Cannot use DNS-over-HTTPS (JSON) protocol for 'this-server'. Please use the TLS certificate domain name with a url as the server.");
- default:
- throw new InvalidOperationException();
- }
- proxy = null; //no proxy required for this server
- }
- else
- {
- nameServer = new NameServerAddress(server);
- if (nameServer.Protocol != protocol)
- nameServer = nameServer.ChangeProtocol(protocol);
- if (nameServer.IsIPEndPointStale)
- {
- if (proxy is null)
- await nameServer.ResolveIPAddressAsync(_dnsServer, _dnsServer.PreferIPv6);
- }
- else if (protocol != DnsTransportProtocol.Tls)
- {
- try
- {
- await nameServer.ResolveDomainNameAsync(_dnsServer);
- }
- catch
- { }
- }
- }
- DnsClient dnsClient = new DnsClient(nameServer);
- dnsClient.Proxy = proxy;
- dnsClient.PreferIPv6 = preferIPv6;
- dnsClient.RandomizeName = randomizeName;
- dnsClient.Retries = RETRIES;
- dnsClient.Timeout = TIMEOUT;
- dnsClient.UdpPayloadSize = udpPayloadSize;
- dnsClient.DnssecValidation = dnssecValidation;
- if (dnssecValidation)
- {
- //load trust anchors into dns client if domain is locally hosted
- _dnsServer.AuthZoneManager.LoadTrustAnchorsTo(dnsClient, domain, type);
- }
- try
- {
- dnsResponse = await dnsClient.ResolveAsync(domain, type);
- }
- catch (DnsClientResponseDnssecValidationException ex)
- {
- dnsResponse = ex.Response;
- dnssecErrorMessage = ex.Message;
- importResponse = false;
- }
- if (type == DnsResourceRecordType.AXFR)
- dnsResponse = dnsResponse.Join();
- }
- if (importResponse)
- {
- AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.FindAuthZoneInfo(domain);
- if ((zoneInfo is null) || ((zoneInfo.Type == AuthZoneType.Secondary) && !zoneInfo.Name.Equals(domain, StringComparison.OrdinalIgnoreCase)))
- {
- zoneInfo = _dnsServer.AuthZoneManager.CreatePrimaryZone(domain, _dnsServer.ServerDomain, false);
- if (zoneInfo is null)
- throw new DnsServerException("Cannot import records: failed to create primary zone.");
- }
- else
- {
- switch (zoneInfo.Type)
- {
- case AuthZoneType.Primary:
- break;
- case AuthZoneType.Forwarder:
- if (type == DnsResourceRecordType.AXFR)
- throw new DnsServerException("Cannot import records via zone transfer: import zone must be of primary type.");
- break;
- default:
- throw new DnsServerException("Cannot import records: import zone must be of primary or forwarder type.");
- }
- }
- if (type == DnsResourceRecordType.AXFR)
- {
- _dnsServer.AuthZoneManager.SyncZoneTransferRecords(zoneInfo.Name, dnsResponse.Answer);
- }
- else
- {
- List<DnsResourceRecord> importRecords = new List<DnsResourceRecord>(dnsResponse.Answer.Count + dnsResponse.Authority.Count);
- foreach (DnsResourceRecord record in dnsResponse.Answer)
- {
- if (record.Name.Equals(zoneInfo.Name, StringComparison.OrdinalIgnoreCase) || record.Name.EndsWith("." + zoneInfo.Name, StringComparison.OrdinalIgnoreCase) || (zoneInfo.Name.Length == 0))
- {
- record.RemoveExpiry();
- importRecords.Add(record);
- if (record.Type == DnsResourceRecordType.NS)
- record.SyncGlueRecords(dnsResponse.Additional);
- }
- }
- foreach (DnsResourceRecord record in dnsResponse.Authority)
- {
- if (record.Name.Equals(zoneInfo.Name, StringComparison.OrdinalIgnoreCase) || record.Name.EndsWith("." + zoneInfo.Name, StringComparison.OrdinalIgnoreCase) || (zoneInfo.Name.Length == 0))
- {
- record.RemoveExpiry();
- importRecords.Add(record);
- if (record.Type == DnsResourceRecordType.NS)
- record.SyncGlueRecords(dnsResponse.Additional);
- }
- }
- _dnsServer.AuthZoneManager.ImportRecords(zoneInfo.Name, importRecords);
- }
- _log.Write(GetRequestRemoteEndPoint(request), "[" + GetSession(request).Username + "] DNS Client imported record(s) for authoritative zone {server: " + server + "; zone: " + zoneInfo.Name + "; type: " + type + ";}");
- _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
- }
- if (dnssecErrorMessage is not null)
- {
- jsonWriter.WritePropertyName("warningMessage");
- jsonWriter.WriteValue(dnssecErrorMessage);
- }
- jsonWriter.WritePropertyName("result");
- jsonWriter.WriteRawValue(JsonConvert.SerializeObject(dnsResponse, new StringEnumConverter()));
- }
- #endregion
- #region auth
- private void SetCredentials(string username, string password)
- {
- username = username.ToLower();
- string passwordHash = GetPasswordHash(username, password);
- _credentials[username] = passwordHash;
- }
- private void LoadCredentials(string username, string passwordHash)
- {
- username = username.ToLower();
- _credentials[username] = passwordHash;
- }
- private static string GetPasswordHash(string username, string password)
- {
- using (HMAC hmac = new HMACSHA256(Encoding.UTF8.GetBytes(password)))
- {
- return Convert.ToHexString(hmac.ComputeHash(Encoding.UTF8.GetBytes(username))).ToLower();
- }
- }
- #endregion
- #region block list
- private bool ForceUpdateBlockLists()
- {
- if ((_dnsServer.BlockListZoneManager.AllowListUrls.Count + _dnsServer.BlockListZoneManager.BlockListUrls.Count) > 0)
- {
- _blockListLastUpdatedOn = new DateTime();
- StopBlockListUpdateTimer();
- StartBlockListUpdateTimer();
- return true;
- }
- return false;
- }
- private void StartBlockListUpdateTimer()
- {
- if (_blockListUpdateTimer == null)
- {
- _blockListUpdateTimer = new Timer(async delegate (object state)
- {
- try
- {
- if (DateTime.UtcNow > _blockListLastUpdatedOn.AddHours(_blockListUpdateIntervalHours))
- {
- if (await _dnsServer.BlockListZoneManager.UpdateBlockListsAsync())
- {
- //block lists were updated
- //save last updated on time
- _blockListLastUpdatedOn = DateTime.UtcNow;
- SaveConfigFile();
- }
- }
- }
- catch (Exception ex)
- {
- _log.Write("DNS Server encountered an error while updating block lists.\r\n" + ex.ToString());
- }
- }, null, BLOCK_LIST_UPDATE_TIMER_INITIAL_INTERVAL, BLOCK_LIST_UPDATE_TIMER_PERIODIC_INTERVAL);
- }
- }
- private void StopBlockListUpdateTimer()
- {
- if (_blockListUpdateTimer != null)
- {
- _blockListUpdateTimer.Dispose();
- _blockListUpdateTimer = null;
- }
- }
- #endregion
- #region tls
- private void StartTlsCertificateUpdateTimer()
- {
- if (_tlsCertificateUpdateTimer == null)
- {
- _tlsCertificateUpdateTimer = new Timer(delegate (object state)
- {
- if (!string.IsNullOrEmpty(_webServiceTlsCertificatePath))
- {
- try
- {
- FileInfo fileInfo = new FileInfo(_webServiceTlsCertificatePath);
- if (fileInfo.Exists && (fileInfo.LastWriteTimeUtc != _webServiceTlsCertificateLastModifiedOn))
- LoadWebServiceTlsCertificate(_webServiceTlsCertificatePath, _webServiceTlsCertificatePassword);
- }
- catch (Exception ex)
- {
- _log.Write("DNS Server encountered an error while updating Web Service TLS Certificate: " + _webServiceTlsCertificatePath + "\r\n" + ex.ToString());
- }
- }
- if (!string.IsNullOrEmpty(_dnsTlsCertificatePath))
- {
- try
- {
- FileInfo fileInfo = new FileInfo(_dnsTlsCertificatePath);
- if (fileInfo.Exists && (fileInfo.LastWriteTimeUtc != _dnsTlsCertificateLastModifiedOn))
- LoadDnsTlsCertificate(_dnsTlsCertificatePath, _dnsTlsCertificatePassword);
- }
- catch (Exception ex)
- {
- _log.Write("DNS Server encountered an error while updating DNS Server TLS Certificate: " + _dnsTlsCertificatePath + "\r\n" + ex.ToString());
- }
- }
- }, null, TLS_CERTIFICATE_UPDATE_TIMER_INITIAL_INTERVAL, TLS_CERTIFICATE_UPDATE_TIMER_INTERVAL);
- }
- }
- private void StopTlsCertificateUpdateTimer()
- {
- if (_tlsCertificateUpdateTimer != null)
- {
- _tlsCertificateUpdateTimer.Dispose();
- _tlsCertificateUpdateTimer = null;
- }
- }
- private void LoadWebServiceTlsCertificate(string tlsCertificatePath, string tlsCertificatePassword)
- {
- FileInfo fileInfo = new FileInfo(tlsCertificatePath);
- if (!fileInfo.Exists)
- throw new ArgumentException("Web Service TLS certificate file does not exists: " + tlsCertificatePath);
- if (Path.GetExtension(tlsCertificatePath) != ".pfx")
- throw new ArgumentException("Web Service TLS certificate file must be PKCS #12 formatted with .pfx extension: " + tlsCertificatePath);
- X509Certificate2 certificate = new X509Certificate2(tlsCertificatePath, tlsCertificatePassword);
- _webServiceTlsCertificate = certificate;
- _webServiceTlsCertificateLastModifiedOn = fileInfo.LastWriteTimeUtc;
- _log.Write("Web Service TLS certificate was loaded: " + tlsCertificatePath);
- }
- private void LoadDnsTlsCertificate(string tlsCertificatePath, string tlsCertificatePassword)
- {
- FileInfo fileInfo = new FileInfo(tlsCertificatePath);
- if (!fileInfo.Exists)
- throw new ArgumentException("DNS Server TLS certificate file does not exists: " + tlsCertificatePath);
- if (Path.GetExtension(tlsCertificatePath) != ".pfx")
- throw new ArgumentException("DNS Server TLS certificate file must be PKCS #12 formatted with .pfx extension: " + tlsCertificatePath);
- X509Certificate2 certificate = new X509Certificate2(tlsCertificatePath, tlsCertificatePassword);
- _dnsServer.Certificate = certificate;
- _dnsTlsCertificateLastModifiedOn = fileInfo.LastWriteTimeUtc;
- _log.Write("DNS Server TLS certificate was loaded: " + tlsCertificatePath);
- }
- #endregion
- #region config
- private void LoadConfigFile()
- {
- string configFile = Path.Combine(_configFolder, "dns.config");
- try
- {
- bool passwordResetOption = false;
- if (!File.Exists(configFile))
- {
- string passwordResetConfigFile = Path.Combine(_configFolder, "reset.config");
- if (File.Exists(passwordResetConfigFile))
- {
- passwordResetOption = true;
- configFile = passwordResetConfigFile;
- }
- }
- byte version;
- using (FileStream fS = new FileStream(configFile, FileMode.Open, FileAccess.Read))
- {
- BinaryReader bR = new BinaryReader(fS);
- if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "DS") //format
- throw new InvalidDataException("DnsServer config file format is invalid.");
- version = bR.ReadByte();
- switch (version)
- {
- case 2:
- case 3:
- case 4:
- case 5:
- case 6:
- case 7:
- case 8:
- case 9:
- case 10:
- case 11:
- case 12:
- case 13:
- case 14:
- case 15:
- case 16:
- case 17:
- case 18:
- case 19:
- case 20:
- case 21:
- case 22:
- case 23:
- case 24:
- case 25:
- case 26:
- _dnsServer.ServerDomain = bR.ReadShortString();
- _webServiceHttpPort = bR.ReadInt32();
- if (version >= 13)
- {
- {
- int count = bR.ReadByte();
- if (count > 0)
- {
- IPAddress[] localAddresses = new IPAddress[count];
- for (int i = 0; i < count; i++)
- localAddresses[i] = IPAddressExtension.Parse(bR);
- _webServiceLocalAddresses = localAddresses;
- }
- }
- _webServiceTlsPort = bR.ReadInt32();
- _webServiceEnableTls = bR.ReadBoolean();
- _webServiceHttpToTlsRedirect = bR.ReadBoolean();
- _webServiceTlsCertificatePath = bR.ReadShortString();
- _webServiceTlsCertificatePassword = bR.ReadShortString();
- if (_webServiceTlsCertificatePath.Length == 0)
- _webServiceTlsCertificatePath = null;
- if (_webServiceTlsCertificatePath != null)
- {
- try
- {
- LoadWebServiceTlsCertificate(_webServiceTlsCertificatePath, _webServiceTlsCertificatePassword);
- }
- catch (Exception ex)
- {
- _log.Write("DNS Server encountered an error while loading Web Service TLS certificate: " + _webServiceTlsCertificatePath + "\r\n" + ex.ToString());
- }
- StartTlsCertificateUpdateTimer();
- }
- }
- else
- {
- _webServiceLocalAddresses = new IPAddress[] { IPAddress.Any, IPAddress.IPv6Any };
- _webServiceTlsPort = 53443;
- _webServiceEnableTls = false;
- _webServiceHttpToTlsRedirect = false;
- _webServiceTlsCertificatePath = string.Empty;
- _webServiceTlsCertificatePassword = string.Empty;
- }
- _dnsServer.PreferIPv6 = bR.ReadBoolean();
- if (bR.ReadBoolean()) //logQueries
- _dnsServer.QueryLogManager = _log;
- if (version >= 14)
- _dnsServer.StatsManager.MaxStatFileDays = bR.ReadInt32();
- else
- _dnsServer.StatsManager.MaxStatFileDays = 0;
- if (version >= 17)
- {
- _dnsServer.Recursion = (DnsServerRecursion)bR.ReadByte();
- {
- int count = bR.ReadByte();
- if (count > 0)
- {
- NetworkAddress[] networks = new NetworkAddress[count];
- for (int i = 0; i < count; i++)
- networks[i] = NetworkAddress.Parse(bR);
- _dnsServer.RecursionDeniedNetworks = networks;
- }
- }
- {
- int count = bR.ReadByte();
- if (count > 0)
- {
- NetworkAddress[] networks = new NetworkAddress[count];
- for (int i = 0; i < count; i++)
- networks[i] = NetworkAddress.Parse(bR);
- _dnsServer.RecursionAllowedNetworks = networks;
- }
- }
- }
- else
- {
- bool allowRecursion = bR.ReadBoolean();
- bool allowRecursionOnlyForPrivateNetworks;
- if (version >= 4)
- allowRecursionOnlyForPrivateNetworks = bR.ReadBoolean();
- else
- allowRecursionOnlyForPrivateNetworks = true; //default true for security reasons
- if (allowRecursion)
- {
- if (allowRecursionOnlyForPrivateNetworks)
- _dnsServer.Recursion = DnsServerRecursion.AllowOnlyForPrivateNetworks;
- else
- _dnsServer.Recursion = DnsServerRecursion.Allow;
- }
- else
- {
- _dnsServer.Recursion = DnsServerRecursion.Deny;
- }
- }
- if (version >= 12)
- _dnsServer.RandomizeName = bR.ReadBoolean();
- else
- _dnsServer.RandomizeName = true; //default true to enable security feature
- if (version >= 15)
- _dnsServer.QnameMinimization = bR.ReadBoolean();
- else
- _dnsServer.QnameMinimization = true; //default true to enable privacy feature
- if (version >= 20)
- {
- _dnsServer.QpmLimitRequests = bR.ReadInt32();
- _dnsServer.QpmLimitErrors = bR.ReadInt32();
- _dnsServer.QpmLimitSampleMinutes = bR.ReadInt32();
- _dnsServer.QpmLimitIPv4PrefixLength = bR.ReadInt32();
- _dnsServer.QpmLimitIPv6PrefixLength = bR.ReadInt32();
- }
- else if (version >= 17)
- {
- _dnsServer.QpmLimitRequests = bR.ReadInt32();
- _dnsServer.QpmLimitSampleMinutes = bR.ReadInt32();
- _ = bR.ReadInt32(); //read obsolete value _dnsServer.QpmLimitSamplingIntervalInMinutes
- }
- else
- {
- _dnsServer.QpmLimitRequests = 0;
- _dnsServer.QpmLimitErrors = 0;
- _dnsServer.QpmLimitSampleMinutes = 1;
- _dnsServer.QpmLimitIPv4PrefixLength = 24;
- _dnsServer.QpmLimitIPv6PrefixLength = 56;
- }
- if (version >= 13)
- {
- _dnsServer.ServeStale = bR.ReadBoolean();
- _dnsServer.CacheZoneManager.ServeStaleTtl = bR.ReadUInt32();
- }
- else
- {
- _dnsServer.ServeStale = true;
- _dnsServer.CacheZoneManager.ServeStaleTtl = CacheZoneManager.SERVE_STALE_TTL;
- }
- if (version >= 9)
- {
- _dnsServer.CachePrefetchEligibility = bR.ReadInt32();
- _dnsServer.CachePrefetchTrigger = bR.ReadInt32();
- _dnsServer.CachePrefetchSampleIntervalInMinutes = bR.ReadInt32();
- _dnsServer.CachePrefetchSampleEligibilityHitsPerHour = bR.ReadInt32();
- }
- else
- {
- _dnsServer.CachePrefetchEligibility = 2;
- _dnsServer.CachePrefetchTrigger = 9;
- _dnsServer.CachePrefetchSampleIntervalInMinutes = 5;
- _dnsServer.CachePrefetchSampleEligibilityHitsPerHour = 30;
- }
- NetProxyType proxyType = (NetProxyType)bR.ReadByte();
- if (proxyType != NetProxyType.None)
- {
- string address = bR.ReadShortString();
- int port = bR.ReadInt32();
- NetworkCredential credential = null;
- if (bR.ReadBoolean()) //credential set
- credential = new NetworkCredential(bR.ReadShortString(), bR.ReadShortString());
- _dnsServer.Proxy = NetProxy.CreateProxy(proxyType, address, port, credential);
- if (version >= 10)
- {
- int count = bR.ReadByte();
- List<NetProxyBypassItem> bypassList = new List<NetProxyBypassItem>(count);
- for (int i = 0; i < count; i++)
- bypassList.Add(new NetProxyBypassItem(bR.ReadShortString()));
- _dnsServer.Proxy.BypassList = bypassList;
- }
- else
- {
- _dnsServer.Proxy.BypassList = null;
- }
- }
- else
- {
- _dnsServer.Proxy = null;
- }
- {
- int count = bR.ReadByte();
- if (count > 0)
- {
- NameServerAddress[] forwarders = new NameServerAddress[count];
- for (int i = 0; i < count; i++)
- forwarders[i] = new NameServerAddress(bR);
- _dnsServer.Forwarders = forwarders;
- }
- }
- if (version <= 10)
- {
- DnsTransportProtocol forwarderProtocol = (DnsTransportProtocol)bR.ReadByte();
- if (_dnsServer.Forwarders != null)
- {
- List<NameServerAddress> forwarders = new List<NameServerAddress>();
- foreach (NameServerAddress forwarder in _dnsServer.Forwarders)
- {
- if (forwarder.Protocol == forwarderProtocol)
- forwarders.Add(forwarder);
- else
- forwarders.Add(forwarder.ChangeProtocol(forwarderProtocol));
- }
- _dnsServer.Forwarders = forwarders;
- }
- }
- {
- int count = bR.ReadByte();
- if (count > 0)
- {
- if (version > 2)
- {
- for (int i = 0; i < count; i++)
- LoadCredentials(bR.ReadShortString(), bR.ReadShortString());
- }
- else
- {
- for (int i = 0; i < count; i++)
- SetCredentials(bR.ReadShortString(), bR.ReadShortString());
- }
- }
- }
- if (version <= 6)
- {
- int count = bR.ReadInt32();
- _configDisabledZones = new List<string>(count);
- for (int i = 0; i < count; i++)
- {
- string domain = bR.ReadShortString();
- _configDisabledZones.Add(domain);
- }
- }
- if (version >= 18)
- _dnsServer.EnableBlocking = bR.ReadBoolean();
- else
- _dnsServer.EnableBlocking = true;
- if (version >= 18)
- _dnsServer.BlockingType = (DnsServerBlockingType)bR.ReadByte();
- else if (version >= 16)
- _dnsServer.BlockingType = bR.ReadBoolean() ? DnsServerBlockingType.NxDomain : DnsServerBlockingType.AnyAddress;
- else
- _dnsServer.BlockingType = DnsServerBlockingType.AnyAddress;
- if (version >= 18)
- {
- //read custom blocking addresses
- int count = bR.ReadByte();
- if (count > 0)
- {
- List<DnsARecordData> dnsARecords = new List<DnsARecordData>();
- List<DnsAAAARecordData> dnsAAAARecords = new List<DnsAAAARecordData>();
- for (int i = 0; i < count; i++)
- {
- IPAddress customAddress = IPAddressExtension.Parse(bR);
- switch (customAddress.AddressFamily)
- {
- case AddressFamily.InterNetwork:
- dnsARecords.Add(new DnsARecordData(customAddress));
- break;
- case AddressFamily.InterNetworkV6:
- dnsAAAARecords.Add(new DnsAAAARecordData(customAddress));
- break;
- }
- }
- _dnsServer.CustomBlockingARecords = dnsARecords;
- _dnsServer.CustomBlockingAAAARecords = dnsAAAARecords;
- }
- }
- else
- {
- _dnsServer.CustomBlockingARecords = null;
- _dnsServer.CustomBlockingAAAARecords = null;
- }
- if (version > 4)
- {
- //read block list urls
- int count = bR.ReadByte();
- for (int i = 0; i < count; i++)
- {
- string listUrl = bR.ReadShortString();
- if (listUrl.StartsWith("!"))
- _dnsServer.BlockListZoneManager.AllowListUrls.Add(new Uri(listUrl.Substring(1)));
- else
- _dnsServer.BlockListZoneManager.BlockListUrls.Add(new Uri(listUrl));
- }
- _blockListLastUpdatedOn = bR.ReadDateTime();
- if (version >= 13)
- _blockListUpdateIntervalHours = bR.ReadInt32();
- }
- else
- {
- _dnsServer.BlockListZoneManager.AllowListUrls.Clear();
- _dnsServer.BlockListZoneManager.BlockListUrls.Clear();
- _blockListLastUpdatedOn = DateTime.MinValue;
- _blockListUpdateIntervalHours = 24;
- }
- if (version >= 11)
- {
- int count = bR.ReadByte();
- if (count > 0)
- {
- IPEndPoint[] localEndPoints = new IPEndPoint[count];
- for (int i = 0; i < count; i++)
- localEndPoints[i] = (IPEndPoint)EndPointExtension.Parse(bR);
- _dnsServer.LocalEndPoints = localEndPoints;
- }
- }
- else if (version >= 6)
- {
- int count = bR.ReadByte();
- if (count > 0)
- {
- IPEndPoint[] localEndPoints = new IPEndPoint[count];
- for (int i = 0; i < count; i++)
- localEndPoints[i] = new IPEndPoint(IPAddressExtension.Parse(bR), 53);
- _dnsServer.LocalEndPoints = localEndPoints;
- }
- }
- else
- {
- _dnsServer.LocalEndPoints = new IPEndPoint[] { new IPEndPoint(IPAddress.Any, 53), new IPEndPoint(IPAddress.IPv6Any, 53) };
- }
- if (version >= 8)
- {
- _dnsServer.EnableDnsOverHttp = bR.ReadBoolean();
- _dnsServer.EnableDnsOverTls = bR.ReadBoolean();
- _dnsServer.EnableDnsOverHttps = bR.ReadBoolean();
- _dnsTlsCertificatePath = bR.ReadShortString();
- _dnsTlsCertificatePassword = bR.ReadShortString();
- if (_dnsTlsCertificatePath.Length == 0)
- _dnsTlsCertificatePath = null;
- if (_dnsTlsCertificatePath != null)
- {
- try
- {
- LoadDnsTlsCertificate(_dnsTlsCertificatePath, _dnsTlsCertificatePassword);
- }
- catch (Exception ex)
- {
- _log.Write("DNS Server encountered an error while loading DNS Server TLS certificate: " + _dnsTlsCertificatePath + "\r\n" + ex.ToString());
- }
- StartTlsCertificateUpdateTimer();
- }
- }
- else
- {
- _dnsServer.EnableDnsOverHttp = false;
- _dnsServer.EnableDnsOverTls = false;
- _dnsServer.EnableDnsOverHttps = false;
- _dnsTlsCertificatePath = string.Empty;
- _dnsTlsCertificatePassword = string.Empty;
- }
- if (version >= 19)
- {
- _dnsServer.CacheZoneManager.MinimumRecordTtl = bR.ReadUInt32();
- _dnsServer.CacheZoneManager.MaximumRecordTtl = bR.ReadUInt32();
- _dnsServer.CacheZoneManager.NegativeRecordTtl = bR.ReadUInt32();
- _dnsServer.CacheZoneManager.FailureRecordTtl = bR.ReadUInt32();
- }
- else
- {
- _dnsServer.CacheZoneManager.MinimumRecordTtl = CacheZoneManager.MINIMUM_RECORD_TTL;
- _dnsServer.CacheZoneManager.MaximumRecordTtl = CacheZoneManager.MAXIMUM_RECORD_TTL;
- _dnsServer.CacheZoneManager.NegativeRecordTtl = CacheZoneManager.NEGATIVE_RECORD_TTL;
- _dnsServer.CacheZoneManager.FailureRecordTtl = CacheZoneManager.FAILURE_RECORD_TTL;
- }
- if (version >= 21)
- {
- int count = bR.ReadByte();
- Dictionary<string, TsigKey> tsigKeys = new Dictionary<string, TsigKey>(count);
- for (int i = 0; i < count; i++)
- {
- string keyName = bR.ReadShortString();
- string sharedSecret = bR.ReadShortString();
- TsigAlgorithm algorithm = (TsigAlgorithm)bR.ReadByte();
- tsigKeys.Add(keyName, new TsigKey(keyName, sharedSecret, algorithm));
- }
- _dnsServer.TsigKeys = tsigKeys;
- }
- else if (version >= 20)
- {
- int count = bR.ReadByte();
- Dictionary<string, TsigKey> tsigKeys = new Dictionary<string, TsigKey>(count);
- for (int i = 0; i < count; i++)
- {
- string keyName = bR.ReadShortString();
- string sharedSecret = bR.ReadShortString();
- tsigKeys.Add(keyName, new TsigKey(keyName, sharedSecret, TsigAlgorithm.HMAC_SHA256));
- }
- _dnsServer.TsigKeys = tsigKeys;
- }
- else
- {
- _dnsServer.TsigKeys = null;
- }
- if (version >= 22)
- _dnsServer.NsRevalidation = bR.ReadBoolean();
- else
- _dnsServer.NsRevalidation = false; //default false since some badly configured websites fail to load
- if (version >= 23)
- {
- _dnsServer.AllowTxtBlockingReport = bR.ReadBoolean();
- _zonesApi.DefaultRecordTtl = bR.ReadUInt32();
- }
- else
- {
- _dnsServer.AllowTxtBlockingReport = true;
- _zonesApi.DefaultRecordTtl = 3600;
- }
- if (version >= 24)
- {
- _webServiceUseSelfSignedTlsCertificate = bR.ReadBoolean();
- SelfSignedCertCheck(false);
- }
- else
- {
- _webServiceUseSelfSignedTlsCertificate = false;
- }
- if (version >= 25)
- _dnsServer.UdpPayloadSize = bR.ReadUInt16();
- else
- _dnsServer.UdpPayloadSize = DnsDatagram.EDNS_DEFAULT_UDP_PAYLOAD_SIZE;
- if (version >= 26)
- {
- _dnsServer.DnssecValidation = bR.ReadBoolean();
- _dnsServer.ResolverRetries = bR.ReadInt32();
- _dnsServer.ResolverTimeout = bR.ReadInt32();
- _dnsServer.ResolverMaxStackCount = bR.ReadInt32();
- _dnsServer.ForwarderRetries = bR.ReadInt32();
- _dnsServer.ForwarderTimeout = bR.ReadInt32();
- _dnsServer.ForwarderConcurrency = bR.ReadInt32();
- _dnsServer.ClientTimeout = bR.ReadInt32();
- _dnsServer.TcpSendTimeout = bR.ReadInt32();
- _dnsServer.TcpReceiveTimeout = bR.ReadInt32();
- }
- else
- {
- _dnsServer.DnssecValidation = true;
- CreateForwarderZoneToDisableDnssecForNTP();
- _dnsServer.ResolverRetries = 3;
- _dnsServer.ResolverTimeout = 2000;
- _dnsServer.ResolverMaxStackCount = 16;
- _dnsServer.ForwarderRetries = 3;
- _dnsServer.ForwarderTimeout = 2000;
- _dnsServer.ForwarderConcurrency = 2;
- _dnsServer.ClientTimeout = 4000;
- _dnsServer.TcpSendTimeout = 10000;
- _dnsServer.TcpReceiveTimeout = 10000;
- }
- break;
- default:
- throw new InvalidDataException("DNS Server config version not supported.");
- }
- }
- _log.Write("DNS Server config file was loaded: " + configFile);
- if (passwordResetOption)
- {
- SetCredentials("admin", "admin");
- _log.Write("DNS Server reset password for user: admin");
- SaveConfigFile();
- try
- {
- File.Delete(configFile);
- }
- catch
- { }
- }
- if (version <= 6)
- SaveConfigFile(); //save as new config version to avoid loading old version next time
- }
- catch (FileNotFoundException)
- {
- _log.Write("DNS Server config file was not found: " + configFile);
- _log.Write("DNS Server is restoring default config file.");
- string serverDomain = Environment.GetEnvironmentVariable("DNS_SERVER_DOMAIN");
- if (!string.IsNullOrEmpty(serverDomain))
- _dnsServer.ServerDomain = serverDomain;
- string adminPassword = Environment.GetEnvironmentVariable("DNS_SERVER_ADMIN_PASSWORD");
- string adminPasswordFile = Environment.GetEnvironmentVariable("DNS_SERVER_ADMIN_PASSWORD_FILE");
- if (!string.IsNullOrEmpty(adminPassword))
- {
- SetCredentials("admin", adminPassword);
- }
- else if (!string.IsNullOrEmpty(adminPasswordFile))
- {
- try
- {
- using (StreamReader sR = new StreamReader(adminPasswordFile, true))
- {
- string password = sR.ReadLine();
- SetCredentials("admin", password);
- }
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- SetCredentials("admin", "admin");
- }
- }
- else
- {
- SetCredentials("admin", "admin");
- }
- string strPreferIPv6 = Environment.GetEnvironmentVariable("DNS_SERVER_PREFER_IPV6");
- if (!string.IsNullOrEmpty(strPreferIPv6))
- _dnsServer.PreferIPv6 = bool.Parse(strPreferIPv6);
- string strDnsOverHttp = Environment.GetEnvironmentVariable("DNS_SERVER_OPTIONAL_PROTOCOL_DNS_OVER_HTTP");
- if (!string.IsNullOrEmpty(strDnsOverHttp))
- _dnsServer.EnableDnsOverHttp = bool.Parse(strDnsOverHttp);
- string strRecursion = Environment.GetEnvironmentVariable("DNS_SERVER_RECURSION");
- if (!string.IsNullOrEmpty(strRecursion))
- _dnsServer.Recursion = Enum.Parse<DnsServerRecursion>(strRecursion, true);
- else
- _dnsServer.Recursion = DnsServerRecursion.AllowOnlyForPrivateNetworks; //default for security reasons
- string strRecursionDeniedNetworks = Environment.GetEnvironmentVariable("DNS_SERVER_RECURSION_DENIED_NETWORKS");
- if (!string.IsNullOrEmpty(strRecursionDeniedNetworks))
- {
- string[] strRecursionDeniedNetworkAddresses = strRecursionDeniedNetworks.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- NetworkAddress[] networks = new NetworkAddress[strRecursionDeniedNetworkAddresses.Length];
- for (int i = 0; i < networks.Length; i++)
- networks[i] = NetworkAddress.Parse(strRecursionDeniedNetworkAddresses[i].Trim());
- _dnsServer.RecursionDeniedNetworks = networks;
- }
- string strRecursionAllowedNetworks = Environment.GetEnvironmentVariable("DNS_SERVER_RECURSION_ALLOWED_NETWORKS");
- if (!string.IsNullOrEmpty(strRecursionAllowedNetworks))
- {
- string[] strRecursionAllowedNetworkAddresses = strRecursionAllowedNetworks.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- NetworkAddress[] networks = new NetworkAddress[strRecursionAllowedNetworkAddresses.Length];
- for (int i = 0; i < networks.Length; i++)
- networks[i] = NetworkAddress.Parse(strRecursionAllowedNetworkAddresses[i].Trim());
- _dnsServer.RecursionAllowedNetworks = networks;
- }
- string strEnableBlocking = Environment.GetEnvironmentVariable("DNS_SERVER_ENABLE_BLOCKING");
- if (!string.IsNullOrEmpty(strEnableBlocking))
- _dnsServer.EnableBlocking = bool.Parse(strEnableBlocking);
- string strAllowTxtBlockingReport = Environment.GetEnvironmentVariable("DNS_SERVER_ALLOW_TXT_BLOCKING_REPORT");
- if (!string.IsNullOrEmpty(strAllowTxtBlockingReport))
- _dnsServer.AllowTxtBlockingReport = bool.Parse(strAllowTxtBlockingReport);
- string strForwarders = Environment.GetEnvironmentVariable("DNS_SERVER_FORWARDERS");
- if (!string.IsNullOrEmpty(strForwarders))
- {
- DnsTransportProtocol forwarderProtocol;
- string strForwarderProtocol = Environment.GetEnvironmentVariable("DNS_SERVER_FORWARDER_PROTOCOL");
- if (string.IsNullOrEmpty(strForwarderProtocol))
- forwarderProtocol = DnsTransportProtocol.Udp;
- else
- forwarderProtocol = Enum.Parse<DnsTransportProtocol>(strForwarderProtocol, true);
- List<NameServerAddress> forwarders = new List<NameServerAddress>();
- string[] strForwardersAddresses = strForwarders.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
- foreach (string strForwarderAddress in strForwardersAddresses)
- forwarders.Add(new NameServerAddress(strForwarderAddress.Trim(), forwarderProtocol));
- _dnsServer.Forwarders = forwarders;
- }
- _dnsServer.RandomizeName = true; //default true to enable security feature
- _dnsServer.QnameMinimization = true; //default true to enable privacy feature
- _dnsServer.NsRevalidation = false; //default false since some badly configured websites fail to load
- _dnsServer.DnssecValidation = true;
- CreateForwarderZoneToDisableDnssecForNTP();
- SaveConfigFile();
- }
- catch (Exception ex)
- {
- _log.Write("DNS Server encountered an error while loading config file: " + configFile + "\r\n" + ex.ToString());
- _log.Write("Note: You may try deleting the config file to fix this issue. However, you will lose DNS settings but, zone data wont be affected.");
- throw;
- }
- }
- private void CreateForwarderZoneToDisableDnssecForNTP()
- {
- if (Environment.OSVersion.Platform == PlatformID.Unix)
- {
- //adding a conditional forwarder zone for disabling DNSSEC validation for ntp.org so that systems with no real-time clock can sync time
- string ntpDomain = "ntp.org";
- string fwdRecordComments = "This forwarder zone was automatically created to disable DNSSEC validation for ntp.org to allow systems with no real-time clock (e.g. Raspberry Pi) to sync time via NTP when booting.";
- if (_dnsServer.AuthZoneManager.CreateForwarderZone(ntpDomain, DnsTransportProtocol.Udp, "this-server", false, NetProxyType.None, null, 0, null, null, fwdRecordComments) is not null)
- {
- Directory.CreateDirectory(Path.Combine(_dnsServer.ConfigFolder, "zones"));
- _dnsServer.AuthZoneManager.SaveZoneFile(ntpDomain);
- }
- }
- }
- private void SaveConfigFile()
- {
- string configFile = Path.Combine(_configFolder, "dns.config");
- using (MemoryStream mS = new MemoryStream())
- {
- //serialize config
- BinaryWriter bW = new BinaryWriter(mS);
- bW.Write(Encoding.ASCII.GetBytes("DS")); //format
- bW.Write((byte)26); //version
- bW.WriteShortString(_dnsServer.ServerDomain);
- bW.Write(_webServiceHttpPort);
- {
- bW.Write(Convert.ToByte(_webServiceLocalAddresses.Count));
- foreach (IPAddress localAddress in _webServiceLocalAddresses)
- localAddress.WriteTo(bW);
- }
- bW.Write(_webServiceTlsPort);
- bW.Write(_webServiceEnableTls);
- bW.Write(_webServiceHttpToTlsRedirect);
- if (_webServiceTlsCertificatePath == null)
- bW.WriteShortString(string.Empty);
- else
- bW.WriteShortString(_webServiceTlsCertificatePath);
- if (_webServiceTlsCertificatePassword == null)
- bW.WriteShortString(string.Empty);
- else
- bW.WriteShortString(_webServiceTlsCertificatePassword);
- bW.Write(_dnsServer.PreferIPv6);
- bW.Write(_dnsServer.QueryLogManager != null); //logQueries
- bW.Write(_dnsServer.StatsManager.MaxStatFileDays);
- bW.Write((byte)_dnsServer.Recursion);
- if (_dnsServer.RecursionDeniedNetworks is null)
- {
- bW.Write((byte)0);
- }
- else
- {
- bW.Write(Convert.ToByte(_dnsServer.RecursionDeniedNetworks.Count));
- foreach (NetworkAddress networkAddress in _dnsServer.RecursionDeniedNetworks)
- networkAddress.WriteTo(bW);
- }
- if (_dnsServer.RecursionAllowedNetworks is null)
- {
- bW.Write((byte)0);
- }
- else
- {
- bW.Write(Convert.ToByte(_dnsServer.RecursionAllowedNetworks.Count));
- foreach (NetworkAddress networkAddress in _dnsServer.RecursionAllowedNetworks)
- networkAddress.WriteTo(bW);
- }
- bW.Write(_dnsServer.RandomizeName);
- bW.Write(_dnsServer.QnameMinimization);
- bW.Write(_dnsServer.QpmLimitRequests);
- bW.Write(_dnsServer.QpmLimitErrors);
- bW.Write(_dnsServer.QpmLimitSampleMinutes);
- bW.Write(_dnsServer.QpmLimitIPv4PrefixLength);
- bW.Write(_dnsServer.QpmLimitIPv6PrefixLength);
- bW.Write(_dnsServer.ServeStale);
- bW.Write(_dnsServer.CacheZoneManager.ServeStaleTtl);
- bW.Write(_dnsServer.CachePrefetchEligibility);
- bW.Write(_dnsServer.CachePrefetchTrigger);
- bW.Write(_dnsServer.CachePrefetchSampleIntervalInMinutes);
- bW.Write(_dnsServer.CachePrefetchSampleEligibilityHitsPerHour);
- if (_dnsServer.Proxy == null)
- {
- bW.Write((byte)NetProxyType.None);
- }
- else
- {
- bW.Write((byte)_dnsServer.Proxy.Type);
- bW.WriteShortString(_dnsServer.Proxy.Address);
- bW.Write(_dnsServer.Proxy.Port);
- NetworkCredential credential = _dnsServer.Proxy.Credential;
- if (credential == null)
- {
- bW.Write(false);
- }
- else
- {
- bW.Write(true);
- bW.WriteShortString(credential.UserName);
- bW.WriteShortString(credential.Password);
- }
- //bypass list
- {
- bW.Write(Convert.ToByte(_dnsServer.Proxy.BypassList.Count));
- foreach (NetProxyBypassItem item in _dnsServer.Proxy.BypassList)
- bW.WriteShortString(item.Value);
- }
- }
- if (_dnsServer.Forwarders == null)
- {
- bW.Write((byte)0);
- }
- else
- {
- bW.Write(Convert.ToByte(_dnsServer.Forwarders.Count));
- foreach (NameServerAddress forwarder in _dnsServer.Forwarders)
- forwarder.WriteTo(bW);
- }
- {
- bW.Write(Convert.ToByte(_credentials.Count));
- foreach (KeyValuePair<string, string> credential in _credentials)
- {
- bW.WriteShortString(credential.Key);
- bW.WriteShortString(credential.Value);
- }
- }
- //block list
- bW.Write(_dnsServer.EnableBlocking);
- bW.Write((byte)_dnsServer.BlockingType);
- {
- bW.Write(Convert.ToByte(_dnsServer.CustomBlockingARecords.Count + _dnsServer.CustomBlockingAAAARecords.Count));
- foreach (DnsARecordData record in _dnsServer.CustomBlockingARecords)
- record.Address.WriteTo(bW);
- foreach (DnsAAAARecordData record in _dnsServer.CustomBlockingAAAARecords)
- record.Address.WriteTo(bW);
- }
- {
- bW.Write(Convert.ToByte(_dnsServer.BlockListZoneManager.AllowListUrls.Count + _dnsServer.BlockListZoneManager.BlockListUrls.Count));
- foreach (Uri allowListUrl in _dnsServer.BlockListZoneManager.AllowListUrls)
- bW.WriteShortString("!" + allowListUrl.AbsoluteUri);
- foreach (Uri blockListUrl in _dnsServer.BlockListZoneManager.BlockListUrls)
- bW.WriteShortString(blockListUrl.AbsoluteUri);
- bW.Write(_blockListLastUpdatedOn);
- bW.Write(_blockListUpdateIntervalHours);
- }
- {
- bW.Write(Convert.ToByte(_dnsServer.LocalEndPoints.Count));
- foreach (IPEndPoint localEP in _dnsServer.LocalEndPoints)
- localEP.WriteTo(bW);
- }
- bW.Write(_dnsServer.EnableDnsOverHttp);
- bW.Write(_dnsServer.EnableDnsOverTls);
- bW.Write(_dnsServer.EnableDnsOverHttps);
- if (_dnsTlsCertificatePath == null)
- bW.WriteShortString(string.Empty);
- else
- bW.WriteShortString(_dnsTlsCertificatePath);
- if (_dnsTlsCertificatePassword == null)
- bW.WriteShortString(string.Empty);
- else
- bW.WriteShortString(_dnsTlsCertificatePassword);
- bW.Write(_dnsServer.CacheZoneManager.MinimumRecordTtl);
- bW.Write(_dnsServer.CacheZoneManager.MaximumRecordTtl);
- bW.Write(_dnsServer.CacheZoneManager.NegativeRecordTtl);
- bW.Write(_dnsServer.CacheZoneManager.FailureRecordTtl);
- if (_dnsServer.TsigKeys is null)
- {
- bW.Write((byte)0);
- }
- else
- {
- bW.Write(Convert.ToByte(_dnsServer.TsigKeys.Count));
- foreach (KeyValuePair<string, TsigKey> tsigKey in _dnsServer.TsigKeys)
- {
- bW.WriteShortString(tsigKey.Key);
- bW.WriteShortString(tsigKey.Value.SharedSecret);
- bW.Write((byte)tsigKey.Value.Algorithm);
- }
- }
- bW.Write(_dnsServer.NsRevalidation);
- bW.Write(_dnsServer.AllowTxtBlockingReport);
- bW.Write(_zonesApi.DefaultRecordTtl);
- bW.Write(_webServiceUseSelfSignedTlsCertificate);
- bW.Write(_dnsServer.UdpPayloadSize);
- bW.Write(_dnsServer.DnssecValidation);
- bW.Write(_dnsServer.ResolverRetries);
- bW.Write(_dnsServer.ResolverTimeout);
- bW.Write(_dnsServer.ResolverMaxStackCount);
- bW.Write(_dnsServer.ForwarderRetries);
- bW.Write(_dnsServer.ForwarderTimeout);
- bW.Write(_dnsServer.ForwarderConcurrency);
- bW.Write(_dnsServer.ClientTimeout);
- bW.Write(_dnsServer.TcpSendTimeout);
- bW.Write(_dnsServer.TcpReceiveTimeout);
- //write config
- mS.Position = 0;
- using (FileStream fS = new FileStream(configFile, FileMode.Create, FileAccess.Write))
- {
- mS.CopyTo(fS);
- }
- }
- _log.Write("DNS Server config file was saved: " + configFile);
- }
- #endregion
- #region web service start stop
- private void StartDnsWebService()
- {
- int acceptTasks = Math.Max(1, Environment.ProcessorCount);
- //HTTP service
- try
- {
- string webServiceHostname = null;
- _webService = new HttpListener();
- IPAddress httpAddress = null;
- foreach (IPAddress webServiceLocalAddress in _webServiceLocalAddresses)
- {
- string host;
- if (webServiceLocalAddress.Equals(IPAddress.Any))
- {
- host = "+";
- httpAddress = IPAddress.Loopback;
- }
- else if (webServiceLocalAddress.Equals(IPAddress.IPv6Any))
- {
- host = "+";
- if ((httpAddress == null) || !IPAddress.IsLoopback(httpAddress))
- httpAddress = IPAddress.IPv6Loopback;
- }
- else
- {
- if (webServiceLocalAddress.AddressFamily == AddressFamily.InterNetworkV6)
- host = "[" + webServiceLocalAddress.ToString() + "]";
- else
- host = webServiceLocalAddress.ToString();
- if (httpAddress == null)
- httpAddress = webServiceLocalAddress;
- if (webServiceHostname == null)
- webServiceHostname = host;
- }
- _webService.Prefixes.Add("http://" + host + ":" + _webServiceHttpPort + "/");
- }
- _webService.Start();
- if (httpAddress == null)
- httpAddress = IPAddress.Loopback;
- _webServiceHttpEP = new IPEndPoint(httpAddress, _webServiceHttpPort);
- _webServiceHostname = webServiceHostname ?? Environment.MachineName.ToLower();
- }
- catch (Exception ex)
- {
- _log.Write("Web Service failed to bind using default hostname. Attempting to bind again using 'localhost' hostname.\r\n" + ex.ToString());
- try
- {
- _webService = new HttpListener();
- _webService.Prefixes.Add("http://localhost:" + _webServiceHttpPort + "/");
- _webService.Prefixes.Add("http://127.0.0.1:" + _webServiceHttpPort + "/");
- _webService.Start();
- }
- catch
- {
- _webService = new HttpListener();
- _webService.Prefixes.Add("http://localhost:" + _webServiceHttpPort + "/");
- _webService.Start();
- }
- _webServiceHttpEP = new IPEndPoint(IPAddress.Loopback, _webServiceHttpPort);
- _webServiceHostname = "localhost";
- }
- _webService.IgnoreWriteExceptions = true;
- for (int i = 0; i < acceptTasks; i++)
- {
- _ = Task.Factory.StartNew(delegate ()
- {
- return AcceptWebRequestAsync();
- }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _webServiceTaskScheduler);
- }
- _log.Write(new IPEndPoint(IPAddress.Any, _webServiceHttpPort), "HTTP Web Service was started successfully.");
- //TLS service
- if (_webServiceEnableTls && (_webServiceTlsCertificate != null))
- {
- List<Socket> webServiceTlsListeners = new List<Socket>();
- try
- {
- foreach (IPAddress webServiceLocalAddress in _webServiceLocalAddresses)
- {
- Socket tlsListener = new Socket(webServiceLocalAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- tlsListener.Bind(new IPEndPoint(webServiceLocalAddress, _webServiceTlsPort));
- tlsListener.Listen(10);
- webServiceTlsListeners.Add(tlsListener);
- }
- foreach (Socket tlsListener in webServiceTlsListeners)
- {
- for (int i = 0; i < acceptTasks; i++)
- {
- _ = Task.Factory.StartNew(delegate ()
- {
- return AcceptTlsWebRequestAsync(tlsListener);
- }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _webServiceTaskScheduler);
- }
- }
- _webServiceTlsListeners = webServiceTlsListeners;
- _log.Write(new IPEndPoint(IPAddress.Any, _webServiceHttpPort), "TLS Web Service was started successfully.");
- }
- catch (Exception ex)
- {
- _log.Write("TLS Web Service failed to start.\r\n" + ex.ToString());
- foreach (Socket tlsListener in webServiceTlsListeners)
- tlsListener.Dispose();
- }
- }
- }
- private void StopDnsWebService()
- {
- _webService.Stop();
- if (_webServiceTlsListeners != null)
- {
- foreach (Socket tlsListener in _webServiceTlsListeners)
- tlsListener.Dispose();
- _webServiceTlsListeners = null;
- }
- }
- #endregion
- #endregion
- #region public
- public void Start()
- {
- if (_disposed)
- throw new ObjectDisposedException("WebService");
- if (_state != ServiceState.Stopped)
- throw new InvalidOperationException("Web Service is already running.");
- _state = ServiceState.Starting;
- try
- {
- //get initial server domain
- string dnsServerDomain = Environment.MachineName.ToLower();
- if (!DnsClient.IsDomainNameValid(dnsServerDomain))
- dnsServerDomain = "dns-server-1"; //use this name instead since machine name is not a valid domain name
- //init dns server
- _dnsServer = new DnsServer(dnsServerDomain, _configFolder, Path.Combine(_appFolder, "dohwww"), _log);
- //init dhcp server
- _dhcpServer = new DhcpServer(Path.Combine(_configFolder, "scopes"), _log);
- _dhcpServer.AuthZoneManager = _dnsServer.AuthZoneManager;
- //load config
- LoadConfigFile();
- //load all dns applications
- _dnsServer.DnsApplicationManager.LoadAllApplications();
- //load all zones files
- _dnsServer.AuthZoneManager.LoadAllZoneFiles();
- //disable zones from old config format
- if (_configDisabledZones != null)
- {
- foreach (string domain in _configDisabledZones)
- {
- AuthZoneInfo zoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(domain);
- if (zoneInfo is not null)
- {
- zoneInfo.Disabled = true;
- _dnsServer.AuthZoneManager.SaveZoneFile(zoneInfo.Name);
- }
- }
- }
- //load allowed zone and blocked zone
- _dnsServer.AllowedZoneManager.LoadAllowedZoneFile();
- _dnsServer.BlockedZoneManager.LoadBlockedZoneFile();
- //load block list zone async
- if (_dnsServer.BlockListZoneManager.BlockListUrls.Count > 0)
- {
- ThreadPool.QueueUserWorkItem(delegate (object state)
- {
- try
- {
- _dnsServer.BlockListZoneManager.LoadBlockLists();
- StartBlockListUpdateTimer();
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- });
- }
- //start dns and dhcp
- _dnsServer.Start();
- _dhcpServer.Start();
- //start web service
- StartDnsWebService();
- _state = ServiceState.Running;
- _log.Write("DNS Server (v" + _currentVersion.ToString() + ") was started successfully.");
- }
- catch (Exception ex)
- {
- _log.Write("Failed to start DNS Server (v" + _currentVersion.ToString() + ")\r\n" + ex.ToString());
- throw;
- }
- }
- public void Stop()
- {
- if (_state != ServiceState.Running)
- return;
- _state = ServiceState.Stopping;
- try
- {
- StopDnsWebService();
- _dnsServer.Dispose();
- _dhcpServer.Dispose();
- StopBlockListUpdateTimer();
- StopTlsCertificateUpdateTimer();
- if (_temporaryDisableBlockingTimer is not null)
- _temporaryDisableBlockingTimer.Dispose();
- _state = ServiceState.Stopped;
- _log.Write("DNS Server (v" + _currentVersion.ToString() + ") was stopped successfully.");
- }
- catch (Exception ex)
- {
- _log.Write("Failed to stop DNS Server (v" + _currentVersion.ToString() + ")\r\n" + ex.ToString());
- throw;
- }
- }
- #endregion
- #region properties
- internal LogManager Log
- { get { return _log; } }
- internal DnsServer DnsServer
- { get { return _dnsServer; } }
- internal DhcpServer DhcpServer
- { get { return _dhcpServer; } }
- public string ConfigFolder
- { get { return _configFolder; } }
- public int WebServiceHttpPort
- { get { return _webServiceHttpPort; } }
- public int WebServiceTlsPort
- { get { return _webServiceTlsPort; } }
- public string WebServiceHostname
- { get { return _webServiceHostname; } }
- #endregion
- }
- }
|