/
Forest.cs
1208 lines (1005 loc) · 47.5 KB
/
Forest.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text;
using System.Collections;
using System.Globalization;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.DirectoryServices.ActiveDirectory
{
public enum ForestMode : int
{
Unknown = -1,
Windows2000Forest = 0,
Windows2003InterimForest = 1,
Windows2003Forest = 2,
Windows2008Forest = 3,
Windows2008R2Forest = 4,
Windows8Forest = 5,
Windows2012R2Forest = 6,
}
public class Forest : IDisposable
{
// Private Variables
private readonly DirectoryContext _context;
private readonly DirectoryEntryManager _directoryEntryMgr;
private bool _disposed;
// Internal variables corresponding to public properties
private readonly string _forestDnsName;
private ReadOnlySiteCollection? _cachedSites;
private DomainCollection? _cachedDomains;
private GlobalCatalogCollection? _cachedGlobalCatalogs;
private ApplicationPartitionCollection? _cachedApplicationPartitions;
private int _forestModeLevel = -1;
private Domain? _cachedRootDomain;
private ActiveDirectorySchema? _cachedSchema;
private DomainController? _cachedSchemaRoleOwner;
private DomainController? _cachedNamingRoleOwner;
#region constructors
internal Forest(DirectoryContext context, string forestDnsName, DirectoryEntryManager directoryEntryMgr)
{
_context = context;
_directoryEntryMgr = directoryEntryMgr;
_forestDnsName = forestDnsName;
}
internal Forest(DirectoryContext context, string name)
: this(context, name, new DirectoryEntryManager(context))
{
}
#endregion constructors
#region IDisposable
public void Dispose() => Dispose(true);
// private Dispose method
protected void Dispose(bool disposing)
{
if (!_disposed)
{
// check if this is an explicit Dispose
// only then clean up the directory entries
if (disposing)
{
// dispose all directory entries
foreach (DirectoryEntry entry in _directoryEntryMgr.GetCachedDirectoryEntries())
{
entry.Dispose();
}
}
_disposed = true;
}
}
#endregion IDisposable
#region public methods
public static Forest GetForest(DirectoryContext context)
{
DirectoryEntryManager? directoryEntryMgr = null;
DirectoryEntry? rootDSE = null;
string? rootDomainNC = null;
// check that the argument is not null
if (context == null)
throw new ArgumentNullException(nameof(context));
// contexttype should be Forest or DirectoryServer
if ((context.ContextType != DirectoryContextType.Forest) &&
(context.ContextType != DirectoryContextType.DirectoryServer))
{
throw new ArgumentException(SR.TargetShouldBeServerORForest, nameof(context));
}
if ((context.Name == null) && (!context.isRootDomain()))
{
throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(Forest), null);
}
if (context.Name != null)
{
// the target should be a valid forest name or a server
if (!((context.isRootDomain()) || (context.isServer())))
{
if (context.ContextType == DirectoryContextType.Forest)
{
throw new ActiveDirectoryObjectNotFoundException(SR.ForestNotFound, typeof(Forest), context.Name);
}
else
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound, context.Name), typeof(Forest), null);
}
}
}
// work with copy of the context
context = new DirectoryContext(context);
directoryEntryMgr = new DirectoryEntryManager(context);
// at this point we know that the target is either a
// valid forest name or a server (may be a bogus server name -- to check bind to rootdse)
// bind to the rootDSE of the forest specified in the context
try
{
rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory)))
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound, context.Name), typeof(Forest), null);
}
rootDomainNC = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.RootDomainNamingContext)!;
}
catch (COMException e)
{
int errorCode = e.ErrorCode;
if (errorCode == unchecked((int)0x8007203a))
{
if (context.ContextType == DirectoryContextType.Forest)
{
throw new ActiveDirectoryObjectNotFoundException(SR.ForestNotFound, typeof(Forest), context.Name);
}
else
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound, context.Name), typeof(Forest), null);
}
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
// return forest object
return new Forest(context, Utils.GetDnsNameFromDN(rootDomainNC), directoryEntryMgr);
}
public void RaiseForestFunctionalityLevel(int forestMode)
{
CheckIfDisposed();
// check new functional level is valid or not
if (forestMode < 0)
{
throw new ArgumentException(SR.InvalidMode, nameof(forestMode));
}
// new functional level should be higher than the old one
if (forestMode <= ForestModeLevel)
{
throw new ArgumentException(SR.InvalidMode, nameof(forestMode));
}
// set the forest mode on AD
DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(_context, _directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
// NOTE:
// If the domain is a W2K domain (W2K schema) then the msDS-Behavior-Version attribute will not be present.
// If that is the case, the forest functionality cannot be raised.
try
{
partitionsEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = forestMode;
partitionsEntry.CommitChanges();
}
catch (System.Runtime.InteropServices.COMException e)
{
if (e.ErrorCode == unchecked((int)0x8007200A))
{
throw new ArgumentException(SR.NoW2K3DCsInForest, nameof(forestMode));
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
finally
{
partitionsEntry.Dispose();
}
// at this point the raise forest function has succeeded
// invalidate the cached entry so that we will go to the server next time
_forestModeLevel = -1;
}
public void RaiseForestFunctionality(ForestMode forestMode)
{
CheckIfDisposed();
// check if forest mode is a valid enum value
if (forestMode < ForestMode.Windows2000Forest)
{
throw new InvalidEnumArgumentException(nameof(forestMode), (int)forestMode, typeof(ForestMode));
}
if (forestMode <= ForestMode)
{
throw new ArgumentException(SR.InvalidMode, nameof(forestMode));
}
RaiseForestFunctionalityLevel((int)forestMode);
}
public override string ToString() => Name;
public GlobalCatalog FindGlobalCatalog()
{
CheckIfDisposed();
return GlobalCatalog.FindOneInternal(_context, Name, null, 0);
}
public GlobalCatalog FindGlobalCatalog(string siteName)
{
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
return GlobalCatalog.FindOneInternal(_context, Name, siteName, 0);
}
public GlobalCatalog FindGlobalCatalog(LocatorOptions flag)
{
CheckIfDisposed();
return GlobalCatalog.FindOneInternal(_context, Name, null, flag);
}
public GlobalCatalog FindGlobalCatalog(string siteName, LocatorOptions flag)
{
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
return GlobalCatalog.FindOneInternal(_context, Name, siteName, flag);
}
public GlobalCatalogCollection FindAllGlobalCatalogs()
{
CheckIfDisposed();
return GlobalCatalog.FindAllInternal(_context, null);
}
public GlobalCatalogCollection FindAllGlobalCatalogs(string siteName)
{
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
return GlobalCatalog.FindAllInternal(_context, siteName);
}
public GlobalCatalogCollection FindAllDiscoverableGlobalCatalogs()
{
long flag = (long)PrivateLocatorFlags.GCRequired;
CheckIfDisposed();
return new GlobalCatalogCollection(Locator.EnumerateDomainControllers(_context, Name, null, flag));
}
public GlobalCatalogCollection FindAllDiscoverableGlobalCatalogs(string siteName)
{
long flag = (long)PrivateLocatorFlags.GCRequired;
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
if (siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName));
}
return new GlobalCatalogCollection(Locator.EnumerateDomainControllers(_context, Name, siteName, flag));
}
public TrustRelationshipInformationCollection GetAllTrustRelationships()
{
CheckIfDisposed();
return GetTrustsHelper(null);
}
public ForestTrustRelationshipInformation GetTrustRelationship(string targetForestName)
{
CheckIfDisposed();
if (targetForestName == null)
throw new ArgumentNullException(nameof(targetForestName));
if (targetForestName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetForestName));
TrustRelationshipInformationCollection collection = GetTrustsHelper(targetForestName);
if (collection.Count != 0)
{
Debug.Assert(collection.Count == 1);
return (ForestTrustRelationshipInformation)collection[0];
}
else
{
// trust relationship does not exist
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist, Name, targetForestName), typeof(TrustRelationshipInformation), null);
}
}
public bool GetSelectiveAuthenticationStatus(string targetForestName)
{
CheckIfDisposed();
if (targetForestName == null)
throw new ArgumentNullException(nameof(targetForestName));
if (targetForestName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetForestName));
return TrustHelper.GetTrustedDomainInfoStatus(_context, Name, targetForestName, TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_CROSS_ORGANIZATION, true);
}
public void SetSelectiveAuthenticationStatus(string targetForestName, bool enable)
{
CheckIfDisposed();
if (targetForestName == null)
throw new ArgumentNullException(nameof(targetForestName));
if (targetForestName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetForestName));
TrustHelper.SetTrustedDomainInfoStatus(_context, Name, targetForestName, TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_CROSS_ORGANIZATION, enable, true);
}
public bool GetSidFilteringStatus(string targetForestName)
{
CheckIfDisposed();
if (targetForestName == null)
throw new ArgumentNullException(nameof(targetForestName));
if (targetForestName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetForestName));
return TrustHelper.GetTrustedDomainInfoStatus(_context, Name, targetForestName, TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_TREAT_AS_EXTERNAL, true);
}
public void SetSidFilteringStatus(string targetForestName, bool enable)
{
CheckIfDisposed();
if (targetForestName == null)
throw new ArgumentNullException(nameof(targetForestName));
if (targetForestName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetForestName));
TrustHelper.SetTrustedDomainInfoStatus(_context, Name, targetForestName, TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_TREAT_AS_EXTERNAL, enable, true);
}
public void DeleteLocalSideOfTrustRelationship(string targetForestName)
{
CheckIfDisposed();
if (targetForestName == null)
throw new ArgumentNullException(nameof(targetForestName));
if (targetForestName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetForestName));
// delete local side of trust only
TrustHelper.DeleteTrust(_context, Name, targetForestName, true);
}
public void DeleteTrustRelationship(Forest targetForest)
{
CheckIfDisposed();
if (targetForest == null)
throw new ArgumentNullException(nameof(targetForest));
// first delete the trust on the remote side
TrustHelper.DeleteTrust(targetForest.GetDirectoryContext(), targetForest.Name, Name, true);
// then delete the local side trust
TrustHelper.DeleteTrust(_context, Name, targetForest.Name, true);
}
public void VerifyOutboundTrustRelationship(string targetForestName)
{
CheckIfDisposed();
if (targetForestName == null)
throw new ArgumentNullException(nameof(targetForestName));
if (targetForestName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetForestName));
TrustHelper.VerifyTrust(_context, Name, targetForestName, true/*forest*/, TrustDirection.Outbound, false /*just TC verification*/, null /* no need to go to specific server*/);
}
public void VerifyTrustRelationship(Forest targetForest, TrustDirection direction)
{
CheckIfDisposed();
if (targetForest == null)
throw new ArgumentNullException(nameof(targetForest));
if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(direction), (int)direction, typeof(TrustDirection));
// verify outbound trust first
if ((direction & TrustDirection.Outbound) != 0)
{
try
{
TrustHelper.VerifyTrust(_context, Name, targetForest.Name, true/*forest*/, TrustDirection.Outbound, false/*just TC verification*/, null /* no need to go to specific server*/);
}
catch (ActiveDirectoryObjectNotFoundException)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection, Name, targetForest.Name, direction), typeof(ForestTrustRelationshipInformation), null);
}
}
// verify inbound trust
if ((direction & TrustDirection.Inbound) != 0)
{
try
{
TrustHelper.VerifyTrust(targetForest.GetDirectoryContext(), targetForest.Name, Name, true/*forest*/, TrustDirection.Outbound, false/*just TC verification*/, null /* no need to go to specific server*/);
}
catch (ActiveDirectoryObjectNotFoundException)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection, Name, targetForest.Name, direction), typeof(ForestTrustRelationshipInformation), null);
}
}
}
public void CreateLocalSideOfTrustRelationship(string targetForestName, TrustDirection direction, string trustPassword)
{
CheckIfDisposed();
if (targetForestName == null)
throw new ArgumentNullException(nameof(targetForestName));
if (targetForestName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetForestName));
if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(direction), (int)direction, typeof(TrustDirection));
if (trustPassword == null)
throw new ArgumentNullException(nameof(trustPassword));
if (trustPassword.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(trustPassword));
// verify first that the target forest name is valid
Locator.GetDomainControllerInfo(null, targetForestName, null, (long)(PrivateLocatorFlags.DirectoryServicesRequired | PrivateLocatorFlags.GCRequired));
DirectoryContext targetContext = Utils.GetNewDirectoryContext(targetForestName, DirectoryContextType.Forest, _context);
TrustHelper.CreateTrust(_context, Name, targetContext, targetForestName, true, direction, trustPassword);
}
public void CreateTrustRelationship(Forest targetForest, TrustDirection direction)
{
CheckIfDisposed();
if (targetForest == null)
throw new ArgumentNullException(nameof(targetForest));
if (direction < TrustDirection.Inbound || direction > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(direction), (int)direction, typeof(TrustDirection));
string password = TrustHelper.CreateTrustPassword();
// first create trust on local side
TrustHelper.CreateTrust(_context, Name, targetForest.GetDirectoryContext(), targetForest.Name, true, direction, password);
// then create trust on remote side
int reverseDirection = 0;
if ((direction & TrustDirection.Inbound) != 0)
reverseDirection |= (int)TrustDirection.Outbound;
if ((direction & TrustDirection.Outbound) != 0)
reverseDirection |= (int)TrustDirection.Inbound;
TrustHelper.CreateTrust(targetForest.GetDirectoryContext(), targetForest.Name, _context, Name, true, (TrustDirection)reverseDirection, password);
}
public void UpdateLocalSideOfTrustRelationship(string targetForestName, string newTrustPassword)
{
CheckIfDisposed();
if (targetForestName == null)
throw new ArgumentNullException(nameof(targetForestName));
if (targetForestName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetForestName));
if (newTrustPassword == null)
throw new ArgumentNullException(nameof(newTrustPassword));
if (newTrustPassword.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(newTrustPassword));
TrustHelper.UpdateTrust(_context, Name, targetForestName, newTrustPassword, true);
}
public void UpdateLocalSideOfTrustRelationship(string targetForestName, TrustDirection newTrustDirection, string newTrustPassword)
{
CheckIfDisposed();
if (targetForestName == null)
throw new ArgumentNullException(nameof(targetForestName));
if (targetForestName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(targetForestName));
if (newTrustDirection < TrustDirection.Inbound || newTrustDirection > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(newTrustDirection), (int)newTrustDirection, typeof(TrustDirection));
if (newTrustPassword == null)
throw new ArgumentNullException(nameof(newTrustPassword));
if (newTrustPassword.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(newTrustPassword));
TrustHelper.UpdateTrustDirection(_context, Name, targetForestName, newTrustPassword, true /*is forest*/, newTrustDirection);
}
public void UpdateTrustRelationship(Forest targetForest, TrustDirection newTrustDirection)
{
CheckIfDisposed();
if (targetForest == null)
throw new ArgumentNullException(nameof(targetForest));
if (newTrustDirection < TrustDirection.Inbound || newTrustDirection > TrustDirection.Bidirectional)
throw new InvalidEnumArgumentException(nameof(newTrustDirection), (int)newTrustDirection, typeof(TrustDirection));
// no we generate trust password
string password = TrustHelper.CreateTrustPassword();
TrustHelper.UpdateTrustDirection(_context, Name, targetForest.Name, password, true /*is forest*/, newTrustDirection);
// then create trust on remote side
TrustDirection reverseDirection = 0;
if ((newTrustDirection & TrustDirection.Inbound) != 0)
reverseDirection |= TrustDirection.Outbound;
if ((newTrustDirection & TrustDirection.Outbound) != 0)
reverseDirection |= TrustDirection.Inbound;
TrustHelper.UpdateTrustDirection(targetForest.GetDirectoryContext(), targetForest.Name, Name, password, true /*is forest*/, reverseDirection);
}
public void RepairTrustRelationship(Forest targetForest)
{
TrustDirection direction = TrustDirection.Bidirectional;
CheckIfDisposed();
if (targetForest == null)
throw new ArgumentNullException(nameof(targetForest));
// first try to reset the secure channel
try
{
direction = GetTrustRelationship(targetForest.Name).TrustDirection;
// verify outbound trust first
if ((direction & TrustDirection.Outbound) != 0)
{
TrustHelper.VerifyTrust(_context, Name, targetForest.Name, true /*is forest*/, TrustDirection.Outbound, true/*reset secure channel*/, null /* no need to go to specific server*/);
}
// verify inbound trust
if ((direction & TrustDirection.Inbound) != 0)
{
TrustHelper.VerifyTrust(targetForest.GetDirectoryContext(), targetForest.Name, Name, true/*is forest*/, TrustDirection.Outbound, true/*reset secure channel*/, null /* no need to go to specific server*/);
}
}
catch (ActiveDirectoryOperationException)
{
RepairTrustHelper(targetForest, direction);
}
catch (UnauthorizedAccessException)
{
RepairTrustHelper(targetForest, direction);
}
catch (ActiveDirectoryObjectNotFoundException)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection, Name, targetForest.Name, direction), typeof(ForestTrustRelationshipInformation), null);
}
}
public static Forest GetCurrentForest() => GetForest(new DirectoryContext(DirectoryContextType.Forest));
#endregion public methods
#region public properties
public string Name
{
get
{
CheckIfDisposed();
return _forestDnsName;
}
}
public ReadOnlySiteCollection Sites
{
get
{
CheckIfDisposed();
return _cachedSites ??= new ReadOnlySiteCollection(GetSites());
}
}
public DomainCollection Domains
{
get
{
CheckIfDisposed();
return _cachedDomains ??= new DomainCollection(GetDomains());
}
}
public GlobalCatalogCollection GlobalCatalogs
{
get
{
CheckIfDisposed();
return _cachedGlobalCatalogs ??= FindAllGlobalCatalogs();
}
}
public ApplicationPartitionCollection ApplicationPartitions
{
get
{
CheckIfDisposed();
return _cachedApplicationPartitions ??= new ApplicationPartitionCollection(GetApplicationPartitions());
}
}
public int ForestModeLevel
{
get
{
CheckIfDisposed();
if (_forestModeLevel == -1)
{
_forestModeLevel = GetForestModeLevel();
}
return _forestModeLevel;
}
}
public ForestMode ForestMode
{
get
{
CheckIfDisposed();
// if forest mode is known cast to proper enum
if (ForestModeLevel <= (int)ForestMode.Windows2012R2Forest)
{
return (ForestMode)ForestModeLevel;
}
// else return unknown
return ForestMode.Unknown;
}
}
public Domain RootDomain
{
get
{
CheckIfDisposed();
if (_cachedRootDomain == null)
{
// Domain context is created by passing the name of the forest
// (since the root domain and the forest have the same name)
DirectoryContext domainContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.Domain, _context);
_cachedRootDomain = new Domain(domainContext, Name);
}
return _cachedRootDomain;
}
}
public ActiveDirectorySchema Schema
{
get
{
CheckIfDisposed();
if (_cachedSchema == null)
{
try
{
_cachedSchema = new ActiveDirectorySchema(_context, _directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext));
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
}
return _cachedSchema;
}
}
public DomainController SchemaRoleOwner
{
get
{
CheckIfDisposed();
return _cachedSchemaRoleOwner ??= GetRoleOwner(ActiveDirectoryRole.SchemaRole);
}
}
public DomainController NamingRoleOwner
{
get
{
CheckIfDisposed();
return _cachedNamingRoleOwner ??= GetRoleOwner(ActiveDirectoryRole.NamingRole);
}
}
#endregion public properties
#region private methods
internal DirectoryContext GetDirectoryContext() => _context;
private int GetForestModeLevel()
{
int forestModeValue = -1;
DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.RootDSE);
try
{
if (!rootDSE.Properties.Contains(PropertyManager.ForestFunctionality))
{
// Since this value is not set, it is a Win2000 forest (with W2K schema)
forestModeValue = 0;
}
else
{
forestModeValue = int.Parse((string)rootDSE.Properties[PropertyManager.ForestFunctionality].Value!, NumberFormatInfo.InvariantInfo);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
finally
{
rootDSE.Dispose();
}
return forestModeValue;
}
//
// Returns a DomainController object for the DC that holds the specified FSMO role
//
private DomainController GetRoleOwner(ActiveDirectoryRole role)
{
DirectoryEntry? entry = null;
string? dcName = null;
try
{
switch (role)
{
case ActiveDirectoryRole.SchemaRole:
{
entry = DirectoryEntryManager.GetDirectoryEntry(_context, _directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext));
break;
}
case ActiveDirectoryRole.NamingRole:
{
entry = DirectoryEntryManager.GetDirectoryEntry(_context, _directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
break;
}
default:
// should not happen since we are calling this only internally
Debug.Fail("Forest.GetRoleOwner: Invalid role type.");
break;
}
dcName = Utils.GetDnsHostNameFromNTDSA(_context, (string)PropertyManager.GetPropertyValue(_context, entry, PropertyManager.FsmoRoleOwner)!);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
finally
{
entry?.Dispose();
}
// create a new context object for the domain controller passing on the
// credentials from the forest context
DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, _context);
return new DomainController(dcContext, dcName);
}
private unsafe ArrayList GetSites()
{
ArrayList sites = new ArrayList();
int result = 0;
IntPtr dsHandle = IntPtr.Zero;
IntPtr authIdentity = IntPtr.Zero;
IntPtr sitesPtr = IntPtr.Zero;
try
{
// get the directory handle
GetDSHandle(out dsHandle, out authIdentity);
// Get the sites within the forest
// call DsListSites
/*DWORD DsListSites(
HANDLE hDs,
PDS_NAME_RESULT* ppSites
);*/
var dsListSites = (delegate* unmanaged<IntPtr, IntPtr*, int>)global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListSitesW");
if (dsListSites == null)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastPInvokeError());
}
result = dsListSites(dsHandle, &sitesPtr);
if (result == 0)
{
try
{
DsNameResult dsNameResult = new DsNameResult();
Marshal.PtrToStructure(sitesPtr, dsNameResult);
IntPtr currentItem = dsNameResult.items;
for (int i = 0; i < dsNameResult.itemCount; i++)
{
DsNameResultItem dsNameResultItem = new DsNameResultItem();
Marshal.PtrToStructure(currentItem, dsNameResultItem);
if (dsNameResultItem.status == NativeMethods.DsNameNoError)
{
string siteName = Utils.GetDNComponents(dsNameResultItem.name!)[0].Value!;
// an existing site
sites.Add(new ActiveDirectorySite(_context, siteName, true));
}
currentItem = IntPtr.Add(currentItem, Marshal.SizeOf(dsNameResultItem));
}
}
finally
{
// free the DsNameResult structure
if (sitesPtr != IntPtr.Zero)
{
// call DsFreeNameResultW
var dsFreeNameResultW = (delegate* unmanaged<IntPtr, void>)global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
if (dsFreeNameResultW == null)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastPInvokeError());
}
dsFreeNameResultW(sitesPtr);
}
}
}
else
{
throw ExceptionHelper.GetExceptionFromErrorCode(result, _context.GetServerName());
}
}
finally
{
// DsUnbind
if (dsHandle != (IntPtr)0)
{
Utils.FreeDSHandle(dsHandle, DirectoryContext.ADHandle);
}
// free the credentials object
if (authIdentity != (IntPtr)0)
{
Utils.FreeAuthIdentity(authIdentity, DirectoryContext.ADHandle);
}
}
return sites;
}
private ArrayList GetApplicationPartitions()
{
ArrayList appNCs = new ArrayList();
DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(_context, _directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
// search for all the "crossRef" objects that have the
// ADS_SYSTEMFLAG_CR_NTDS_NC set and the SYSTEMFLAG_CR_NTDS_DOMAIN flag not set
// (one-level search is good enough)
// setup the directory searcher object
// build the filter
StringBuilder str = new StringBuilder(15);
str.Append("(&(");
str.Append(PropertyManager.ObjectCategory);
str.Append("=crossRef)(");
str.Append(PropertyManager.SystemFlags);
str.Append(":1.2.840.113556.1.4.804:=");
str.Append((int)SystemFlag.SystemFlagNtdsNC);
str.Append(")(!(");
str.Append(PropertyManager.SystemFlags);
str.Append(":1.2.840.113556.1.4.803:=");
str.Append((int)SystemFlag.SystemFlagNtdsDomain);
str.Append(")))");
string filter = str.ToString();
string[] propertiesToLoad = new string[2];
propertiesToLoad[0] = PropertyManager.DnsRoot;
propertiesToLoad[1] = PropertyManager.NCName;
ADSearcher searcher = new ADSearcher(partitionsEntry, filter, propertiesToLoad, SearchScope.OneLevel);
SearchResultCollection? resCol = null;
try
{
resCol = searcher.FindAll();
string schemaNamingContext = _directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext);
string configurationNamingContext = _directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.ConfigurationNamingContext);
foreach (SearchResult res in resCol)
{
// add the name of the appNC only if it is not
// the Schema or Configuration partition
string nCName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.NCName)!;
if ((!(nCName.Equals(schemaNamingContext)))
&& (!(nCName.Equals(configurationNamingContext))))
{
// create a new context to be passed on to the appNC object
// (pass the dns name of the appliction partition as the target)
string dnsName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.DnsRoot)!;
DirectoryContext appNCContext = Utils.GetNewDirectoryContext(dnsName, DirectoryContextType.ApplicationPartition, _context);
appNCs.Add(new ApplicationPartition(appNCContext, nCName, (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.DnsRoot)!, ApplicationPartitionType.ADApplicationPartition, new DirectoryEntryManager(appNCContext)));
}
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
}
finally
{
resCol?.Dispose();
partitionsEntry.Dispose();
}
return appNCs;
}
private ArrayList GetDomains()