-
-
Notifications
You must be signed in to change notification settings - Fork 735
Expand file tree
/
Copy pathAuthManager.cs
More file actions
1378 lines (1095 loc) · 49.7 KB
/
Copy pathAuthManager.cs
File metadata and controls
1378 lines (1095 loc) · 49.7 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 System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TechnitiumLibrary.IO;
using TechnitiumLibrary.Net;
using TechnitiumLibrary.Security.OTP;
namespace DnsServerCore.Auth
{
sealed class AuthManager : IDisposable
{
#region variables
ConcurrentDictionary<string, Group> _groups = new ConcurrentDictionary<string, Group>(1, 4);
ConcurrentDictionary<string, User> _users = new ConcurrentDictionary<string, User>(1, 4);
ConcurrentDictionary<PermissionSection, Permission> _permissions = new ConcurrentDictionary<PermissionSection, Permission>(1, 11);
ConcurrentDictionary<string, UserSession> _sessions = new ConcurrentDictionary<string, UserSession>(1, 10);
readonly ConcurrentDictionary<IPAddress, int> _failedLoginAttemptNetworks = new ConcurrentDictionary<IPAddress, int>(1, 10);
const int MAX_LOGIN_ATTEMPTS = 5;
readonly ConcurrentDictionary<IPAddress, DateTime> _blockedNetworks = new ConcurrentDictionary<IPAddress, DateTime>(1, 10);
const int BLOCK_NETWORK_INTERVAL = 5 * 60 * 1000;
readonly string _configFolder;
readonly LogManager _log;
bool _ssoEnabled;
Uri _ssoAuthority;
string _ssoClientId;
string _ssoClientSecret;
Uri _ssoMetadataAddress;
bool _ssoAllowSignup;
bool _ssoAllowSignupOnlyForMappedUsers = true;
IReadOnlyDictionary<string, string> _ssoGroupMap;
readonly Lock _saveLock = new Lock();
bool _pendingSave;
readonly Timer _saveTimer;
const int SAVE_TIMER_INITIAL_INTERVAL = 5000;
#endregion
#region constructor
public AuthManager(string configFolder, LogManager log)
{
_configFolder = configFolder;
_log = log;
_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);
}
}
}
});
LoadConfigFile();
}
#endregion
#region IDisposable
bool _disposed;
public void Dispose()
{
if (_disposed)
return;
lock (_saveLock)
{
_saveTimer?.Dispose();
//always save config here to write user login timestamps details
try
{
SaveConfigFileInternal();
}
catch (Exception ex)
{
_log.Write(ex);
}
finally
{
_pendingSave = false;
}
}
_disposed = true;
}
#endregion
#region config
private void LoadConfigFile()
{
string configFile = Path.Combine(_configFolder, "auth.config");
try
{
bool passwordResetOption = false;
if (!File.Exists(configFile))
{
string passwordResetConfigFile = Path.Combine(_configFolder, "resetadmin.config");
if (File.Exists(passwordResetConfigFile))
{
passwordResetOption = true;
configFile = passwordResetConfigFile;
}
}
using (FileStream fS = new FileStream(configFile, FileMode.Open, FileAccess.Read))
{
ReadConfigFrom(fS, false, out bool _);
}
_log.Write("DNS Server auth config file was loaded: " + configFile);
if (passwordResetOption)
{
User adminUser = GetUser("admin");
if (adminUser is null)
{
adminUser = CreateUser("Administrator", "admin", "admin");
}
else
{
adminUser.ChangePassword("admin");
adminUser.Disabled = false;
if (adminUser.TOTPEnabled)
adminUser.DisableTOTP();
}
adminUser.AddToGroup(GetGroup(Group.ADMINISTRATORS));
_log.Write("DNS Server has reset the password for user: admin");
SaveConfigFileInternal();
try
{
File.Delete(configFile);
}
catch
{ }
}
}
catch (FileNotFoundException)
{
CreateDefaultConfig();
string strSsoEnabled = Environment.GetEnvironmentVariable("DNS_SERVER_SSO_ENABLED");
if (!string.IsNullOrEmpty(strSsoEnabled))
_ssoEnabled = bool.Parse(strSsoEnabled);
string strSsoAuthority = Environment.GetEnvironmentVariable("DNS_SERVER_SSO_AUTHORITY");
if (!string.IsNullOrEmpty(strSsoAuthority))
_ssoAuthority = new Uri(strSsoAuthority);
string strSsoClientId = Environment.GetEnvironmentVariable("DNS_SERVER_SSO_CLIENT_ID");
if (!string.IsNullOrEmpty(strSsoClientId))
_ssoClientId = strSsoClientId;
string strSsoClientSecret = Environment.GetEnvironmentVariable("DNS_SERVER_SSO_CLIENT_SECRET");
string strSsoClientSecretFile = Environment.GetEnvironmentVariable("DNS_SERVER_SSO_CLIENT_SECRET_FILE");
if (!string.IsNullOrEmpty(strSsoClientSecret))
{
_ssoClientSecret = strSsoClientSecret;
}
else if (!string.IsNullOrEmpty(strSsoClientSecretFile))
{
using (StreamReader sR = new StreamReader(strSsoClientSecretFile, true))
{
_ssoClientSecret = sR.ReadLine();
}
}
string strSsoMetadataAddress = Environment.GetEnvironmentVariable("DNS_SERVER_SSO_METADATA_ADDRESS");
if (!string.IsNullOrEmpty(strSsoMetadataAddress))
_ssoMetadataAddress = new Uri(strSsoMetadataAddress);
string strSsoAllowSignup = Environment.GetEnvironmentVariable("DNS_SERVER_SSO_ALLOW_SIGNUP");
if (!string.IsNullOrEmpty(strSsoAllowSignup))
_ssoAllowSignup = bool.Parse(strSsoAllowSignup);
string strSsoAllowSignupOnlyForMappedUsers = Environment.GetEnvironmentVariable("DNS_SERVER_SSO_ALLOW_SIGNUP_ONLY_FOR_MAPPED_USERS");
if (!string.IsNullOrEmpty(strSsoAllowSignupOnlyForMappedUsers))
_ssoAllowSignupOnlyForMappedUsers = bool.Parse(strSsoAllowSignupOnlyForMappedUsers);
string strGroupMap = Environment.GetEnvironmentVariable("DNS_SERVER_SSO_GROUP_MAP");
if (!string.IsNullOrEmpty(strGroupMap))
{
string[] entries = strGroupMap.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Dictionary<string, string> groupMap = new Dictionary<string, string>(entries.Length);
foreach (string entry in entries)
{
string[] parts = entry.Split(':', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length == 2)
groupMap.TryAdd(parts[0], parts[1]);
}
_ssoGroupMap = groupMap;
}
SaveConfigFileInternal();
}
catch (Exception ex)
{
_log.Write("DNS Server encountered an error while loading auth config file: " + configFile + "\r\n" + ex.ToString());
_log.Write("Note: You may try deleting the auth config file to fix this issue. However, you will lose auth settings but, rest of the DNS settings and zone data wont be affected.");
throw;
}
}
public void LoadOldConfig(string password, bool isPasswordHash)
{
User user = GetUser("admin");
if (user is null)
user = CreateUser("Administrator", "admin", "admin");
user.AddToGroup(GetGroup(Group.ADMINISTRATORS));
if (isPasswordHash)
user.LoadOldSchemeCredentials(password);
else
user.ChangePassword(password);
lock (_saveLock)
{
SaveConfigFileInternal();
}
}
public void LoadConfig(Stream s, bool isConfigTransfer, out bool restartWebService, UserSession implantSession = null)
{
lock (_saveLock)
{
ReadConfigFrom(s, isConfigTransfer, out restartWebService);
if (!isConfigTransfer)
{
if (implantSession is not null)
{
//implant current user and session into config while restoring backup config
using (MemoryStream mS = new MemoryStream())
{
//implant current user
implantSession.User.WriteTo(new BinaryWriter(mS));
mS.Position = 0;
User newUser = new User(new BinaryReader(mS), _groups);
newUser.AddToGroup(GetGroup(Group.ADMINISTRATORS));
_users[newUser.Username] = newUser;
//implant current session
mS.SetLength(0);
implantSession.WriteTo(new BinaryWriter(mS));
mS.Position = 0;
UserSession newSession = new UserSession(new BinaryReader(mS), _users);
_sessions[newSession.Token] = newSession;
}
}
}
//save config file
SaveConfigFileInternal();
if (_pendingSave)
{
_pendingSave = false;
_saveTimer.Change(Timeout.Infinite, Timeout.Infinite);
}
}
}
private void SaveConfigFileInternal()
{
string tmpConfigFile = Path.Combine(_configFolder, "auth.tmp");
string configFile = Path.Combine(_configFolder, "auth.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);
fS.Flush(flushToDisk: true);
}
}
File.Move(tmpConfigFile, configFile, true);
_log.Write("DNS Server auth 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 ReadConfigFrom(Stream s, bool isConfigTransfer, out bool restartWebService)
{
if (Encoding.ASCII.GetString(s.ReadExactly(2)) != "AS") //format
throw new InvalidDataException("DNS Server auth config file format is invalid.");
restartWebService = false;
ConcurrentDictionary<string, Group> groups = new ConcurrentDictionary<string, Group>(1, 4);
ConcurrentDictionary<string, User> users = new ConcurrentDictionary<string, User>(1, 4);
ConcurrentDictionary<PermissionSection, Permission> permissions = new ConcurrentDictionary<PermissionSection, Permission>(1, 11);
ConcurrentDictionary<string, UserSession> sessions = new ConcurrentDictionary<string, UserSession>(1, 10);
BinaryReader bR = new BinaryReader(s);
int version = bR.ReadByte();
switch (version)
{
case 1:
case 2:
{
int count = bR.ReadByte();
for (int i = 0; i < count; i++)
{
Group group = new Group(bR);
groups.TryAdd(group.Name.ToLowerInvariant(), group);
}
}
{
int count = bR.ReadByte();
for (int i = 0; i < count; i++)
{
User user = new User(bR, groups);
users.TryAdd(user.Username, user);
}
}
{
int count = bR.ReadInt32();
for (int i = 0; i < count; i++)
{
Permission permission = new Permission(bR, users, groups);
permissions.TryAdd(permission.Section, permission);
}
}
{
int count = bR.ReadInt32();
for (int i = 0; i < count; i++)
{
UserSession session = new UserSession(bR, users);
if (!session.HasExpired())
sessions.TryAdd(session.Token, session);
}
}
if (version >= 2)
{
bool ssoIsStillDisabled = false;
bool ssoEnabled = bR.ReadBoolean();
if (_ssoEnabled == ssoEnabled)
{
ssoIsStillDisabled = !ssoEnabled;
}
else
{
_ssoEnabled = ssoEnabled;
restartWebService = true;
}
string strSsoAuthority = s.ReadShortString();
Uri ssoAuthority;
if (strSsoAuthority.Length == 0)
ssoAuthority = null;
else
ssoAuthority = new Uri(strSsoAuthority);
if (_ssoAuthority != ssoAuthority)
{
_ssoAuthority = ssoAuthority;
restartWebService = true;
}
string ssoClientId = s.ReadShortString();
if (ssoClientId.Length == 0)
ssoClientId = null;
if (_ssoClientId != ssoClientId)
{
_ssoClientId = ssoClientId;
restartWebService = true;
}
string ssoClientSecret = s.ReadShortString();
if (ssoClientSecret.Length == 0)
ssoClientSecret = null;
if (_ssoClientSecret != ssoClientSecret)
{
_ssoClientSecret = ssoClientSecret;
restartWebService = true;
}
string strSsoMetadataAddress = s.ReadShortString();
Uri ssoMetadataAddress;
if (strSsoMetadataAddress.Length == 0)
ssoMetadataAddress = null;
else
ssoMetadataAddress = new Uri(strSsoMetadataAddress);
if (_ssoMetadataAddress != ssoMetadataAddress)
{
_ssoMetadataAddress = ssoMetadataAddress;
restartWebService = true;
}
_ssoAllowSignup = bR.ReadBoolean();
_ssoAllowSignupOnlyForMappedUsers = bR.ReadBoolean();
{
int count = bR.ReadByte();
if (count > 0)
{
Dictionary<string, string> ssoGroupMap = new Dictionary<string, string>(count);
for (int i = 0; i < count; i++)
{
string key = s.ReadShortString();
string value = s.ReadShortString();
ssoGroupMap.TryAdd(key, value);
}
_ssoGroupMap = ssoGroupMap;
}
else
{
_ssoGroupMap = null;
}
}
restartWebService = !ssoIsStillDisabled && restartWebService;
}
break;
default:
throw new InvalidDataException("DNS Server auth config version not supported.");
}
_groups = groups;
_users = users;
if (isConfigTransfer)
{
//sync only required permissions from newly loaded config
foreach (KeyValuePair<PermissionSection, Permission> permission in permissions)
{
switch (permission.Key)
{
case PermissionSection.Zones:
//sync user and group permissions as-is for zones section
Permission zonesPermission = _permissions[PermissionSection.Zones];
zonesPermission.SyncPermissions(permission.Value.UserPermissions);
zonesPermission.SyncPermissions(permission.Value.GroupPermissions);
break;
default:
_permissions[permission.Key] = permission.Value;
break;
}
}
//update all user objects in existing sessions to reflect the newly loaded config
foreach (KeyValuePair<string, UserSession> session in _sessions)
session.Value.UpdateUserObject(_users);
//sync only API sessions from newly loaded config
foreach (KeyValuePair<string, UserSession> existingSession in _sessions)
{
switch (existingSession.Value.Type)
{
case UserSessionType.ApiToken:
if (!sessions.ContainsKey(existingSession.Key))
_sessions.TryRemove(existingSession);
break;
}
}
foreach (KeyValuePair<string, UserSession> session in sessions)
{
switch (session.Value.Type)
{
case UserSessionType.ApiToken:
case UserSessionType.ClusterApiToken:
_sessions[session.Key] = session.Value;
break;
}
}
}
else
{
_permissions = permissions;
_sessions = sessions;
}
}
private void WriteConfigTo(Stream s)
{
BinaryWriter bW = new BinaryWriter(s);
bW.Write(Encoding.ASCII.GetBytes("AS")); //format
bW.Write((byte)2); //version
bW.Write(Convert.ToByte(_groups.Count));
foreach (KeyValuePair<string, Group> group in _groups)
group.Value.WriteTo(bW);
bW.Write(Convert.ToByte(_users.Count));
foreach (KeyValuePair<string, User> user in _users)
user.Value.WriteTo(bW);
bW.Write(_permissions.Count);
foreach (KeyValuePair<PermissionSection, Permission> permission in _permissions)
permission.Value.WriteTo(bW);
List<UserSession> activeSessions = new List<UserSession>(_sessions.Count);
foreach (KeyValuePair<string, UserSession> session in _sessions)
{
if (session.Value.HasExpired())
_sessions.TryRemove(session.Key, out _);
else
activeSessions.Add(session.Value);
}
bW.Write(activeSessions.Count);
foreach (UserSession session in activeSessions)
session.WriteTo(bW);
bW.Write(_ssoEnabled);
if (_ssoAuthority is null)
s.WriteShortString("");
else
s.WriteShortString(_ssoAuthority.OriginalString);
if (_ssoClientId is null)
s.WriteShortString("");
else
s.WriteShortString(_ssoClientId);
if (_ssoClientSecret is null)
s.WriteShortString("");
else
s.WriteShortString(_ssoClientSecret);
if (_ssoMetadataAddress is null)
s.WriteShortString("");
else
s.WriteShortString(_ssoMetadataAddress.OriginalString);
bW.Write(_ssoAllowSignup);
bW.Write(_ssoAllowSignupOnlyForMappedUsers);
if ((_ssoGroupMap is null) || (_ssoGroupMap.Count == 0))
{
bW.Write((byte)0);
}
else
{
bW.Write(Convert.ToByte(_ssoGroupMap.Count));
foreach (KeyValuePair<string, string> entry in _ssoGroupMap)
{
s.WriteShortString(entry.Key);
s.WriteShortString(entry.Value);
}
}
}
#endregion
#region private
private void CreateDefaultConfig()
{
Group adminGroup = CreateGroup(Group.ADMINISTRATORS, "Super administrators");
Group dnsAdminGroup = CreateGroup(Group.DNS_ADMINISTRATORS, "DNS service administrators");
Group dhcpAdminGroup = CreateGroup(Group.DHCP_ADMINISTRATORS, "DHCP service administrators");
Group everyoneGroup = CreateGroup(Group.EVERYONE, "All users");
SetPermission(PermissionSection.Dashboard, adminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Zones, adminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Cache, adminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Allowed, adminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Blocked, adminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Apps, adminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.DnsClient, adminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Settings, adminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.DhcpServer, adminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Administration, adminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Logs, adminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Zones, dnsAdminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Cache, dnsAdminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Allowed, dnsAdminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Blocked, dnsAdminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Apps, dnsAdminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.DnsClient, dnsAdminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Settings, dnsAdminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.DhcpServer, dhcpAdminGroup, PermissionFlag.ViewModifyDelete);
SetPermission(PermissionSection.Dashboard, everyoneGroup, PermissionFlag.View);
SetPermission(PermissionSection.Zones, everyoneGroup, PermissionFlag.View);
SetPermission(PermissionSection.Cache, everyoneGroup, PermissionFlag.View);
SetPermission(PermissionSection.Allowed, everyoneGroup, PermissionFlag.View);
SetPermission(PermissionSection.Blocked, everyoneGroup, PermissionFlag.View);
SetPermission(PermissionSection.Apps, everyoneGroup, PermissionFlag.View);
SetPermission(PermissionSection.DnsClient, everyoneGroup, PermissionFlag.View);
SetPermission(PermissionSection.DhcpServer, everyoneGroup, PermissionFlag.View);
SetPermission(PermissionSection.Logs, everyoneGroup, PermissionFlag.View);
string adminPassword = Environment.GetEnvironmentVariable("DNS_SERVER_ADMIN_PASSWORD");
string adminPasswordFile = Environment.GetEnvironmentVariable("DNS_SERVER_ADMIN_PASSWORD_FILE");
User adminUser;
if (!string.IsNullOrEmpty(adminPassword))
{
adminUser = CreateUser("Administrator", "admin", adminPassword);
}
else if (!string.IsNullOrEmpty(adminPasswordFile))
{
try
{
using (StreamReader sR = new StreamReader(adminPasswordFile, true))
{
string password = sR.ReadLine();
adminUser = CreateUser("Administrator", "admin", password);
}
}
catch (Exception ex)
{
_log.Write(ex);
adminUser = CreateUser("Administrator", "admin", "admin");
}
}
else
{
adminUser = CreateUser("Administrator", "admin", "admin");
}
adminUser.AddToGroup(adminGroup);
}
private async Task<User> AuthenticateUserAsync(string username, string password, string totp, IPAddress remoteAddress)
{
IPAddress network = GetClientNetwork(remoteAddress);
if (IsNetworkBlocked(network))
throw new DnsWebServiceException("Max limit of " + MAX_LOGIN_ATTEMPTS + " attempts exceeded. Access blocked for " + (BLOCK_NETWORK_INTERVAL / 1000) + " seconds.");
User user = GetUser(username);
if ((user is null) || user.IsSsoUser || !user.PasswordHash.Equals(user.GetPasswordHashFor(password), StringComparison.Ordinal))
{
if ((username != "admin") || (password != "admin"))
{
MarkFailedLoginAttempt(network);
if (HasLoginAttemptExceedLimit(network, MAX_LOGIN_ATTEMPTS))
BlockNetwork(network, BLOCK_NETWORK_INTERVAL);
}
await Task.Delay(1000);
throw new DnsWebServiceException("Invalid username or password for user: " + username);
}
if (user.TOTPEnabled)
{
if (string.IsNullOrEmpty(totp))
throw new TwoFactorAuthRequiredWebServiceException("A time-based one-time password (TOTP) is required for user: " + username);
Authenticator authenticator = new Authenticator(user.TOTPKeyUri);
if (!authenticator.IsTOTPValid(totp))
{
MarkFailedLoginAttempt(network);
if (HasLoginAttemptExceedLimit(network, MAX_LOGIN_ATTEMPTS))
BlockNetwork(network, BLOCK_NETWORK_INTERVAL);
await Task.Delay(1000);
throw new DnsWebServiceException("Invalid time-based one-time password (TOTP) was attempted for user: " + username);
}
}
ResetFailedLoginAttempts(network);
if (user.Disabled)
throw new DnsWebServiceException("User account is disabled. Please contact your administrator.");
return user;
}
private static IPAddress GetClientNetwork(IPAddress address)
{
switch (address.AddressFamily)
{
case AddressFamily.InterNetwork:
return address.GetNetworkAddress(32);
case AddressFamily.InterNetworkV6:
return address.GetNetworkAddress(64);
default:
throw new InvalidOperationException();
}
}
private void MarkFailedLoginAttempt(IPAddress network)
{
_failedLoginAttemptNetworks.AddOrUpdate(network, 1, delegate (IPAddress key, int attempts)
{
return attempts + 1;
});
}
private bool HasLoginAttemptExceedLimit(IPAddress network, int limit)
{
if (!_failedLoginAttemptNetworks.TryGetValue(network, out int attempts))
return false;
return attempts >= limit;
}
private void ResetFailedLoginAttempts(IPAddress network)
{
_failedLoginAttemptNetworks.TryRemove(network, out _);
}
private void BlockNetwork(IPAddress network, int interval)
{
_blockedNetworks.TryAdd(network, DateTime.UtcNow.AddMilliseconds(interval));
}
private bool IsNetworkBlocked(IPAddress network)
{
if (!_blockedNetworks.TryGetValue(network, out DateTime expiry))
return false;
if (expiry > DateTime.UtcNow)
{
return true;
}
else
{
UnblockNetwork(network);
ResetFailedLoginAttempts(network);
return false;
}
}
private void UnblockNetwork(IPAddress network)
{
_blockedNetworks.TryRemove(network, out _);
}
#endregion
#region public
public User GetUser(string username)
{
if (_users.TryGetValue(username.ToLowerInvariant(), out User user))
return user;
return null;
}
public User GetSsoUser(string ssoIdentifier)
{
foreach (KeyValuePair<string, User> user in _users)
{
if (ssoIdentifier.Equals(user.Value.SsoIdentifier, StringComparison.Ordinal) && user.Value.IsSsoUser)
return user.Value;
}
return null;
}
public User CreateUser(string displayName, string username, string password, int iterations = User.DEFAULT_ITERATIONS)
{
if (_users.Count >= byte.MaxValue)
throw new DnsWebServiceException("Cannot create more than 255 users.");
username = username.ToLowerInvariant();
User user = User.CreateLocalUser(displayName, username, password, iterations);
if (_users.TryAdd(username, user))
{
if (_users.Count > byte.MaxValue)
{
_users.TryRemove(username, out _); //undo
throw new DnsWebServiceException("Cannot create more than 255 users.");
}
user.AddToGroup(GetGroup(Group.EVERYONE));
return user;
}
throw new DnsWebServiceException("User already exists: " + username);
}
public User CreateSsoUser(string displayName, string username, string ssoIdentifier)
{
if (_users.Count >= byte.MaxValue)
throw new DnsWebServiceException("Cannot create more than 255 users.");
username = username.ToLowerInvariant();
User user = User.CreateSsoUser(displayName, username, ssoIdentifier);
if (_users.TryAdd(username, user))
{
if (_users.Count > byte.MaxValue)
{
_users.TryRemove(username, out _); //undo
throw new DnsWebServiceException("Cannot create more than 255 users.");
}
user.AddToGroup(GetGroup(Group.EVERYONE));
return user;
}
throw new DnsWebServiceException("User already exists: " + username);
}
public void ChangeUsername(User user, string newUsername)
{
if (user.Username.Equals(newUsername, StringComparison.OrdinalIgnoreCase))
return;
string oldUsername = user.Username;
user.SetUsername(newUsername);
if (!_users.TryAdd(user.Username, user))
{
user.SetUsername(oldUsername); //revert
throw new DnsWebServiceException("User already exists: " + newUsername);
}
_users.TryRemove(oldUsername, out _);
}
public async Task<User> ChangePasswordAsync(string username, string password, string totp, IPAddress remoteAddress, string newPassword, int iterations)
{
User user = await AuthenticateUserAsync(username, password, totp, remoteAddress);
user.ChangePassword(newPassword, iterations);
return user;
}
public bool DeleteUser(string username)
{
if (_users.TryRemove(username.ToLowerInvariant(), out User deletedUser))
{
//delete all sessions
foreach (UserSession session in GetSessions(deletedUser))
DeleteSession(session.Token);
//delete all permissions
foreach (KeyValuePair<PermissionSection, Permission> permission in _permissions)
{
permission.Value.RemovePermission(deletedUser);
permission.Value.RemoveAllSubItemPermissions(deletedUser);
}
return true;
}
return false;
}
public Group GetGroup(string name)
{
if (_groups.TryGetValue(name.ToLowerInvariant(), out Group group))
return group;
return null;
}
public List<User> GetGroupMembers(Group group)
{
List<User> members = new List<User>();
foreach (KeyValuePair<string, User> user in _users)
{
if (user.Value.IsMemberOfGroup(group))
members.Add(user.Value);
}
return members;
}
public void SyncGroupMembers(Group group, IReadOnlyDictionary<string, User> users)
{
//remove
foreach (KeyValuePair<string, User> user in _users)
{
if (!users.ContainsKey(user.Key))
user.Value.RemoveFromGroup(group);
}
//set
foreach (KeyValuePair<string, User> user in users)
user.Value.AddToGroup(group);
}
public Group CreateGroup(string name, string description)
{