/
ActiveDirectorySchema.cs
560 lines (485 loc) · 22.2 KB
/
ActiveDirectorySchema.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
namespace System.DirectoryServices.ActiveDirectory
{
public enum SchemaClassType : int
{
Type88 = 0,
Structural = 1,
Abstract = 2,
Auxiliary = 3
}
[Flags]
public enum PropertyTypes : int
{
Indexed = 2,
InGlobalCatalog = 4
}
public class ActiveDirectorySchema : ActiveDirectoryPartition
{
private bool _disposed;
private DirectoryEntry _schemaEntry;
private DirectoryEntry? _abstractSchemaEntry;
private DirectoryServer? _cachedSchemaRoleOwner;
#region constructors
internal ActiveDirectorySchema(DirectoryContext context, string distinguishedName)
: base(context, distinguishedName)
{
this.directoryEntryMgr = new DirectoryEntryManager(context);
_schemaEntry = DirectoryEntryManager.GetDirectoryEntry(context, distinguishedName);
}
internal ActiveDirectorySchema(DirectoryContext context, string distinguishedName, DirectoryEntryManager directoryEntryMgr)
: base(context, distinguishedName)
{
this.directoryEntryMgr = directoryEntryMgr;
_schemaEntry = DirectoryEntryManager.GetDirectoryEntry(context, distinguishedName);
}
#endregion constructors
#region IDisposable
// private Dispose method
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
try
{
// if there are any managed or unmanaged
// resources to be freed, those should be done here
// if not an explicit dispose only unmanaged resources should
// be disposed
if (disposing)
{
// dispose schema entry
if (_schemaEntry != null)
{
_schemaEntry.Dispose();
_schemaEntry = null!;
}
// dispose the abstract schema entry
if (_abstractSchemaEntry != null)
{
_abstractSchemaEntry.Dispose();
_abstractSchemaEntry = null;
}
}
_disposed = true;
}
finally
{
base.Dispose();
}
}
}
#endregion IDisposable
#region public methods
public static ActiveDirectorySchema GetSchema(DirectoryContext context)
{
ArgumentNullException.ThrowIfNull(context);
// contexttype should be Forest, DirectoryServer or ConfigurationSet
if ((context.ContextType != DirectoryContextType.Forest) &&
(context.ContextType != DirectoryContextType.ConfigurationSet) &&
(context.ContextType != DirectoryContextType.DirectoryServer))
{
throw new ArgumentException(SR.NotADOrADAM, nameof(context));
}
if ((context.Name == null) && (!context.isRootDomain()))
{
throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(ActiveDirectorySchema), null);
}
if (context.Name != null)
{
// the target should be a valid forest name or a server
if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || (context.isServer())))
{
if (context.ContextType == DirectoryContextType.Forest)
{
throw new ActiveDirectoryObjectNotFoundException(SR.ForestNotFound, typeof(ActiveDirectorySchema), context.Name);
}
else if (context.ContextType == DirectoryContextType.ConfigurationSet)
{
throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ActiveDirectorySchema), context.Name);
}
else
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ServerNotFound, context.Name), typeof(ActiveDirectorySchema), null);
}
}
}
// work with copy of the context
context = new DirectoryContext(context);
DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context);
string schemaNC;
try
{
DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryOrADAM)))
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ServerNotFound, context.Name), typeof(ActiveDirectorySchema), null);
}
schemaNC = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.SchemaNamingContext)!;
}
catch (COMException e)
{
int errorCode = e.ErrorCode;
if (errorCode == unchecked((int)0x8007203a))
{
if (context.ContextType == DirectoryContextType.Forest)
{
throw new ActiveDirectoryObjectNotFoundException(SR.ForestNotFound, typeof(ActiveDirectorySchema), context.Name);
}
else if (context.ContextType == DirectoryContextType.ConfigurationSet)
{
throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ActiveDirectorySchema), context.Name);
}
else
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ServerNotFound, context.Name), typeof(ActiveDirectorySchema), null);
}
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
catch (ActiveDirectoryObjectNotFoundException)
{
if (context.ContextType == DirectoryContextType.ConfigurationSet)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ActiveDirectorySchema), context.Name);
}
else
throw;
}
return new ActiveDirectorySchema(context, schemaNC, directoryEntryMgr);
}
public void RefreshSchema()
{
CheckIfDisposed();
// Refresh the schema on the server
DirectoryEntry? rootDSE = null;
try
{
rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
rootDSE.Properties[PropertyManager.SchemaUpdateNow].Value = 1;
rootDSE.CommitChanges();
// refresh the schema on the client
// bind to the abstract schema
_abstractSchemaEntry ??= directoryEntryMgr.GetCachedDirectoryEntry("Schema");
_abstractSchemaEntry.RefreshCache();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
rootDSE?.Dispose();
}
}
//
// This method finds only among non-defunct classes
//
public ActiveDirectorySchemaClass FindClass(string ldapDisplayName)
{
CheckIfDisposed();
return ActiveDirectorySchemaClass.FindByName(context, ldapDisplayName);
}
//
// This method finds only among defunct classes
//
public ActiveDirectorySchemaClass FindDefunctClass(string commonName)
{
CheckIfDisposed();
if (commonName == null)
{
throw new ArgumentNullException(nameof(commonName));
}
if (commonName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(commonName));
}
// this will bind to the schema container and load the properties of this class
// (will also check whether or not the class exists)
Hashtable propertiesFromServer = ActiveDirectorySchemaClass.GetPropertiesFromSchemaContainer(context, _schemaEntry, commonName, true /* isDefunctOnServer */);
ActiveDirectorySchemaClass schemaClass = new ActiveDirectorySchemaClass(context, commonName, propertiesFromServer, _schemaEntry);
return schemaClass;
}
//
// This method returns only non-defunct classes
//
public ReadOnlyActiveDirectorySchemaClassCollection FindAllClasses()
{
CheckIfDisposed();
string filter = "(&(" + PropertyManager.ObjectCategory + "=classSchema)" +
"(!(" + PropertyManager.IsDefunct + "=TRUE)))";
return GetAllClasses(context, _schemaEntry, filter);
}
//
// This method returns only non-defunct classes of the specified type
//
public ReadOnlyActiveDirectorySchemaClassCollection FindAllClasses(SchemaClassType type)
{
CheckIfDisposed();
// validate the type
if (type < SchemaClassType.Type88 || type > SchemaClassType.Auxiliary)
{
throw new InvalidEnumArgumentException(nameof(type), (int)type, typeof(SchemaClassType));
}
string filter = "(&(" + PropertyManager.ObjectCategory + "=classSchema)" +
"(" + PropertyManager.ObjectClassCategory + "=" + (int)type + ")" +
"(!(" + PropertyManager.IsDefunct + "=TRUE)))";
return GetAllClasses(context, _schemaEntry, filter);
}
//
// This method returns only defunct classes
//
public ReadOnlyActiveDirectorySchemaClassCollection FindAllDefunctClasses()
{
CheckIfDisposed();
string filter = "(&(" + PropertyManager.ObjectCategory + "=classSchema)" +
"(" + PropertyManager.IsDefunct + "=TRUE))";
return GetAllClasses(context, _schemaEntry, filter);
}
//
// This method finds only among non-defunct properties
//
public ActiveDirectorySchemaProperty FindProperty(string ldapDisplayName)
{
CheckIfDisposed();
return ActiveDirectorySchemaProperty.FindByName(context, ldapDisplayName);
}
//
// This method finds only among defunct properties
//
public ActiveDirectorySchemaProperty FindDefunctProperty(string commonName)
{
CheckIfDisposed();
if (commonName == null)
{
throw new ArgumentNullException(nameof(commonName));
}
if (commonName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(commonName));
}
// this will bind to the schema container and load the properties of this property
// (will also check whether or not the property exists)
SearchResult propertiesFromServer = ActiveDirectorySchemaProperty.GetPropertiesFromSchemaContainer(context, _schemaEntry, commonName, true /* isDefunctOnServer */);
ActiveDirectorySchemaProperty schemaProperty = new ActiveDirectorySchemaProperty(context, commonName, propertiesFromServer, _schemaEntry);
return schemaProperty;
}
//
// This method returns only non-defunct properties
//
public ReadOnlyActiveDirectorySchemaPropertyCollection FindAllProperties()
{
CheckIfDisposed();
string filter = "(&(" + PropertyManager.ObjectCategory + "=attributeSchema)" +
"(!(" + PropertyManager.IsDefunct + "=TRUE)))";
return GetAllProperties(context, _schemaEntry, filter);
}
//
// This method returns only non-defunct properties meeting the specified criteria
//
public ReadOnlyActiveDirectorySchemaPropertyCollection FindAllProperties(PropertyTypes type)
{
CheckIfDisposed();
// check validity of type
if ((type & (~(PropertyTypes.Indexed | PropertyTypes.InGlobalCatalog))) != 0)
{
throw new ArgumentException(SR.InvalidFlags, nameof(type));
}
// start the filter
StringBuilder str = new StringBuilder(25);
str.Append("(&(");
str.Append(PropertyManager.ObjectCategory);
str.Append("=attributeSchema)");
str.Append("(!(");
str.Append(PropertyManager.IsDefunct);
str.Append("=TRUE))");
if (((int)type & (int)PropertyTypes.Indexed) != 0)
{
str.Append('(');
str.Append(PropertyManager.SearchFlags);
str.Append(":1.2.840.113556.1.4.804:=");
str.Append((int)SearchFlags.IsIndexed);
str.Append(')');
}
if (((int)type & (int)PropertyTypes.InGlobalCatalog) != 0)
{
str.Append('(');
str.Append(PropertyManager.IsMemberOfPartialAttributeSet);
str.Append("=TRUE)");
}
str.Append(')'); // end filter
return GetAllProperties(context, _schemaEntry, str.ToString());
}
//
// This method returns only defunct properties
//
public ReadOnlyActiveDirectorySchemaPropertyCollection FindAllDefunctProperties()
{
CheckIfDisposed();
string filter = "(&(" + PropertyManager.ObjectCategory + "=attributeSchema)" +
"(" + PropertyManager.IsDefunct + "=TRUE))";
return GetAllProperties(context, _schemaEntry, filter);
}
public override DirectoryEntry GetDirectoryEntry()
{
CheckIfDisposed();
return DirectoryEntryManager.GetDirectoryEntry(context, Name);
}
public static ActiveDirectorySchema GetCurrentSchema()
{
return ActiveDirectorySchema.GetSchema(new DirectoryContext(DirectoryContextType.Forest));
}
#endregion public methods
#region public properties
public DirectoryServer SchemaRoleOwner
{
get
{
CheckIfDisposed();
return _cachedSchemaRoleOwner ??= GetSchemaRoleOwner();
}
}
#endregion public properties
#region private methods
internal static ReadOnlyActiveDirectorySchemaPropertyCollection GetAllProperties(DirectoryContext context, DirectoryEntry schemaEntry, string filter)
{
ArrayList propertyList = new ArrayList();
string[] propertiesToLoad = new string[3];
propertiesToLoad[0] = PropertyManager.LdapDisplayName;
propertiesToLoad[1] = PropertyManager.Cn;
propertiesToLoad[2] = PropertyManager.IsDefunct;
ADSearcher searcher = new ADSearcher(schemaEntry, filter, propertiesToLoad, SearchScope.OneLevel);
SearchResultCollection? resCol = null;
try
{
resCol = searcher.FindAll();
foreach (SearchResult res in resCol)
{
string ldapDisplayName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.LdapDisplayName)!;
DirectoryEntry directoryEntry = res.GetDirectoryEntry();
directoryEntry.AuthenticationType = Utils.DefaultAuthType;
directoryEntry.Username = context.UserName;
directoryEntry.Password = context.Password;
bool isDefunct = false;
if ((res.Properties[PropertyManager.IsDefunct] != null) && (res.Properties[PropertyManager.IsDefunct].Count > 0))
{
isDefunct = (bool)res.Properties[PropertyManager.IsDefunct][0]!;
}
if (isDefunct)
{
string commonName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.Cn)!;
propertyList.Add(new ActiveDirectorySchemaProperty(context, commonName, ldapDisplayName, directoryEntry, schemaEntry));
}
else
{
propertyList.Add(new ActiveDirectorySchemaProperty(context, ldapDisplayName, directoryEntry, schemaEntry));
}
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
// dispose off the result collection
resCol?.Dispose();
}
return new ReadOnlyActiveDirectorySchemaPropertyCollection(propertyList);
}
internal static ReadOnlyActiveDirectorySchemaClassCollection GetAllClasses(DirectoryContext context, DirectoryEntry schemaEntry, string filter)
{
ArrayList classList = new ArrayList();
string[] propertiesToLoad = new string[3];
propertiesToLoad[0] = PropertyManager.LdapDisplayName;
propertiesToLoad[1] = PropertyManager.Cn;
propertiesToLoad[2] = PropertyManager.IsDefunct;
ADSearcher searcher = new ADSearcher(schemaEntry, filter, propertiesToLoad, SearchScope.OneLevel);
SearchResultCollection? resCol = null;
try
{
resCol = searcher.FindAll();
foreach (SearchResult res in resCol)
{
string ldapDisplayName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.LdapDisplayName)!;
DirectoryEntry directoryEntry = res.GetDirectoryEntry();
directoryEntry.AuthenticationType = Utils.DefaultAuthType;
directoryEntry.Username = context.UserName;
directoryEntry.Password = context.Password;
bool isDefunct = false;
if ((res.Properties[PropertyManager.IsDefunct] != null) && (res.Properties[PropertyManager.IsDefunct].Count > 0))
{
isDefunct = (bool)res.Properties[PropertyManager.IsDefunct][0]!;
}
if (isDefunct)
{
string commonName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.Cn)!;
classList.Add(new ActiveDirectorySchemaClass(context, commonName, ldapDisplayName, directoryEntry, schemaEntry));
}
else
{
classList.Add(new ActiveDirectorySchemaClass(context, ldapDisplayName, directoryEntry, schemaEntry));
}
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
// dispose off the result collection
resCol?.Dispose();
}
return new ReadOnlyActiveDirectorySchemaClassCollection(classList);
}
private DirectoryServer GetSchemaRoleOwner()
{
try
{
_schemaEntry.RefreshCache();
if (context.isADAMConfigSet())
{
// ADAM
string adamInstName = Utils.GetAdamDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, _schemaEntry, PropertyManager.FsmoRoleOwner)!);
DirectoryContext adamInstContext = Utils.GetNewDirectoryContext(adamInstName, DirectoryContextType.DirectoryServer, context);
return new AdamInstance(adamInstContext, adamInstName);
}
else
{
// could be AD or adam server
DirectoryServer? server = null;
DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
if (Utils.CheckCapability(rootDSE, Capability.ActiveDirectory))
{
string dcName = Utils.GetDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, _schemaEntry, PropertyManager.FsmoRoleOwner)!);
DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context);
server = new DomainController(dcContext, dcName);
}
else
{
// ADAM case again
string adamInstName = Utils.GetAdamDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, _schemaEntry, PropertyManager.FsmoRoleOwner)!);
DirectoryContext adamInstContext = Utils.GetNewDirectoryContext(adamInstName, DirectoryContextType.DirectoryServer, context);
server = new AdamInstance(adamInstContext, adamInstName);
}
return server;
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
#endregion private methods
}
}