-
-
Notifications
You must be signed in to change notification settings - Fork 713
Expand file tree
/
Copy pathDnsWebService.cs
More file actions
2925 lines (2422 loc) · 132 KB
/
Copy pathDnsWebService.cs
File metadata and controls
2925 lines (2422 loc) · 132 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Technitium DNS Server
Copyright (C) 2026 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.Auth;
using DnsServerCore.Cluster;
using DnsServerCore.Dhcp;
using DnsServerCore.Dns;
using DnsServerCore.Dns.Applications;
using DnsServerCore.Dns.Dnssec;
using DnsServerCore.Dns.Zones;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Net.Quic;
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.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using TechnitiumLibrary;
using TechnitiumLibrary.IO;
using TechnitiumLibrary.Net;
using TechnitiumLibrary.Net.Dns;
using TechnitiumLibrary.Net.Dns.ClientConnection;
using TechnitiumLibrary.Net.Dns.ResourceRecords;
using TechnitiumLibrary.Net.Http.Client;
namespace DnsServerCore
{
public sealed partial class DnsWebService : IAsyncDisposable, IDisposable
{
#region variables
readonly static char[] commaSeparator = new char[] { ',' };
readonly Version _currentVersion;
readonly DateTime _uptimestamp = DateTime.UtcNow;
readonly string _appFolder;
readonly string _configFolder;
readonly LogManager _log;
readonly AuthManager _authManager;
readonly WebServiceApi _api;
readonly WebServiceDashboardApi _dashboardApi;
readonly WebServiceZonesApi _zonesApi;
readonly WebServiceOtherZonesApi _otherZonesApi;
readonly WebServiceAppsApi _appsApi;
readonly WebServiceSettingsApi _settingsApi;
readonly WebServiceDhcpApi _dhcpApi;
readonly WebServiceAuthApi _authApi;
readonly WebServiceClusterApi _clusterApi;
readonly WebServiceLogsApi _logsApi;
WebApplication _webService;
HttpClientNetworkHandler _ssoHttpHandler;
HttpClient _ssoHttpClient;
ClusterManager _clusterManager;
DnsServer _dnsServer;
DhcpServer _dhcpServer;
//web service
IReadOnlyList<IPAddress> _webServiceLocalAddresses = [IPAddress.Any, IPAddress.IPv6Any];
int _webServiceHttpPort = 5380;
int _webServiceTlsPort = 53443;
bool _webServiceEnableTls;
bool _webServiceEnableHttp3;
bool _webServiceHttpToTlsRedirect;
bool _webServiceUseSelfSignedTlsCertificate;
IReadOnlyCollection<NetworkAccessControl> _webServiceReverseProxyAddresses =
[
new NetworkAccessControl(IPAddress.Parse("127.0.0.0"), 8),
new NetworkAccessControl(IPAddress.Parse("10.0.0.0"), 8),
new NetworkAccessControl(IPAddress.Parse("100.64.0.0"), 10),
new NetworkAccessControl(IPAddress.Parse("169.254.0.0"), 16),
new NetworkAccessControl(IPAddress.Parse("172.16.0.0"), 12),
new NetworkAccessControl(IPAddress.Parse("192.168.0.0"), 16),
new NetworkAccessControl(IPAddress.Parse("2000::"), 3, true),
new NetworkAccessControl(IPAddress.IPv6Any, 0)
];
string _webServiceTlsCertificatePath;
string _webServiceTlsCertificatePassword;
string _webServiceRealIpHeader = "X-Real-IP";
Timer _tlsCertificateUpdateTimer;
const int TLS_CERTIFICATE_UPDATE_TIMER_INITIAL_INTERVAL = 60000;
const int TLS_CERTIFICATE_UPDATE_TIMER_INTERVAL = 60000;
DateTime _webServiceCertificateLastModifiedOn;
SslServerAuthenticationOptions _webServiceSslServerAuthenticationOptions;
bool _ssoEnabled;
List<string> _configDisabledZones;
readonly Lock _saveLock = new Lock();
bool _pendingSave;
readonly Timer _saveTimer;
const int SAVE_TIMER_INITIAL_INTERVAL = 5000;
bool _isRunning;
#endregion
#region constructor
public DnsWebService(bool isPortableApp, string configFolder = null, Uri updateCheckUri = null)
{
Assembly assembly = Assembly.GetExecutingAssembly();
_currentVersion = assembly.GetName().Version;
_appFolder = Path.GetDirectoryName(assembly.Location);
if (configFolder is null)
_configFolder = Path.Combine(_appFolder, "config");
else
_configFolder = configFolder;
Directory.CreateDirectory(_configFolder);
Directory.CreateDirectory(Path.Combine(_configFolder, "blocklists"));
Directory.CreateDirectory(Path.Combine(_configFolder, "zones"));
_log = new LogManager(isPortableApp, _configFolder);
_authManager = new AuthManager(_configFolder, _log);
_api = new WebServiceApi(this, updateCheckUri);
_dashboardApi = new WebServiceDashboardApi(this);
_zonesApi = new WebServiceZonesApi(this);
_otherZonesApi = new WebServiceOtherZonesApi(this);
_appsApi = new WebServiceAppsApi(this);
_settingsApi = new WebServiceSettingsApi(this);
_dhcpApi = new WebServiceDhcpApi(this);
_authApi = new WebServiceAuthApi(this);
_clusterApi = new WebServiceClusterApi(this);
_logsApi = new WebServiceLogsApi(this);
_saveTimer = new Timer(delegate (object state)
{
lock (_saveLock)
{
if (_pendingSave)
{
try
{
SaveConfigFileInternal();
_pendingSave = false;
}
catch (Exception ex)
{
_log.Write(ex);
//set timer to retry again
_saveTimer.Change(SAVE_TIMER_INITIAL_INTERVAL, Timeout.Infinite);
}
}
}
});
}
#endregion
#region IDisposable
bool _disposed;
public async ValueTask DisposeAsync()
{
if (_disposed)
return;
StopTlsCertificateUpdateTimer();
lock (_saveLock)
{
_saveTimer?.Dispose();
if (_pendingSave)
{
try
{
SaveConfigFileInternal();
}
catch (Exception ex)
{
_log.Write(ex);
}
finally
{
_pendingSave = false;
}
}
}
await StopAsync();
_authManager?.Dispose();
if (_log is not null)
await _log.DisposeAsync();
_disposed = true;
}
public void Dispose()
{
DisposeAsync().Sync();
}
#endregion
#region config
private void LoadConfigFile()
{
string webServiceConfigFile = Path.Combine(_configFolder, "webservice.config");
try
{
using (FileStream fS = new FileStream(webServiceConfigFile, FileMode.Open, FileAccess.Read))
{
ReadConfigFrom(fS);
}
_log.Write("Web Service config file was loaded: " + webServiceConfigFile);
}
catch (FileNotFoundException)
{
if (!TryLoadOldConfigFile())
{
//old config file did not exist; read environment variables and generate new config
CreateForwarderZoneToDisableDnssecForNTP();
//web service
string strWebServiceLocalAddresses = Environment.GetEnvironmentVariable("DNS_SERVER_WEB_SERVICE_LOCAL_ADDRESSES");
if (!string.IsNullOrEmpty(strWebServiceLocalAddresses))
_webServiceLocalAddresses = strWebServiceLocalAddresses.Split(IPAddress.Parse, commaSeparator);
string strWebServiceHttpPort = Environment.GetEnvironmentVariable("DNS_SERVER_WEB_SERVICE_HTTP_PORT");
if (!string.IsNullOrEmpty(strWebServiceHttpPort))
_webServiceHttpPort = int.Parse(strWebServiceHttpPort);
string webServiceTlsPort = Environment.GetEnvironmentVariable("DNS_SERVER_WEB_SERVICE_HTTPS_PORT");
if (!string.IsNullOrEmpty(webServiceTlsPort))
_webServiceTlsPort = int.Parse(webServiceTlsPort);
UdpClientConnection.SocketPoolExcludedPorts = [(ushort)_webServiceTlsPort];
string webServiceEnableTls = Environment.GetEnvironmentVariable("DNS_SERVER_WEB_SERVICE_ENABLE_HTTPS");
if (!string.IsNullOrEmpty(webServiceEnableTls))
_webServiceEnableTls = bool.Parse(webServiceEnableTls);
string webServiceTlsCertificatePassword = Environment.GetEnvironmentVariable("DNS_SERVER_WEB_SERVICE_TLS_CERTIFICATE_PASSWORD");
if (!string.IsNullOrEmpty(webServiceTlsCertificatePassword))
_webServiceTlsCertificatePassword = webServiceTlsCertificatePassword;
string webServiceTlsCertificatePath = Environment.GetEnvironmentVariable("DNS_SERVER_WEB_SERVICE_TLS_CERTIFICATE_PATH");
if (!string.IsNullOrEmpty(webServiceTlsCertificatePath))
{
_webServiceTlsCertificatePath = webServiceTlsCertificatePath;
string webServiceTlsCertificateAbsolutePath = ConvertToAbsolutePath(_webServiceTlsCertificatePath);
try
{
LoadWebServiceTlsCertificate(webServiceTlsCertificateAbsolutePath, _webServiceTlsCertificatePassword);
}
catch (Exception ex)
{
_log.Write("DNS Server encountered an error while loading Web Service TLS certificate: " + webServiceTlsCertificateAbsolutePath + "\r\n" + ex.ToString());
}
StartTlsCertificateUpdateTimer();
}
string webServiceUseSelfSignedTlsCertificate = Environment.GetEnvironmentVariable("DNS_SERVER_WEB_SERVICE_USE_SELF_SIGNED_CERT");
if (!string.IsNullOrEmpty(webServiceUseSelfSignedTlsCertificate))
{
_webServiceUseSelfSignedTlsCertificate = bool.Parse(webServiceUseSelfSignedTlsCertificate);
if (_webServiceUseSelfSignedTlsCertificate && !File.Exists(Path.Combine(_configFolder, "dns.config")))
{
//read DNS server domain name here to generate self signed cert
string serverDomain = Environment.GetEnvironmentVariable("DNS_SERVER_DOMAIN");
if (!string.IsNullOrEmpty(serverDomain))
_dnsServer.ServerDomain = serverDomain;
}
CheckAndLoadSelfSignedCertificate(false, false);
}
string webServiceHttpToTlsRedirect = Environment.GetEnvironmentVariable("DNS_SERVER_WEB_SERVICE_HTTP_TO_TLS_REDIRECT");
if (!string.IsNullOrEmpty(webServiceHttpToTlsRedirect))
_webServiceHttpToTlsRedirect = bool.Parse(webServiceHttpToTlsRedirect);
}
SaveConfigFileInternal();
}
catch (Exception ex)
{
_log.Write("DNS Server encountered an error while loading Web Service config file: " + webServiceConfigFile + "\r\n" + ex.ToString());
_log.Write("Note: You may try deleting the Web Service config file to fix this issue. However, you will lose Web Service settings but, other data wont be affected.");
throw;
}
}
public void LoadConfig(Stream s)
{
lock (_saveLock)
{
ReadConfigFrom(s);
SaveConfigFileInternal();
if (_pendingSave)
{
_pendingSave = false;
_saveTimer.Change(Timeout.Infinite, Timeout.Infinite);
}
}
}
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, DnsForwarderRecordProxyType.DefaultProxy, null, 0, null, null, fwdRecordComments) is not null)
{
//set permissions
_authManager.SetPermission(PermissionSection.Zones, ntpDomain, _authManager.GetGroup(Group.ADMINISTRATORS), PermissionFlag.ViewModifyDelete);
_authManager.SetPermission(PermissionSection.Zones, ntpDomain, _authManager.GetGroup(Group.DNS_ADMINISTRATORS), PermissionFlag.ViewModifyDelete);
_authManager.SaveConfigFile();
}
}
}
private void SaveConfigFileInternal()
{
string tmpConfigFile = Path.Combine(_configFolder, "webservice.tmp");
string configFile = Path.Combine(_configFolder, "webservice.config");
using (MemoryStream mS = new MemoryStream())
{
//serialize config
WriteConfigTo(mS);
//write config
mS.Position = 0;
using (FileStream fS = new FileStream(tmpConfigFile, FileMode.Create, FileAccess.Write))
{
mS.CopyTo(fS);
}
}
File.Move(tmpConfigFile, configFile, true);
_log.Write("Web Service config file was saved: " + configFile);
}
public void SaveConfigFile()
{
lock (_saveLock)
{
if (_pendingSave)
return;
_pendingSave = true;
_saveTimer.Change(SAVE_TIMER_INITIAL_INTERVAL, Timeout.Infinite);
}
}
private void InspectAndFixZonePermissions()
{
Permission permission = _authManager.GetPermission(PermissionSection.Zones);
if (permission is null)
throw new DnsWebServiceException("Failed to read 'Zones' permissions: auth.config file is probably corrupt.");
IReadOnlyDictionary<string, Permission> subItemPermissions = permission.SubItemPermissions;
//remove ghost permissions
foreach (KeyValuePair<string, Permission> subItemPermission in subItemPermissions)
{
string zoneName = subItemPermission.Key;
if (_dnsServer.AuthZoneManager.GetAuthZoneInfo(zoneName) is null)
permission.RemoveAllSubItemPermissions(zoneName); //no such zone exists; remove permissions
}
//add missing admin permissions
IReadOnlyList<AuthZoneInfo> zones = _dnsServer.AuthZoneManager.GetAllZones();
Group admins = _authManager.GetGroup(Group.ADMINISTRATORS);
if (admins is null)
throw new DnsWebServiceException("Failed to find 'Administrators' group: auth.config file is probably corrupt.");
Group dnsAdmins = _authManager.GetGroup(Group.DNS_ADMINISTRATORS);
if (dnsAdmins is null)
throw new DnsWebServiceException("Failed to find 'DNS Administrators' group: auth.config file is probably corrupt.");
foreach (AuthZoneInfo zone in zones)
{
if (zone.Internal)
{
_authManager.SetPermission(PermissionSection.Zones, zone.Name, admins, PermissionFlag.View);
_authManager.SetPermission(PermissionSection.Zones, zone.Name, dnsAdmins, PermissionFlag.View);
}
else
{
_authManager.SetPermission(PermissionSection.Zones, zone.Name, admins, PermissionFlag.ViewModifyDelete);
_authManager.SetPermission(PermissionSection.Zones, zone.Name, dnsAdmins, PermissionFlag.ViewModifyDelete);
}
}
_authManager.SaveConfigFile();
}
private void ReadConfigFrom(Stream s)
{
if (Encoding.ASCII.GetString(s.ReadExactly(2)) != "WC") //format
throw new InvalidDataException("Web Service config file format is invalid.");
BinaryReader bR = new BinaryReader(s);
int version = bR.ReadByte();
if (version > 2)
throw new InvalidDataException("Web Service config version not supported.");
_webServiceHttpPort = bR.ReadInt32();
_webServiceTlsPort = bR.ReadInt32();
{
IPAddress[] webServiceLocalAddresses;
int count = bR.ReadByte();
if (count > 0)
{
IPAddress[] localAddresses = new IPAddress[count];
for (int i = 0; i < count; i++)
localAddresses[i] = IPAddressExtensions.ReadFrom(bR);
webServiceLocalAddresses = localAddresses;
}
else
{
webServiceLocalAddresses = [IPAddress.Any, IPAddress.IPv6Any];
}
_webServiceLocalAddresses = webServiceLocalAddresses;
}
_webServiceEnableTls = bR.ReadBoolean();
_webServiceEnableHttp3 = bR.ReadBoolean();
_webServiceHttpToTlsRedirect = bR.ReadBoolean();
_webServiceUseSelfSignedTlsCertificate = bR.ReadBoolean();
if (version >= 2)
{
_webServiceReverseProxyAddresses = AuthZoneInfo.ReadNetworkACLFrom(bR);
}
else
{
_webServiceReverseProxyAddresses =
[
new NetworkAccessControl(IPAddress.Parse("127.0.0.0"), 8),
new NetworkAccessControl(IPAddress.Parse("10.0.0.0"), 8),
new NetworkAccessControl(IPAddress.Parse("100.64.0.0"), 10),
new NetworkAccessControl(IPAddress.Parse("169.254.0.0"), 16),
new NetworkAccessControl(IPAddress.Parse("172.16.0.0"), 12),
new NetworkAccessControl(IPAddress.Parse("192.168.0.0"), 16),
new NetworkAccessControl(IPAddress.Parse("2000::"), 3, true),
new NetworkAccessControl(IPAddress.IPv6Any, 0)
];
}
_webServiceTlsCertificatePath = s.ReadShortString();
_webServiceTlsCertificatePassword = s.ReadShortString();
if (_webServiceTlsCertificatePath.Length == 0)
_webServiceTlsCertificatePath = null;
if (_webServiceTlsCertificatePath is null)
{
StopTlsCertificateUpdateTimer();
}
else
{
string webServiceTlsCertificateAbsolutePath = ConvertToAbsolutePath(_webServiceTlsCertificatePath);
try
{
LoadWebServiceTlsCertificate(webServiceTlsCertificateAbsolutePath, _webServiceTlsCertificatePassword);
}
catch (Exception ex)
{
_log.Write("DNS Server encountered an error while loading Web Service TLS certificate: " + webServiceTlsCertificateAbsolutePath + "\r\n" + ex.ToString());
}
StartTlsCertificateUpdateTimer();
}
CheckAndLoadSelfSignedCertificate(false, false);
_webServiceRealIpHeader = s.ReadShortString();
}
private void WriteConfigTo(Stream s)
{
BinaryWriter bW = new BinaryWriter(s);
bW.Write(Encoding.ASCII.GetBytes("WC")); //format
bW.Write((byte)2); //version
bW.Write(_webServiceHttpPort);
bW.Write(_webServiceTlsPort);
{
bW.Write(Convert.ToByte(_webServiceLocalAddresses.Count));
foreach (IPAddress localAddress in _webServiceLocalAddresses)
localAddress.WriteTo(bW);
}
bW.Write(_webServiceEnableTls);
bW.Write(_webServiceEnableHttp3);
bW.Write(_webServiceHttpToTlsRedirect);
bW.Write(_webServiceUseSelfSignedTlsCertificate);
AuthZoneInfo.WriteNetworkACLTo(_webServiceReverseProxyAddresses, bW);
if (_webServiceTlsCertificatePath is null)
s.WriteShortString(string.Empty);
else
s.WriteShortString(_webServiceTlsCertificatePath);
if (_webServiceTlsCertificatePassword is null)
s.WriteShortString(string.Empty);
else
s.WriteShortString(_webServiceTlsCertificatePassword);
s.WriteShortString(_webServiceRealIpHeader);
}
#endregion
#region backup and restore config
internal async Task BackupConfigAsync(Stream zipStream, bool authConfig, bool clusterConfig, bool webServiceSettings, bool dnsSettings, bool logSettings, bool zones, bool allowedZones, bool blockedZones, bool blockLists, bool apps, bool scopes, bool stats, bool logs, bool isConfigTransfer = false, DateTime ifModifiedSince = default, ICollection<string> includeZones = null)
{
using (ZipArchive backupZip = new ZipArchive(zipStream, ZipArchiveMode.Create, true, Encoding.UTF8))
{
if (authConfig)
{
string authConfigFile = Path.Combine(_configFolder, "auth.config");
if (File.Exists(authConfigFile) && (File.GetLastWriteTimeUtc(authConfigFile) > ifModifiedSince))
backupZip.CreateEntryFromFile(authConfigFile, "auth.config");
}
if (clusterConfig && !isConfigTransfer)
{
string clusterConfigFile = Path.Combine(_configFolder, "cluster.config");
if (File.Exists(clusterConfigFile))
backupZip.CreateEntryFromFile(clusterConfigFile, "cluster.config");
}
if (webServiceSettings && !isConfigTransfer)
{
string webServiceConfigFile = Path.Combine(_configFolder, "webservice.config");
if (File.Exists(webServiceConfigFile) && (File.GetLastWriteTimeUtc(webServiceConfigFile) > ifModifiedSince))
backupZip.CreateEntryFromFile(webServiceConfigFile, "webservice.config");
//backup web service cert
if (!isConfigTransfer && !string.IsNullOrEmpty(_webServiceTlsCertificatePath))
{
string webServiceTlsCertificatePath = ConvertToAbsolutePath(_webServiceTlsCertificatePath);
if (File.Exists(webServiceTlsCertificatePath) && webServiceTlsCertificatePath.StartsWith(_configFolder, Environment.OSVersion.Platform == PlatformID.Win32NT ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
{
string entryName = ConvertToRelativePath(webServiceTlsCertificatePath).Replace('\\', '/');
backupZip.CreateEntryFromFile(webServiceTlsCertificatePath, entryName);
}
}
}
if (dnsSettings)
{
string dnsConfigFile = Path.Combine(_configFolder, "dns.config");
if (File.Exists(dnsConfigFile) && (File.GetLastWriteTimeUtc(dnsConfigFile) > ifModifiedSince))
backupZip.CreateEntryFromFile(dnsConfigFile, "dns.config");
//backup optional protocols cert
if (!isConfigTransfer && !string.IsNullOrEmpty(_dnsServer.DnsTlsCertificatePath))
{
string dnsTlsCertificatePath = ConvertToAbsolutePath(_dnsServer.DnsTlsCertificatePath);
if (File.Exists(dnsTlsCertificatePath) && dnsTlsCertificatePath.StartsWith(_configFolder, Environment.OSVersion.Platform == PlatformID.Win32NT ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
{
string entryName = ConvertToRelativePath(dnsTlsCertificatePath).Replace('\\', '/');
backupZip.CreateEntryFromFile(dnsTlsCertificatePath, entryName);
}
}
}
if (logSettings && !isConfigTransfer)
{
string logConfigFile = Path.Combine(_configFolder, "log.config");
if (File.Exists(logConfigFile) && (File.GetLastWriteTimeUtc(logConfigFile) > ifModifiedSince))
backupZip.CreateEntryFromFile(logConfigFile, "log.config");
}
if (zones)
{
if (isConfigTransfer)
{
//backup Primary zone DNSSEC private keys that are member zone of the cluster catalog zone
AuthZoneInfo clusterCatalogZoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo("cluster-catalog." + _clusterManager.ClusterDomain);
if ((clusterCatalogZoneInfo is not null) && (clusterCatalogZoneInfo.Type == AuthZoneType.Catalog))
{
IReadOnlyCollection<string> memberZoneNames = (clusterCatalogZoneInfo.ApexZone as CatalogZone).GetAllMemberZoneNames();
foreach (string memberZoneName in memberZoneNames)
{
AuthZoneInfo memberZoneInfo = _dnsServer.AuthZoneManager.GetAuthZoneInfo(memberZoneName);
if (memberZoneInfo is null)
continue; //no such zone exists; ignore
if (memberZoneInfo.Type != AuthZoneType.Primary)
continue; //not a Primary zone; ignore
if (memberZoneInfo.ApexZone.DnssecStatus == AuthZoneDnssecStatus.Unsigned)
continue; //not a DNSSEC signed zone; ignore
IReadOnlyCollection<DnssecPrivateKey> dnssecPrivateKeys = memberZoneInfo.DnssecPrivateKeys;
bool includePrivateKeys = false;
if ((includeZones is not null) && includeZones.Contains(memberZoneInfo.Name))
{
includePrivateKeys = true;
}
else
{
foreach (DnssecPrivateKey dnssecPrivateKey in dnssecPrivateKeys)
{
if (dnssecPrivateKey.StateChangedOn > ifModifiedSince)
{
//found a changed key
includePrivateKeys = true;
break;
}
}
}
if (includePrivateKeys)
{
using (MemoryStream mS = new MemoryStream(4096))
{
AuthZoneInfo.WriteDnssecPrivateKeysTo(dnssecPrivateKeys, new BinaryWriter(mS));
mS.Position = 0;
//create zip entry
ZipArchiveEntry entry = backupZip.CreateEntry("zones/" + memberZoneName + ".keys", CompressionLevel.Optimal);
await using (Stream entryStream = entry.Open())
{
await mS.CopyToAsync(entryStream);
}
}
}
}
}
}
else
{
//backup zone files
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) && (File.GetLastWriteTimeUtc(allowedZonesFile) > ifModifiedSince))
backupZip.CreateEntryFromFile(allowedZonesFile, "allowed.config");
}
if (blockedZones)
{
string blockedZonesFile = Path.Combine(_configFolder, "blocked.config");
if (File.Exists(blockedZonesFile) && (File.GetLastWriteTimeUtc(blockedZonesFile) > ifModifiedSince))
backupZip.CreateEntryFromFile(blockedZonesFile, "blocked.config");
}
if (blockLists)
{
string blockListConfigFile = Path.Combine(_configFolder, "blocklist.config");
if (File.Exists(blockListConfigFile) && (File.GetLastWriteTimeUtc(blockListConfigFile) > ifModifiedSince))
backupZip.CreateEntryFromFile(blockListConfigFile, "blocklist.config");
string[] blockListFiles = Directory.GetFiles(Path.Combine(_configFolder, "blocklists"), "*", SearchOption.TopDirectoryOnly);
foreach (string blockListFile in blockListFiles)
{
if (File.GetLastWriteTimeUtc(blockListFile) > ifModifiedSince)
{
string entryName = "blocklists/" + Path.GetFileName(blockListFile);
backupZip.CreateEntryFromFile(blockListFile, entryName);
}
}
}
if (apps)
{
if (isConfigTransfer)
{
string[] appDirectories = Directory.GetDirectories(Path.Combine(_configFolder, "apps"), "*", SearchOption.TopDirectoryOnly);
foreach (string appDirectory in appDirectories)
{
string applicationName = Path.GetFileName(appDirectory);
string applicationZipFile = Path.Combine(appDirectory, applicationName + ".zip");
string configFile = Path.Combine(appDirectory, "dnsApp.config");
bool fileAdded = false;
if (File.Exists(applicationZipFile) && (File.GetLastWriteTimeUtc(applicationZipFile) > ifModifiedSince))
{
string entryName = "apps/" + applicationName + "/" + applicationName + ".zip";
backupZip.CreateEntryFromFile(applicationZipFile, entryName);
fileAdded = true;
}
if (File.Exists(configFile) && (File.GetLastWriteTimeUtc(configFile) > ifModifiedSince))
{
string entryName = "apps/" + applicationName + "/dnsApp.config";
backupZip.CreateEntryFromFile(configFile, entryName);
fileAdded = true;
}
if (!fileAdded)
_ = backupZip.CreateEntry("apps/" + applicationName + "/.exists", CompressionLevel.Optimal);
}
}
else
{
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('/');
await CreateBackupEntryFromSharedFileAsync(backupZip, appFile, entryName);
}
}
}
if (scopes && !isConfigTransfer)
{
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 (stats && !isConfigTransfer)
{
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 (logs && !isConfigTransfer)
{
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))
{
await CreateBackupEntryFromSharedFileAsync(backupZip, logFile, entryName);
}
else
{
backupZip.CreateEntryFromFile(logFile, entryName);
}
}
}
}
}
internal async Task RestoreConfigAsync(Stream zipStream, bool authConfig, bool clusterConfig, bool webServiceSettings, bool dnsSettings, bool logSettings, bool zones, bool allowedZones, bool blockedZones, bool blockLists, bool apps, bool scopes, bool stats, bool logs, bool deleteExistingFiles, UserSession implantSession = null, bool isConfigTransfer = false)
{
using (ZipArchive backupZip = new ZipArchive(zipStream, ZipArchiveMode.Read, false, Encoding.UTF8))
{
bool restartWebService = false;
try
{
if (logSettings && !isConfigTransfer)
{
ZipArchiveEntry entry = backupZip.GetEntry("log.config");
if (entry is not null)
{
//dynamically load and apply logger config
await using (Stream stream = entry.Open())
{
_log.LoadConfig(stream);
}
}
}
if (logs && !isConfigTransfer)
{
_log.BulkManipulateLogFiles(delegate ()
{
if (deleteExistingFiles)
{
//delete existing log files
string[] logFiles = Directory.GetFiles(_log.LogFolderAbsolutePath, "*.log", SearchOption.TopDirectoryOnly);
foreach (string logFile in logFiles)
{
try
{
File.Delete(logFile);
}
catch (Exception ex)
{
_log.Write(ex);
}
}
}
//extract log files from backup
foreach (ZipArchiveEntry entry in backupZip.Entries)
{
if (entry.FullName.StartsWith("logs/"))
{
try
{
entry.ExtractToFile(Path.Combine(_log.LogFolderAbsolutePath, entry.Name), true);
}
catch (Exception ex)
{
_log.Write(ex);
}
}
}
});
}
if (authConfig)
{
ZipArchiveEntry entry = backupZip.GetEntry("auth.config");
if (entry is not null)
{
//dynamically load and apply auth config
await using (Stream stream = entry.Open())
{
_authManager.LoadConfig(stream, isConfigTransfer, out restartWebService, implantSession);
}
}
}
if (clusterConfig && !isConfigTransfer)
{
ZipArchiveEntry entry = backupZip.GetEntry("cluster.config");
if (entry is not null)
{
//dynamically load and apply cluster config
await using (Stream stream = entry.Open())
{
_clusterManager.LoadConfig(stream);
}
}
}
if ((webServiceSettings || dnsSettings) && !isConfigTransfer)
{
//extract any certs
foreach (ZipArchiveEntry certEntry in backupZip.Entries)
{
if (certEntry.FullName.StartsWith("apps/"))
continue;
if (certEntry.FullName.EndsWith(".pfx", StringComparison.OrdinalIgnoreCase) || certEntry.FullName.EndsWith(".p12", StringComparison.OrdinalIgnoreCase))
{
string certFile = Path.Combine(_configFolder, certEntry.FullName);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(certFile));
certEntry.ExtractToFile(certFile, true);
}
catch (Exception ex)
{
_log.Write(ex);
}
}
}
}
if (webServiceSettings && !isConfigTransfer)
{
ZipArchiveEntry entry = backupZip.GetEntry("webservice.config");
if (entry is not null)
{
//dynamically load and apply web service config
await using (Stream stream = entry.Open())
{
LoadConfig(stream);
}
//cert may have changed so update cluster certs when restoring
if (_clusterManager.ClusterInitialized)
{
try
{
_clusterManager.UpdateSelfNodeUrlAndCertificate();
}
catch (Exception ex)
{
_log.Write(ex);
}
}
}
}