/
DirectoryContext.cs
719 lines (630 loc) · 28 KB
/
DirectoryContext.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Net;
using System.Security.Principal;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.IO;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32.SafeHandles;
namespace System.DirectoryServices.ActiveDirectory
{
public enum DirectoryContextType
{
Domain = 0,
Forest = 1,
DirectoryServer = 2,
ConfigurationSet = 3,
ApplicationPartition = 4
}
public class DirectoryContext
{
private string? _name;
private DirectoryContextType _contextType;
private NetworkCredential _credential;
internal string? serverName;
internal bool usernameIsNull;
internal bool passwordIsNull;
private bool _validated;
private bool _contextIsValid;
internal static Microsoft.Win32.SafeHandles.SafeLibraryHandle ADHandle;
internal static Microsoft.Win32.SafeHandles.SafeLibraryHandle ADAMHandle;
#region constructors
static DirectoryContext()
{
// load ntdsapi.dll for AD and ADAM
GetLibraryHandle();
}
// Internal Constructors
[MemberNotNull(nameof(_credential))]
internal void InitializeDirectoryContext(DirectoryContextType contextType, string? name, string? username, string? password)
{
_name = name;
_contextType = contextType;
_credential = new NetworkCredential(username, password);
if (username == null)
{
usernameIsNull = true;
}
if (password == null)
{
passwordIsNull = true;
}
}
internal DirectoryContext(DirectoryContextType contextType, string? name, DirectoryContext? context)
{
_name = name;
_contextType = contextType;
if (context != null)
{
_credential = context.Credential;
this.usernameIsNull = context.usernameIsNull;
this.passwordIsNull = context.passwordIsNull;
}
else
{
_credential = new NetworkCredential(null, "", null);
this.usernameIsNull = true;
this.passwordIsNull = true;
}
}
internal DirectoryContext(DirectoryContext context)
{
_name = context.Name;
_contextType = context.ContextType;
_credential = context.Credential;
this.usernameIsNull = context.usernameIsNull;
this.passwordIsNull = context.passwordIsNull;
if (context.ContextType != DirectoryContextType.ConfigurationSet)
{
//
// only for configurationset, we select a server, so we should not copy over that
// information, for all other types, this is either the same as name of the target or if the target is netbios name
// (for domain and forest) it could be the dns name. We should copy over this information.
//
this.serverName = context.serverName;
}
}
#endregion constructors
#region public constructors
public DirectoryContext(DirectoryContextType contextType)
{
//
// this constructor can only be called for DirectoryContextType.Forest or DirectoryContextType.Domain
// since all other types require the name to be specified
//
if (contextType != DirectoryContextType.Domain && contextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.OnlyDomainOrForest, nameof(contextType));
}
InitializeDirectoryContext(contextType, null, null, null);
}
public DirectoryContext(DirectoryContextType contextType, string name)
{
if (contextType < DirectoryContextType.Domain || contextType > DirectoryContextType.ApplicationPartition)
{
throw new InvalidEnumArgumentException(nameof(contextType), (int)contextType, typeof(DirectoryContextType));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (name.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(name));
}
InitializeDirectoryContext(contextType, name, null, null);
}
public DirectoryContext(DirectoryContextType contextType, string? username, string? password)
{
//
// this constructor can only be called for DirectoryContextType.Forest or DirectoryContextType.Domain
// since all other types require the name to be specified
//
if (contextType != DirectoryContextType.Domain && contextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.OnlyDomainOrForest, nameof(contextType));
}
InitializeDirectoryContext(contextType, null, username, password);
}
public DirectoryContext(DirectoryContextType contextType, string name, string? username, string? password)
{
if (contextType < DirectoryContextType.Domain || contextType > DirectoryContextType.ApplicationPartition)
{
throw new InvalidEnumArgumentException(nameof(contextType), (int)contextType, typeof(DirectoryContextType));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (name.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(name));
}
InitializeDirectoryContext(contextType, name, username, password);
}
#endregion public methods
#region public properties
public string? Name => _name;
public string? UserName => usernameIsNull ? null : _credential.UserName;
internal string? Password
{
get => passwordIsNull ? null : _credential.Password;
}
public DirectoryContextType ContextType => _contextType;
internal NetworkCredential Credential => _credential;
#endregion public properties
#region private methods
internal static bool IsContextValid(DirectoryContext context, DirectoryContextType contextType)
{
bool contextIsValid = false;
if ((contextType == DirectoryContextType.Domain) || ((contextType == DirectoryContextType.Forest) && (context.Name == null)))
{
string? tmpTarget = context.Name;
if (tmpTarget == null)
{
// GetLoggedOnDomain returns the dns name of the logged on user's domain
context.serverName = GetLoggedOnDomain();
contextIsValid = true;
}
else
{
// check for domain
int errorCode = 0;
DomainControllerInfo domainControllerInfo;
errorCode = Locator.DsGetDcNameWrapper(null, tmpTarget, null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// try with force rediscovery
errorCode = Locator.DsGetDcNameWrapper(null, tmpTarget, null, (long)PrivateLocatorFlags.DirectoryServicesRequired | (long)LocatorOptions.ForceRediscovery, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DomainName != null);
context.serverName = domainControllerInfo.DomainName;
contextIsValid = true;
}
}
else if (errorCode == NativeMethods.ERROR_INVALID_DOMAIN_NAME_FORMAT)
{
// we can get this error if the target it server:port (not a valid domain)
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DomainName != null);
context.serverName = domainControllerInfo.DomainName;
contextIsValid = true;
}
}
}
else if (contextType == DirectoryContextType.Forest)
{
Debug.Assert(context.Name != null);
// check for forest
int errorCode = 0;
DomainControllerInfo domainControllerInfo;
errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)(PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DirectoryServicesRequired), out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// try with force rediscovery
errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)((PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DirectoryServicesRequired)) | (long)LocatorOptions.ForceRediscovery, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DnsForestName != null);
context.serverName = domainControllerInfo.DnsForestName;
contextIsValid = true;
}
}
else if (errorCode == NativeMethods.ERROR_INVALID_DOMAIN_NAME_FORMAT)
{
// we can get this error if the target it server:port (not a valid forest)
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DnsForestName != null);
context.serverName = domainControllerInfo.DnsForestName;
contextIsValid = true;
}
}
else if (contextType == DirectoryContextType.ApplicationPartition)
{
Debug.Assert(context.Name != null);
// check for application partition
int errorCode = 0;
DomainControllerInfo domainControllerInfo;
errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)PrivateLocatorFlags.OnlyLDAPNeeded, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// try with force rediscovery
errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)PrivateLocatorFlags.OnlyLDAPNeeded | (long)LocatorOptions.ForceRediscovery, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
contextIsValid = true;
}
}
else if (errorCode == NativeMethods.ERROR_INVALID_DOMAIN_NAME_FORMAT)
{
// we can get this error if the target it server:port (not a valid application partition)
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
contextIsValid = true;
}
}
else if (contextType == DirectoryContextType.DirectoryServer)
{
//
// if the servername contains a port number, then remove that
//
string? tempServerName = null;
string? portNumber;
tempServerName = Utils.SplitServerNameAndPortNumber(context.Name!, out portNumber);
//
// this will validate that the name specified in the context is truely the name of a machine (and not of a domain)
//
DirectoryEntry de = new DirectoryEntry("WinNT://" + tempServerName + ",computer", context.UserName, context.Password, Utils.DefaultAuthType);
try
{
de.Bind(true);
contextIsValid = true;
}
catch (COMException e)
{
if ((e.ErrorCode == unchecked((int)0x80070035)) || (e.ErrorCode == unchecked((int)0x80070033)) || (e.ErrorCode == unchecked((int)0x80005000)))
{
// if this returns bad network path
contextIsValid = false;
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
de.Dispose();
}
}
else
{
// no special validation for ConfigurationSet
contextIsValid = true;
}
return contextIsValid;
}
internal bool isRootDomain()
{
if (_contextType != DirectoryContextType.Forest)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.Forest);
_validated = true;
}
return _contextIsValid;
}
internal bool isDomain()
{
if (_contextType != DirectoryContextType.Domain)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.Domain);
_validated = true;
}
return _contextIsValid;
}
internal bool isNdnc()
{
if (_contextType != DirectoryContextType.ApplicationPartition)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.ApplicationPartition);
_validated = true;
}
return _contextIsValid;
}
internal bool isServer()
{
if (_contextType != DirectoryContextType.DirectoryServer)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.DirectoryServer);
_validated = true;
}
return _contextIsValid;
}
internal bool isADAMConfigSet()
{
if (_contextType != DirectoryContextType.ConfigurationSet)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.ConfigurationSet);
_validated = true;
}
return _contextIsValid;
}
//
// this method is called when the forest name is explicitly specified
// and we want to check if that matches the current logged on forest
//
internal bool isCurrentForest()
{
bool result = false;
Debug.Assert(_name != null);
DomainControllerInfo domainControllerInfo = Locator.GetDomainControllerInfo(null, _name, null, (long)(PrivateLocatorFlags.DirectoryServicesRequired | PrivateLocatorFlags.ReturnDNSName));
DomainControllerInfo currentDomainControllerInfo;
string loggedOnDomain = GetLoggedOnDomain();
int errorCode = Locator.DsGetDcNameWrapper(null, loggedOnDomain, null, (long)(PrivateLocatorFlags.DirectoryServicesRequired | PrivateLocatorFlags.ReturnDNSName), out currentDomainControllerInfo);
if (errorCode == 0)
{
Debug.Assert(domainControllerInfo.DnsForestName != null);
Debug.Assert(currentDomainControllerInfo.DnsForestName != null);
result = (Utils.Compare(domainControllerInfo.DnsForestName, currentDomainControllerInfo.DnsForestName) == 0);
}
//
// if there is no forest associated with the logged on domain, then we return false
//
else if (errorCode != NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
return result;
}
internal bool useServerBind()
{
return ((ContextType == DirectoryContextType.DirectoryServer) || (ContextType == DirectoryContextType.ConfigurationSet));
}
internal string? GetServerName()
{
if (serverName == null)
{
switch (_contextType)
{
case DirectoryContextType.ConfigurationSet:
{
AdamInstance adamInst = ConfigurationSet.FindAnyAdamInstance(this);
try
{
serverName = adamInst.Name;
}
finally
{
adamInst.Dispose();
}
break;
}
case DirectoryContextType.Domain:
case DirectoryContextType.Forest:
{
//
// if the target is not specified OR
// if the forest name was explicitly specified and the forest is the same as the current forest
// we want to find a DC in the current domain
//
if ((_name == null) || ((_contextType == DirectoryContextType.Forest) && (isCurrentForest())))
{
serverName = GetLoggedOnDomain();
}
else
{
serverName = GetDnsDomainName(_name);
}
break;
}
case DirectoryContextType.ApplicationPartition:
{
// if this is an appNC the target should not be null
Debug.Assert(_name != null);
serverName = _name;
break;
}
case DirectoryContextType.DirectoryServer:
{
// this should not happen (We should have checks for this earlier itself)
Debug.Assert(_name != null);
serverName = _name;
break;
}
default:
{
Debug.Fail("DirectoryContext::GetServerName - Unknown contextType");
break;
}
}
}
return serverName;
}
internal static string GetLoggedOnDomain()
{
string? domainName = null;
NegotiateCallerNameRequest requestBuffer = default;
int requestBufferLength = (int)Marshal.SizeOf(requestBuffer);
IntPtr pResponseBuffer = IntPtr.Zero;
NegotiateCallerNameResponse responseBuffer = new NegotiateCallerNameResponse();
int responseBufferLength;
uint protocolStatus;
uint result;
LsaLogonProcessSafeHandle lsaHandle;
//
// since we are using safe handles, we don't need to explicitly call NativeMethods.LsaDeregisterLogonProcess(lsaHandle)
//
result = NativeMethods.LsaConnectUntrusted(out lsaHandle);
if (result == 0)
{
//
// initialize the request buffer
//
requestBuffer.messageType = NativeMethods.NegGetCallerName;
result = NativeMethods.LsaCallAuthenticationPackage(lsaHandle, 0, requestBuffer, requestBufferLength, out pResponseBuffer, out responseBufferLength, out protocolStatus);
try
{
if (result == 0 && protocolStatus == 0)
{
Marshal.PtrToStructure(pResponseBuffer, responseBuffer);
//
// callerName is of the form domain\username
//
Debug.Assert((responseBuffer.callerName != null), "NativeMethods.LsaCallAuthenticationPackage returned null callerName.");
int index = responseBuffer.callerName.IndexOf('\\');
Debug.Assert((index != -1), "NativeMethods.LsaCallAuthenticationPackage returned callerName not in domain\\username format.");
domainName = responseBuffer.callerName.Substring(0, index);
}
else
{
if (result == global::Interop.StatusOptions.STATUS_QUOTA_EXCEEDED)
{
throw new OutOfMemoryException();
}
else if ((result == 0) && (global::Interop.Advapi32.LsaNtStatusToWinError(protocolStatus) == NativeMethods.ERROR_NO_SUCH_LOGON_SESSION))
{
// If this is a directory user, extract domain info from username
if (!Utils.IsSamUser())
{
using WindowsIdentity identity = WindowsIdentity.GetCurrent();
int index = identity.Name.IndexOf('\\');
Debug.Assert(index != -1);
domainName = identity.Name.Substring(0, index);
}
}
else
{
throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError((result != 0) ? result : protocolStatus));
}
}
}
finally
{
if (pResponseBuffer != IntPtr.Zero)
{
NativeMethods.LsaFreeReturnBuffer(pResponseBuffer);
}
}
}
else if (result == global::Interop.StatusOptions.STATUS_QUOTA_EXCEEDED)
{
throw new OutOfMemoryException();
}
else
{
throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result));
}
// If we're running as a local user (i.e. NT AUTHORITY\LOCAL SYSTEM, IIS APPPOOL\APPPoolIdentity, etc.),
// domainName will be null and we fall back to the machine's domain
domainName = GetDnsDomainName(domainName);
if (domainName == null)
{
//
// we should never get to this point here since we should have already verified that the context is valid
// by the time we get to this point
//
throw new ActiveDirectoryOperationException(SR.ContextNotAssociatedWithDomain);
}
return domainName;
}
internal static string? GetDnsDomainName(string? domainName)
{
DomainControllerInfo domainControllerInfo;
int errorCode = 0;
//
// Locator.DsGetDcNameWrapper internally passes the ReturnDNSName flag when calling DsGetDcName
//
errorCode = Locator.DsGetDcNameWrapper(null, domainName, null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// try again with force rediscovery
errorCode = Locator.DsGetDcNameWrapper(null, domainName, null, (long)((long)PrivateLocatorFlags.DirectoryServicesRequired | (long)LocatorOptions.ForceRediscovery), out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
return null;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DomainName != null);
return domainControllerInfo.DomainName;
}
[MemberNotNull(nameof(ADHandle))]
[MemberNotNull(nameof(ADAMHandle))]
private static void GetLibraryHandle()
{
// first get AD handle
string systemPath = Environment.SystemDirectory;
IntPtr tempHandle = global::Interop.Kernel32.LoadLibrary(systemPath + "\\ntdsapi.dll");
if (tempHandle == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastPInvokeError());
}
else
{
ADHandle = new SafeLibraryHandle(tempHandle);
}
// not get the ADAM handle
// got to the windows\adam directory
DirectoryInfo windowsDirectory = Directory.GetParent(systemPath)!;
tempHandle = global::Interop.Kernel32.LoadLibrary(windowsDirectory.FullName + "\\ADAM\\ntdsapi.dll");
if (tempHandle == (IntPtr)0)
{
ADAMHandle = ADHandle;
}
else
{
ADAMHandle = new SafeLibraryHandle(tempHandle);
}
}
#endregion private methods
}
}