| | 1 | | using System; |
| | 2 | | using System.Collections.Concurrent; |
| | 3 | | using System.Collections.Generic; |
| | 4 | | using System.DirectoryServices; |
| | 5 | | using System.DirectoryServices.AccountManagement; |
| | 6 | | using System.DirectoryServices.ActiveDirectory; |
| | 7 | | using System.Linq; |
| | 8 | | using System.Net; |
| | 9 | | using System.Net.Sockets; |
| | 10 | | using System.Security.Principal; |
| | 11 | | using System.Text; |
| | 12 | | using System.Text.RegularExpressions; |
| | 13 | | using System.Threading; |
| | 14 | | using System.Threading.Tasks; |
| | 15 | | using Microsoft.Extensions.Logging; |
| | 16 | | using SharpHoundCommonLib.DirectoryObjects; |
| | 17 | | using SharpHoundCommonLib.Enums; |
| | 18 | | using SharpHoundCommonLib.LDAPQueries; |
| | 19 | | using SharpHoundCommonLib.OutputTypes; |
| | 20 | | using SharpHoundCommonLib.Processors; |
| | 21 | | using SharpHoundRPC.NetAPINative; |
| | 22 | | using Domain = System.DirectoryServices.ActiveDirectory.Domain; |
| | 23 | | using Group = SharpHoundCommonLib.OutputTypes.Group; |
| | 24 | | using SearchScope = System.DirectoryServices.Protocols.SearchScope; |
| | 25 | |
|
| | 26 | | namespace SharpHoundCommonLib { |
| | 27 | | public class LdapUtils : ILdapUtils { |
| | 28 | | //This cache is indexed by domain sid |
| 1 | 29 | | private static ConcurrentDictionary<string, Domain> _domainCache = new(); |
| 1 | 30 | | private static ConcurrentHashSet _domainControllers = new(StringComparer.OrdinalIgnoreCase); |
| 1 | 31 | | private static ConcurrentHashSet _unresolvablePrincipals = new(StringComparer.OrdinalIgnoreCase); |
| | 32 | |
|
| 1 | 33 | | private static readonly ConcurrentDictionary<string, string> DomainToForestCache = |
| 1 | 34 | | new(StringComparer.OrdinalIgnoreCase); |
| | 35 | |
|
| 1 | 36 | | private static readonly ConcurrentDictionary<string, ResolvedWellKnownPrincipal> |
| 1 | 37 | | SeenWellKnownPrincipals = new(); |
| | 38 | |
|
| 62 | 39 | | private readonly ConcurrentDictionary<string, string> |
| 62 | 40 | | _hostResolutionMap = new(StringComparer.OrdinalIgnoreCase); |
| | 41 | |
|
| 62 | 42 | | private readonly ConcurrentDictionary<string, TypedPrincipal> _distinguishedNameCache = |
| 62 | 43 | | new(StringComparer.OrdinalIgnoreCase); |
| | 44 | |
|
| | 45 | | private readonly ILogger _log; |
| | 46 | | private readonly PortScanner _portScanner; |
| | 47 | | private readonly NativeMethods _nativeMethods; |
| 62 | 48 | | private readonly string _nullCacheKey = Guid.NewGuid().ToString(); |
| 1 | 49 | | private static readonly Regex SIDRegex = new(@"^(S-\d+-\d+-\d+-\d+-\d+-\d+)(-\d+)?$"); |
| | 50 | |
|
| 62 | 51 | | private readonly string[] _translateNames = { "Administrator", "admin" }; |
| 62 | 52 | | private LdapConfig _ldapConfig = new(); |
| | 53 | |
|
| | 54 | | private ConnectionPoolManager _connectionPool; |
| | 55 | |
|
| 1 | 56 | | private static readonly byte[] NameRequest = { |
| 1 | 57 | | 0x80, 0x94, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, |
| 1 | 58 | | 0x00, 0x00, 0x00, 0x00, 0x20, 0x43, 0x4b, 0x41, |
| 1 | 59 | | 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, |
| 1 | 60 | | 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, |
| 1 | 61 | | 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, |
| 1 | 62 | | 0x41, 0x41, 0x41, 0x41, 0x41, 0x00, 0x00, 0x21, |
| 1 | 63 | | 0x00, 0x01 |
| 1 | 64 | | }; |
| | 65 | |
|
| | 66 | | private class ResolvedWellKnownPrincipal { |
| 3 | 67 | | public string DomainName { get; set; } |
| 3 | 68 | | public string WkpId { get; set; } |
| | 69 | | } |
| | 70 | |
|
| 124 | 71 | | public LdapUtils() { |
| 62 | 72 | | _nativeMethods = new NativeMethods(); |
| 62 | 73 | | _portScanner = new PortScanner(); |
| 62 | 74 | | _log = Logging.LogProvider.CreateLogger("LDAPUtils"); |
| 62 | 75 | | _connectionPool = new ConnectionPoolManager(_ldapConfig, _log); |
| 62 | 76 | | } |
| | 77 | |
|
| 0 | 78 | | public LdapUtils(NativeMethods nativeMethods = null, PortScanner scanner = null, ILogger log = null) { |
| 0 | 79 | | _nativeMethods = nativeMethods ?? new NativeMethods(); |
| 0 | 80 | | _portScanner = scanner ?? new PortScanner(); |
| 0 | 81 | | _log = log ?? Logging.LogProvider.CreateLogger("LDAPUtils"); |
| 0 | 82 | | _connectionPool = new ConnectionPoolManager(_ldapConfig, scanner: _portScanner); |
| 0 | 83 | | } |
| | 84 | |
|
| | 85 | | public IAsyncEnumerable<Result<string>> RangedRetrieval(string distinguishedName, |
| 0 | 86 | | string attributeName, CancellationToken cancellationToken = new()) { |
| 0 | 87 | | return _connectionPool.RangedRetrieval(distinguishedName, attributeName, cancellationToken); |
| 0 | 88 | | } |
| | 89 | |
|
| | 90 | | public IAsyncEnumerable<LdapResult<IDirectoryObject>> Query(LdapQueryParameters queryParameters, |
| 1 | 91 | | CancellationToken cancellationToken = new()) { |
| 1 | 92 | | return _connectionPool.Query(queryParameters, cancellationToken); |
| 1 | 93 | | } |
| | 94 | |
|
| | 95 | | public IAsyncEnumerable<LdapResult<IDirectoryObject>> PagedQuery(LdapQueryParameters queryParameters, |
| 0 | 96 | | CancellationToken cancellationToken = new()) { |
| 0 | 97 | | return _connectionPool.PagedQuery(queryParameters, cancellationToken); |
| 0 | 98 | | } |
| | 99 | |
|
| | 100 | | public async Task<(bool Success, TypedPrincipal Principal)> ResolveIDAndType( |
| | 101 | | SecurityIdentifier securityIdentifier, |
| 0 | 102 | | string objectDomain) { |
| 0 | 103 | | return await ResolveIDAndType(securityIdentifier.Value, objectDomain); |
| 0 | 104 | | } |
| | 105 | |
|
| | 106 | | public async Task<(bool Success, TypedPrincipal Principal)> |
| 2 | 107 | | ResolveIDAndType(string identifier, string objectDomain) { |
| 3 | 108 | | if (identifier.IndexOf("0ACNF", StringComparison.OrdinalIgnoreCase) >= 0) { |
| 1 | 109 | | return (false, new TypedPrincipal(identifier, Label.Base)); |
| | 110 | | } |
| | 111 | |
|
| 2 | 112 | | if (await GetWellKnownPrincipal(identifier, objectDomain) is (true, var principal)) { |
| 1 | 113 | | return (true, principal); |
| | 114 | | } |
| | 115 | |
|
| 0 | 116 | | if (_unresolvablePrincipals.Contains(identifier)) { |
| 0 | 117 | | return (false, new TypedPrincipal(identifier, Label.Base)); |
| | 118 | | } |
| | 119 | |
|
| 0 | 120 | | if (identifier.StartsWith("S-")) { |
| 0 | 121 | | var result = await LookupSidType(identifier, objectDomain); |
| 0 | 122 | | if (!result.Success) { |
| 0 | 123 | | _unresolvablePrincipals.Add(identifier); |
| 0 | 124 | | } |
| | 125 | |
|
| 0 | 126 | | return (result.Success, new TypedPrincipal(identifier, result.Type)); |
| | 127 | | } |
| | 128 | |
|
| 0 | 129 | | var (success, type) = await LookupGuidType(identifier, objectDomain); |
| 0 | 130 | | if (!success) { |
| 0 | 131 | | _unresolvablePrincipals.Add(identifier); |
| 0 | 132 | | } |
| | 133 | |
|
| 0 | 134 | | return (success, new TypedPrincipal(identifier, type)); |
| 2 | 135 | | } |
| | 136 | |
|
| 0 | 137 | | private async Task<(bool Success, Label Type)> LookupSidType(string sid, string domain) { |
| 0 | 138 | | if (Cache.GetIDType(sid, out var type)) { |
| 0 | 139 | | return (true, type); |
| | 140 | | } |
| | 141 | |
|
| 0 | 142 | | var tempDomain = domain; |
| | 143 | |
|
| 0 | 144 | | if (await GetDomainNameFromSid(sid) is (true, var domainName)) { |
| 0 | 145 | | tempDomain = domainName; |
| 0 | 146 | | } |
| | 147 | |
|
| 0 | 148 | | var result = await Query(new LdapQueryParameters() { |
| 0 | 149 | | DomainName = tempDomain, |
| 0 | 150 | | LDAPFilter = CommonFilters.SpecificSID(sid), |
| 0 | 151 | | Attributes = CommonProperties.TypeResolutionProps |
| 0 | 152 | | }).DefaultIfEmpty(LdapResult<IDirectoryObject>.Fail()).FirstOrDefaultAsync(); |
| | 153 | |
|
| 0 | 154 | | if (result.IsSuccess) { |
| 0 | 155 | | if (result.Value.GetLabel(out type)) { |
| 0 | 156 | | Cache.AddType(sid, type); |
| 0 | 157 | | return (true, type); |
| | 158 | | } |
| 0 | 159 | | } |
| | 160 | |
|
| 0 | 161 | | try { |
| 0 | 162 | | var entry = CreateDirectoryEntry($"LDAP://<SID={sid}>"); |
| 0 | 163 | | if (entry.GetLabel(out type)) { |
| 0 | 164 | | Cache.AddType(sid, type); |
| 0 | 165 | | return (true, type); |
| | 166 | | } |
| 0 | 167 | | } catch { |
| | 168 | | //pass |
| 0 | 169 | | } |
| | 170 | |
|
| 0 | 171 | | try { |
| 0 | 172 | | using (var ctx = new PrincipalContext(ContextType.Domain)) { |
| 0 | 173 | | var principal = Principal.FindByIdentity(ctx, IdentityType.Sid, sid); |
| 0 | 174 | | if (principal != null) { |
| 0 | 175 | | var entry = ((DirectoryEntry)principal.GetUnderlyingObject()).ToDirectoryObject(); |
| 0 | 176 | | if (entry.GetLabel(out type)) { |
| 0 | 177 | | Cache.AddType(sid, type); |
| 0 | 178 | | return (true, type); |
| | 179 | | } |
| 0 | 180 | | } |
| 0 | 181 | | } |
| 0 | 182 | | } catch { |
| | 183 | | //pass |
| 0 | 184 | | } |
| | 185 | |
|
| | 186 | |
|
| 0 | 187 | | return (false, Label.Base); |
| 0 | 188 | | } |
| | 189 | |
|
| 0 | 190 | | private async Task<(bool Success, Label type)> LookupGuidType(string guid, string domain) { |
| 0 | 191 | | if (Cache.GetIDType(guid, out var type)) { |
| 0 | 192 | | return (true, type); |
| | 193 | | } |
| | 194 | |
|
| 0 | 195 | | var result = await Query(new LdapQueryParameters() { |
| 0 | 196 | | DomainName = domain, |
| 0 | 197 | | LDAPFilter = CommonFilters.SpecificGUID(guid), |
| 0 | 198 | | Attributes = CommonProperties.TypeResolutionProps |
| 0 | 199 | | }).DefaultIfEmpty(LdapResult<IDirectoryObject>.Fail()).FirstOrDefaultAsync(); |
| | 200 | |
|
| 0 | 201 | | if (result.IsSuccess && result.Value.GetLabel(out type)) { |
| 0 | 202 | | Cache.AddType(guid, type); |
| 0 | 203 | | return (true, type); |
| | 204 | | } |
| | 205 | |
|
| 0 | 206 | | try { |
| 0 | 207 | | var entry = CreateDirectoryEntry($"LDAP://<GUID={guid}>"); |
| 0 | 208 | | if (entry.GetLabel(out type)) { |
| 0 | 209 | | Cache.AddType(guid, type); |
| 0 | 210 | | return (true, type); |
| | 211 | | } |
| 0 | 212 | | } catch { |
| | 213 | | //pass |
| 0 | 214 | | } |
| | 215 | |
|
| 0 | 216 | | try { |
| 0 | 217 | | using (var ctx = new PrincipalContext(ContextType.Domain)) { |
| 0 | 218 | | var principal = Principal.FindByIdentity(ctx, IdentityType.Guid, guid); |
| 0 | 219 | | if (principal != null) { |
| 0 | 220 | | var entry = ((DirectoryEntry)principal.GetUnderlyingObject()).ToDirectoryObject(); |
| 0 | 221 | | if (entry.GetLabel(out type)) { |
| 0 | 222 | | Cache.AddType(guid, type); |
| 0 | 223 | | return (true, type); |
| | 224 | | } |
| 0 | 225 | | } |
| 0 | 226 | | } |
| 0 | 227 | | } catch { |
| | 228 | | //pass |
| 0 | 229 | | } |
| | 230 | |
|
| | 231 | |
|
| 0 | 232 | | return (false, Label.Base); |
| 0 | 233 | | } |
| | 234 | |
|
| | 235 | | public async Task<(bool Success, TypedPrincipal WellKnownPrincipal)> GetWellKnownPrincipal( |
| 4 | 236 | | string securityIdentifier, string objectDomain) { |
| 5 | 237 | | if (!WellKnownPrincipal.GetWellKnownPrincipal(securityIdentifier, out var wellKnownPrincipal)) { |
| 1 | 238 | | return (false, null); |
| | 239 | | } |
| | 240 | |
|
| 3 | 241 | | var (newIdentifier, newDomain) = |
| 3 | 242 | | await GetWellKnownPrincipalObjectIdentifier(securityIdentifier, objectDomain); |
| | 243 | |
|
| 3 | 244 | | wellKnownPrincipal.ObjectIdentifier = newIdentifier; |
| 3 | 245 | | SeenWellKnownPrincipals.TryAdd(wellKnownPrincipal.ObjectIdentifier, new ResolvedWellKnownPrincipal { |
| 3 | 246 | | DomainName = newDomain, |
| 3 | 247 | | WkpId = securityIdentifier |
| 3 | 248 | | }); |
| | 249 | |
|
| 3 | 250 | | return (true, wellKnownPrincipal); |
| 4 | 251 | | } |
| | 252 | |
|
| | 253 | | private async Task<(string ObjectID, string Domain)> GetWellKnownPrincipalObjectIdentifier( |
| 3 | 254 | | string securityIdentifier, string domain) { |
| 3 | 255 | | if (!WellKnownPrincipal.GetWellKnownPrincipal(securityIdentifier, out _)) |
| 0 | 256 | | return (securityIdentifier, string.Empty); |
| | 257 | |
|
| 5 | 258 | | if (!securityIdentifier.Equals("S-1-5-9", StringComparison.OrdinalIgnoreCase)) { |
| 2 | 259 | | var tempDomain = domain; |
| 2 | 260 | | if (GetDomain(tempDomain, out var domainObject) && domainObject.Name != null) { |
| 0 | 261 | | tempDomain = domainObject.Name; |
| 0 | 262 | | } |
| | 263 | |
|
| 2 | 264 | | return ($"{tempDomain}-{securityIdentifier}".ToUpper(), tempDomain); |
| | 265 | | } |
| | 266 | |
|
| 2 | 267 | | if (await GetForest(domain) is (true, var forest)) { |
| 1 | 268 | | return ($"{forest}-{securityIdentifier}".ToUpper(), forest); |
| | 269 | | } |
| | 270 | |
|
| 0 | 271 | | _log.LogWarning("Failed to get a forest name for domain {Domain}, unable to resolve enterprise DC sid", |
| 0 | 272 | | domain); |
| 0 | 273 | | return ($"UNKNOWN-{securityIdentifier}", "UNKNOWN"); |
| 3 | 274 | | } |
| | 275 | |
|
| 0 | 276 | | public virtual async Task<(bool Success, string ForestName)> GetForest(string domain) { |
| 0 | 277 | | if (DomainToForestCache.TryGetValue(domain, out var cachedForest)) { |
| 0 | 278 | | return (true, cachedForest); |
| | 279 | | } |
| | 280 | |
|
| 0 | 281 | | if (GetDomain(domain, out var domainObject)) { |
| 0 | 282 | | try { |
| 0 | 283 | | var forestName = domainObject.Forest.Name.ToUpper(); |
| 0 | 284 | | DomainToForestCache.TryAdd(domain, forestName); |
| 0 | 285 | | return (true, forestName); |
| 0 | 286 | | } catch { |
| | 287 | | //pass |
| 0 | 288 | | } |
| 0 | 289 | | } |
| | 290 | |
|
| 0 | 291 | | var (success, forest) = await GetForestFromLdap(domain); |
| 0 | 292 | | if (success) { |
| 0 | 293 | | DomainToForestCache.TryAdd(domain, forest); |
| 0 | 294 | | return (true, forest); |
| | 295 | | } |
| | 296 | |
|
| 0 | 297 | | return (false, null); |
| 0 | 298 | | } |
| | 299 | |
|
| 0 | 300 | | private async Task<(bool Success, string ForestName)> GetForestFromLdap(string domain) { |
| 0 | 301 | | var queryParameters = new LdapQueryParameters { |
| 0 | 302 | | Attributes = new[] { LDAPProperties.RootDomainNamingContext }, |
| 0 | 303 | | SearchScope = SearchScope.Base, |
| 0 | 304 | | DomainName = domain, |
| 0 | 305 | | LDAPFilter = new LdapFilter().AddAllObjects().GetFilter(), |
| 0 | 306 | | }; |
| | 307 | |
|
| 0 | 308 | | var result = await Query(queryParameters).DefaultIfEmpty(LdapResult<IDirectoryObject>.Fail()) |
| 0 | 309 | | .FirstOrDefaultAsync(); |
| 0 | 310 | | if (result.IsSuccess && |
| 0 | 311 | | result.Value.TryGetProperty(LDAPProperties.RootDomainNamingContext, out var rootNamingContext)) { |
| 0 | 312 | | return (true, Helpers.DistinguishedNameToDomain(rootNamingContext).ToUpper()); |
| | 313 | | } |
| | 314 | |
|
| 0 | 315 | | return (false, null); |
| 0 | 316 | | } |
| | 317 | |
|
| 0 | 318 | | public virtual async Task<(bool Success, string DomainName)> GetDomainNameFromSid(string sid) { |
| | 319 | | string domainSid; |
| 0 | 320 | | try { |
| 0 | 321 | | domainSid = new SecurityIdentifier(sid).AccountDomainSid?.Value.ToUpper(); |
| 0 | 322 | | } catch { |
| 0 | 323 | | var match = SIDRegex.Match(sid); |
| 0 | 324 | | domainSid = match.Success ? match.Groups[1].Value : null; |
| 0 | 325 | | } |
| | 326 | |
|
| 0 | 327 | | if (domainSid == null) { |
| 0 | 328 | | return (false, ""); |
| | 329 | | } |
| | 330 | |
|
| 0 | 331 | | if (Cache.GetDomainSidMapping(domainSid, out var domain)) { |
| 0 | 332 | | return (true, domain); |
| | 333 | | } |
| | 334 | |
|
| 0 | 335 | | try { |
| 0 | 336 | | var entry = CreateDirectoryEntry($"LDAP://<SID={domainSid}>"); |
| 0 | 337 | | if (entry.TryGetDistinguishedName(out var dn)) { |
| 0 | 338 | | Cache.AddDomainSidMapping(domainSid, Helpers.DistinguishedNameToDomain(dn)); |
| 0 | 339 | | return (true, Helpers.DistinguishedNameToDomain(dn)); |
| | 340 | | } |
| 0 | 341 | | } catch { |
| | 342 | | //pass |
| 0 | 343 | | } |
| | 344 | |
|
| 0 | 345 | | if (await ConvertDomainSidToDomainNameFromLdap(sid) is (true, var domainName)) { |
| 0 | 346 | | Cache.AddDomainSidMapping(domainSid, domainName); |
| 0 | 347 | | return (true, domainName); |
| | 348 | | } |
| | 349 | |
|
| 0 | 350 | | try { |
| 0 | 351 | | using (var ctx = new PrincipalContext(ContextType.Domain)) { |
| 0 | 352 | | var principal = Principal.FindByIdentity(ctx, IdentityType.Sid, sid); |
| 0 | 353 | | if (principal != null) { |
| 0 | 354 | | var dn = principal.DistinguishedName; |
| 0 | 355 | | if (!string.IsNullOrWhiteSpace(dn)) { |
| 0 | 356 | | Cache.AddDomainSidMapping(domainSid, Helpers.DistinguishedNameToDomain(dn)); |
| 0 | 357 | | return (true, Helpers.DistinguishedNameToDomain(dn)); |
| | 358 | | } |
| 0 | 359 | | } |
| 0 | 360 | | } |
| 0 | 361 | | } catch { |
| | 362 | | //pass |
| 0 | 363 | | } |
| | 364 | |
|
| | 365 | |
|
| 0 | 366 | | return (false, string.Empty); |
| 0 | 367 | | } |
| | 368 | |
|
| 0 | 369 | | private async Task<(bool Success, string DomainName)> ConvertDomainSidToDomainNameFromLdap(string domainSid) { |
| 0 | 370 | | if (!GetDomain(out var domain) || domain?.Name == null) { |
| 0 | 371 | | return (false, string.Empty); |
| | 372 | | } |
| | 373 | |
|
| 0 | 374 | | var result = await Query(new LdapQueryParameters { |
| 0 | 375 | | DomainName = domain.Name, |
| 0 | 376 | | Attributes = new[] { LDAPProperties.DistinguishedName }, |
| 0 | 377 | | GlobalCatalog = true, |
| 0 | 378 | | LDAPFilter = new LdapFilter().AddDomains(CommonFilters.SpecificSID(domainSid)).GetFilter() |
| 0 | 379 | | }).DefaultIfEmpty(LdapResult<IDirectoryObject>.Fail()).FirstOrDefaultAsync(); |
| | 380 | |
|
| 0 | 381 | | if (result.IsSuccess && result.Value.TryGetDistinguishedName(out var distinguishedName)) { |
| 0 | 382 | | return (true, Helpers.DistinguishedNameToDomain(distinguishedName)); |
| | 383 | | } |
| | 384 | |
|
| 0 | 385 | | result = await Query(new LdapQueryParameters { |
| 0 | 386 | | DomainName = domain.Name, |
| 0 | 387 | | Attributes = new[] { LDAPProperties.DistinguishedName }, |
| 0 | 388 | | GlobalCatalog = true, |
| 0 | 389 | | LDAPFilter = new LdapFilter().AddFilter("(objectclass=trusteddomain)", true) |
| 0 | 390 | | .AddFilter($"(securityidentifier={Helpers.ConvertSidToHexSid(domainSid)})", true).GetFilter() |
| 0 | 391 | | }).DefaultIfEmpty(LdapResult<IDirectoryObject>.Fail()).FirstOrDefaultAsync(); |
| | 392 | |
|
| 0 | 393 | | if (result.IsSuccess && result.Value.TryGetDistinguishedName(out distinguishedName)) { |
| 0 | 394 | | return (true, Helpers.DistinguishedNameToDomain(distinguishedName)); |
| | 395 | | } |
| | 396 | |
|
| 0 | 397 | | result = await Query(new LdapQueryParameters { |
| 0 | 398 | | DomainName = domain.Name, |
| 0 | 399 | | Attributes = new[] { LDAPProperties.DistinguishedName }, |
| 0 | 400 | | LDAPFilter = new LdapFilter().AddFilter("(objectclass=domaindns)", true) |
| 0 | 401 | | .AddFilter(CommonFilters.SpecificSID(domainSid), true).GetFilter() |
| 0 | 402 | | }).DefaultIfEmpty(LdapResult<IDirectoryObject>.Fail()).FirstOrDefaultAsync(); |
| | 403 | |
|
| 0 | 404 | | if (result.IsSuccess && result.Value.TryGetDistinguishedName(out distinguishedName)) { |
| 0 | 405 | | return (true, Helpers.DistinguishedNameToDomain(distinguishedName)); |
| | 406 | | } |
| | 407 | |
|
| 0 | 408 | | return (false, string.Empty); |
| 0 | 409 | | } |
| | 410 | |
|
| 0 | 411 | | public virtual async Task<(bool Success, string DomainSid)> GetDomainSidFromDomainName(string domainName) { |
| 0 | 412 | | if (Cache.GetDomainSidMapping(domainName, out var domainSid)) return (true, domainSid); |
| | 413 | |
|
| 0 | 414 | | try { |
| 0 | 415 | | var entry = CreateDirectoryEntry($"LDAP://{domainName}"); |
| | 416 | | //Force load objectsid into the object cache |
| 0 | 417 | | if (entry.TryGetSecurityIdentifier(out var sid)) { |
| 0 | 418 | | Cache.AddDomainSidMapping(domainName, sid); |
| 0 | 419 | | domainSid = sid; |
| 0 | 420 | | return (true, domainSid); |
| | 421 | | } |
| 0 | 422 | | } catch { |
| | 423 | | //we expect this to fail sometimes |
| 0 | 424 | | } |
| | 425 | |
|
| 0 | 426 | | if (GetDomain(domainName, out var domainObject)) |
| 0 | 427 | | try { |
| 0 | 428 | | var entry = domainObject.GetDirectoryEntry().ToDirectoryObject(); |
| 0 | 429 | | if (entry.TryGetSecurityIdentifier(out domainSid)) { |
| 0 | 430 | | Cache.AddDomainSidMapping(domainName, domainSid); |
| 0 | 431 | | return (true, domainSid); |
| | 432 | | } |
| 0 | 433 | | } catch { |
| | 434 | | //we expect this to fail sometimes (not sure why, but better safe than sorry) |
| 0 | 435 | | } |
| | 436 | |
|
| 0 | 437 | | foreach (var name in _translateNames) |
| 0 | 438 | | try { |
| 0 | 439 | | var account = new NTAccount(domainName, name); |
| 0 | 440 | | var sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier)); |
| 0 | 441 | | domainSid = sid.AccountDomainSid.ToString().ToUpper(); |
| 0 | 442 | | Cache.AddDomainSidMapping(domainName, domainSid); |
| 0 | 443 | | return (true, domainSid); |
| 0 | 444 | | } catch { |
| | 445 | | //We expect this to fail if the username doesn't exist in the domain |
| 0 | 446 | | } |
| | 447 | |
|
| 0 | 448 | | var result = await Query(new LdapQueryParameters() { |
| 0 | 449 | | DomainName = domainName, |
| 0 | 450 | | Attributes = new[] { LDAPProperties.ObjectSID }, |
| 0 | 451 | | LDAPFilter = new LdapFilter().AddFilter(CommonFilters.DomainControllers, true).GetFilter() |
| 0 | 452 | | }).DefaultIfEmpty(LdapResult<IDirectoryObject>.Fail()).FirstOrDefaultAsync(); |
| | 453 | |
|
| 0 | 454 | | if (result.IsSuccess && result.Value.TryGetSecurityIdentifier(out var securityIdentifier)) { |
| 0 | 455 | | domainSid = new SecurityIdentifier(securityIdentifier).AccountDomainSid.Value.ToUpper(); |
| 0 | 456 | | Cache.AddDomainSidMapping(domainName, domainSid); |
| 0 | 457 | | return (true, domainSid); |
| | 458 | | } |
| | 459 | |
|
| 0 | 460 | | return (false, string.Empty); |
| 0 | 461 | | } |
| | 462 | |
|
| | 463 | | /// <summary> |
| | 464 | | /// Attempts to get the Domain object representing the target domain. If null is specified for the domain na |
| | 465 | | /// the user's current domain |
| | 466 | | /// </summary> |
| | 467 | | /// <param name="domain"></param> |
| | 468 | | /// <param name="domainName"></param> |
| | 469 | | /// <returns></returns> |
| 2 | 470 | | public bool GetDomain(string domainName, out Domain domain) { |
| 2 | 471 | | var cacheKey = domainName ?? _nullCacheKey; |
| 2 | 472 | | if (_domainCache.TryGetValue(cacheKey, out domain)) return true; |
| | 473 | |
|
| 2 | 474 | | try { |
| | 475 | | DirectoryContext context; |
| 2 | 476 | | if (_ldapConfig.Username != null) |
| 0 | 477 | | context = domainName != null |
| 0 | 478 | | ? new DirectoryContext(DirectoryContextType.Domain, domainName, _ldapConfig.Username, |
| 0 | 479 | | _ldapConfig.Password) |
| 0 | 480 | | : new DirectoryContext(DirectoryContextType.Domain, _ldapConfig.Username, |
| 0 | 481 | | _ldapConfig.Password); |
| | 482 | | else |
| 2 | 483 | | context = domainName != null |
| 2 | 484 | | ? new DirectoryContext(DirectoryContextType.Domain, domainName) |
| 2 | 485 | | : new DirectoryContext(DirectoryContextType.Domain); |
| | 486 | |
|
| 2 | 487 | | domain = Domain.GetDomain(context); |
| 0 | 488 | | if (domain == null) return false; |
| 0 | 489 | | _domainCache.TryAdd(cacheKey, domain); |
| 0 | 490 | | return true; |
| 4 | 491 | | } catch (Exception e) { |
| 2 | 492 | | _log.LogDebug(e, "GetDomain call failed for domain name {Name}", domainName); |
| 2 | 493 | | return false; |
| | 494 | | } |
| 2 | 495 | | } |
| | 496 | |
|
| 2 | 497 | | public static bool GetDomain(string domainName, LdapConfig ldapConfig, out Domain domain) { |
| 2 | 498 | | if (_domainCache.TryGetValue(domainName, out domain)) return true; |
| | 499 | |
|
| 2 | 500 | | try { |
| | 501 | | DirectoryContext context; |
| 2 | 502 | | if (ldapConfig.Username != null) |
| 0 | 503 | | context = domainName != null |
| 0 | 504 | | ? new DirectoryContext(DirectoryContextType.Domain, domainName, ldapConfig.Username, |
| 0 | 505 | | ldapConfig.Password) |
| 0 | 506 | | : new DirectoryContext(DirectoryContextType.Domain, ldapConfig.Username, |
| 0 | 507 | | ldapConfig.Password); |
| | 508 | | else |
| 2 | 509 | | context = domainName != null |
| 2 | 510 | | ? new DirectoryContext(DirectoryContextType.Domain, domainName) |
| 2 | 511 | | : new DirectoryContext(DirectoryContextType.Domain); |
| | 512 | |
|
| 2 | 513 | | domain = Domain.GetDomain(context); |
| 0 | 514 | | if (domain == null) return false; |
| 0 | 515 | | _domainCache.TryAdd(domainName, domain); |
| 0 | 516 | | return true; |
| 4 | 517 | | } catch (Exception e) { |
| 2 | 518 | | Logging.Logger.LogDebug("Static GetDomain call failed for domain {DomainName}: {Error}", domainName, |
| 2 | 519 | | e.Message); |
| 2 | 520 | | return false; |
| | 521 | | } |
| 2 | 522 | | } |
| | 523 | |
|
| | 524 | | /// <summary> |
| | 525 | | /// Attempts to get the Domain object representing the target domain. If null is specified for the domain na |
| | 526 | | /// the user's current domain |
| | 527 | | /// </summary> |
| | 528 | | /// <param name="domain"></param> |
| | 529 | | /// <param name="domainName"></param> |
| | 530 | | /// <returns></returns> |
| 0 | 531 | | public bool GetDomain(out Domain domain) { |
| 0 | 532 | | if (_domainCache.TryGetValue(_nullCacheKey, out domain)) return true; |
| | 533 | |
|
| 0 | 534 | | try { |
| 0 | 535 | | var context = _ldapConfig.Username != null |
| 0 | 536 | | ? new DirectoryContext(DirectoryContextType.Domain, _ldapConfig.Username, |
| 0 | 537 | | _ldapConfig.Password) |
| 0 | 538 | | : new DirectoryContext(DirectoryContextType.Domain); |
| | 539 | |
|
| 0 | 540 | | domain = Domain.GetDomain(context); |
| 0 | 541 | | _domainCache.TryAdd(_nullCacheKey, domain); |
| 0 | 542 | | return true; |
| 0 | 543 | | } catch (Exception e) { |
| 0 | 544 | | _log.LogDebug(e, "GetDomain call failed for blank domain"); |
| 0 | 545 | | return false; |
| | 546 | | } |
| 0 | 547 | | } |
| | 548 | |
|
| 0 | 549 | | public async Task<(bool Success, TypedPrincipal Principal)> ResolveAccountName(string name, string domain) { |
| 0 | 550 | | if (string.IsNullOrWhiteSpace(name)) { |
| 0 | 551 | | return (false, null); |
| | 552 | | } |
| | 553 | |
|
| 0 | 554 | | if (Cache.GetPrefixedValue(name, domain, out var id) && Cache.GetIDType(id, out var type)) |
| 0 | 555 | | return (true, new TypedPrincipal { |
| 0 | 556 | | ObjectIdentifier = id, |
| 0 | 557 | | ObjectType = type |
| 0 | 558 | | }); |
| | 559 | |
|
| 0 | 560 | | var result = await Query(new LdapQueryParameters() { |
| 0 | 561 | | DomainName = domain, |
| 0 | 562 | | Attributes = CommonProperties.TypeResolutionProps, |
| 0 | 563 | | LDAPFilter = $"(samaccountname={name})" |
| 0 | 564 | | }).DefaultIfEmpty(LdapResult<IDirectoryObject>.Fail()).FirstOrDefaultAsync(); |
| | 565 | |
|
| 0 | 566 | | if (result.IsSuccess && result.Value.GetObjectIdentifier(out id)) { |
| 0 | 567 | | result.Value.GetLabel(out type); |
| 0 | 568 | | Cache.AddPrefixedValue(name, domain, id); |
| 0 | 569 | | Cache.AddType(id, type); |
| | 570 | |
|
| 0 | 571 | | var (tempID, _) = await GetWellKnownPrincipalObjectIdentifier(id, domain); |
| 0 | 572 | | return (true, new TypedPrincipal(tempID, type)); |
| | 573 | | } |
| | 574 | |
|
| 0 | 575 | | return (false, null); |
| 0 | 576 | | } |
| | 577 | |
|
| 1 | 578 | | public async Task<(bool Success, string SecurityIdentifier)> ResolveHostToSid(string host, string domain) { |
| | 579 | | //Remove SPN prefixes from the host name so we're working with a clean name |
| 1 | 580 | | var strippedHost = Helpers.StripServicePrincipalName(host).ToUpper().TrimEnd('$'); |
| 2 | 581 | | if (string.IsNullOrEmpty(strippedHost)) { |
| 1 | 582 | | return (false, string.Empty); |
| | 583 | | } |
| | 584 | |
|
| 0 | 585 | | if (_hostResolutionMap.TryGetValue(strippedHost, out var sid)) return (sid != null, sid); |
| | 586 | |
|
| | 587 | | //Immediately start with NetWkstaGetInfo as it's our most reliable indicator if successful |
| 0 | 588 | | if (await GetWorkstationInfo(strippedHost) is (true, var workstationInfo)) { |
| 0 | 589 | | var tempName = workstationInfo.ComputerName; |
| 0 | 590 | | var tempDomain = workstationInfo.LanGroup; |
| | 591 | |
|
| 0 | 592 | | if (string.IsNullOrWhiteSpace(tempDomain)) { |
| 0 | 593 | | tempDomain = domain; |
| 0 | 594 | | } |
| | 595 | |
|
| 0 | 596 | | if (!string.IsNullOrWhiteSpace(tempName)) { |
| 0 | 597 | | tempName = $"{tempName}$".ToUpper(); |
| 0 | 598 | | if (await ResolveAccountName(tempName, tempDomain) is (true, var principal)) { |
| 0 | 599 | | _hostResolutionMap.TryAdd(strippedHost, principal.ObjectIdentifier); |
| 0 | 600 | | return (true, principal.ObjectIdentifier); |
| | 601 | | } |
| 0 | 602 | | } |
| 0 | 603 | | } |
| | 604 | |
|
| | 605 | | //Try some socket magic to get the NETBIOS name |
| 0 | 606 | | if (RequestNETBIOSNameFromComputer(strippedHost, domain, out var netBiosName)) { |
| 0 | 607 | | if (!string.IsNullOrWhiteSpace(netBiosName)) { |
| 0 | 608 | | var result = await ResolveAccountName($"{netBiosName}$", domain); |
| 0 | 609 | | if (result.Success) { |
| 0 | 610 | | _hostResolutionMap.TryAdd(strippedHost, result.Principal.ObjectIdentifier); |
| 0 | 611 | | return (true, result.Principal.ObjectIdentifier); |
| | 612 | | } |
| 0 | 613 | | } |
| 0 | 614 | | } |
| | 615 | |
|
| | 616 | | //Start by handling non-IP address names |
| 0 | 617 | | if (!IPAddress.TryParse(strippedHost, out _)) { |
| | 618 | | //PRIMARY.TESTLAB.LOCAL |
| 0 | 619 | | if (strippedHost.Contains(".")) { |
| 0 | 620 | | var split = strippedHost.Split('.'); |
| 0 | 621 | | var name = split[0]; |
| 0 | 622 | | var result = await ResolveAccountName($"{name}$", domain); |
| 0 | 623 | | if (result.Success) { |
| 0 | 624 | | _hostResolutionMap.TryAdd(strippedHost, result.Principal.ObjectIdentifier); |
| 0 | 625 | | return (true, result.Principal.ObjectIdentifier); |
| | 626 | | } |
| | 627 | |
|
| 0 | 628 | | var tempDomain = string.Join(".", split.Skip(1).ToArray()); |
| 0 | 629 | | result = await ResolveAccountName($"{name}$", tempDomain); |
| 0 | 630 | | if (result.Success) { |
| 0 | 631 | | _hostResolutionMap.TryAdd(strippedHost, result.Principal.ObjectIdentifier); |
| 0 | 632 | | return (true, result.Principal.ObjectIdentifier); |
| | 633 | | } |
| 0 | 634 | | } else { |
| | 635 | | //Format: WIN10 (probably a netbios name) |
| 0 | 636 | | var result = await ResolveAccountName($"{strippedHost}$", domain); |
| 0 | 637 | | if (result.Success) { |
| 0 | 638 | | _hostResolutionMap.TryAdd(strippedHost, result.Principal.ObjectIdentifier); |
| 0 | 639 | | return (true, result.Principal.ObjectIdentifier); |
| | 640 | | } |
| 0 | 641 | | } |
| 0 | 642 | | } |
| | 643 | |
|
| 0 | 644 | | try { |
| 0 | 645 | | var resolvedHostname = (await Dns.GetHostEntryAsync(strippedHost)).HostName; |
| 0 | 646 | | var split = resolvedHostname.Split('.'); |
| 0 | 647 | | var name = split[0]; |
| 0 | 648 | | var result = await ResolveAccountName($"{name}$", domain); |
| 0 | 649 | | if (result.Success) { |
| 0 | 650 | | _hostResolutionMap.TryAdd(strippedHost, result.Principal.ObjectIdentifier); |
| 0 | 651 | | return (true, result.Principal.ObjectIdentifier); |
| | 652 | | } |
| | 653 | |
|
| 0 | 654 | | var tempDomain = string.Join(".", split.Skip(1).ToArray()); |
| 0 | 655 | | result = await ResolveAccountName($"{name}$", tempDomain); |
| 0 | 656 | | if (result.Success) { |
| 0 | 657 | | _hostResolutionMap.TryAdd(strippedHost, result.Principal.ObjectIdentifier); |
| 0 | 658 | | return (true, result.Principal.ObjectIdentifier); |
| | 659 | | } |
| 0 | 660 | | } catch { |
| | 661 | | //pass |
| 0 | 662 | | } |
| | 663 | |
|
| 0 | 664 | | _hostResolutionMap.TryAdd(strippedHost, null); |
| 0 | 665 | | return (false, ""); |
| 1 | 666 | | } |
| | 667 | |
|
| | 668 | | /// <summary> |
| | 669 | | /// Calls the NetWkstaGetInfo API on a hostname |
| | 670 | | /// </summary> |
| | 671 | | /// <param name="hostname"></param> |
| | 672 | | /// <returns></returns> |
| 0 | 673 | | private async Task<(bool Success, NetAPIStructs.WorkstationInfo100 Info)> GetWorkstationInfo(string hostname) { |
| 0 | 674 | | if (!await _portScanner.CheckPort(hostname)) |
| 0 | 675 | | return (false, default); |
| | 676 | |
|
| 0 | 677 | | var result = _nativeMethods.CallNetWkstaGetInfo(hostname); |
| 0 | 678 | | if (result.IsSuccess) return (true, result.Value); |
| | 679 | |
|
| 0 | 680 | | return (false, default); |
| 0 | 681 | | } |
| | 682 | |
|
| 1 | 683 | | public async Task<(bool Success, string[] Sids)> GetGlobalCatalogMatches(string name, string domain) { |
| 1 | 684 | | if (Cache.GetGCCache(name, out var matches)) { |
| 0 | 685 | | return (true, matches); |
| | 686 | | } |
| | 687 | |
|
| 1 | 688 | | var sids = new List<string>(); |
| | 689 | |
|
| 3 | 690 | | await foreach (var result in Query(new LdapQueryParameters { |
| 1 | 691 | | DomainName = domain, |
| 1 | 692 | | Attributes = new[] { LDAPProperties.ObjectSID }, |
| 1 | 693 | | GlobalCatalog = true, |
| 1 | 694 | | LDAPFilter = new LdapFilter().AddUsers($"(samaccountname={name})").GetFilter() |
| 1 | 695 | | })) { |
| 0 | 696 | | if (result.IsSuccess && result.Value.TryGetSecurityIdentifier(out var sid)) { |
| 0 | 697 | | if (await GetWellKnownPrincipal(sid, domain) is (true, var principal)) { |
| 0 | 698 | | sids.Add(principal.ObjectIdentifier); |
| 0 | 699 | | } else { |
| 0 | 700 | | sids.Add(sid); |
| 0 | 701 | | } |
| 0 | 702 | | } else { |
| 0 | 703 | | return (false, Array.Empty<string>()); |
| | 704 | | } |
| 0 | 705 | | } |
| | 706 | |
|
| 1 | 707 | | Cache.AddGCCache(name, sids.ToArray()); |
| 1 | 708 | | return (true, sids.ToArray()); |
| 1 | 709 | | } |
| | 710 | |
|
| | 711 | | public async Task<(bool Success, TypedPrincipal Principal)> ResolveCertTemplateByProperty(string propertyValue, |
| 0 | 712 | | string propertyName, string domainName) { |
| 0 | 713 | | var filter = new LdapFilter().AddCertificateTemplates() |
| 0 | 714 | | .AddFilter($"({propertyName}={propertyValue})", true); |
| 0 | 715 | | var result = await Query(new LdapQueryParameters { |
| 0 | 716 | | DomainName = domainName, |
| 0 | 717 | | Attributes = CommonProperties.TypeResolutionProps, |
| 0 | 718 | | SearchScope = SearchScope.OneLevel, |
| 0 | 719 | | NamingContext = NamingContext.Configuration, |
| 0 | 720 | | RelativeSearchBase = DirectoryPaths.CertTemplateLocation, |
| 0 | 721 | | LDAPFilter = filter.GetFilter(), |
| 0 | 722 | | }).DefaultIfEmpty(LdapResult<IDirectoryObject>.Fail()).FirstOrDefaultAsync(); |
| | 723 | |
|
| 0 | 724 | | if (!result.IsSuccess) { |
| 0 | 725 | | _log.LogWarning( |
| 0 | 726 | | "Could not find certificate template with {PropertyName}:{PropertyValue}: {Error}", |
| 0 | 727 | | propertyName, propertyValue, result.Error); |
| 0 | 728 | | return (false, null); |
| | 729 | | } |
| | 730 | |
|
| 0 | 731 | | if (result.Value.TryGetGuid(out var guid)) { |
| 0 | 732 | | return (true, new TypedPrincipal(guid, Label.CertTemplate)); |
| | 733 | | } |
| | 734 | |
|
| 0 | 735 | | return (false, default); |
| 0 | 736 | | } |
| | 737 | |
|
| | 738 | | /// <summary> |
| | 739 | | /// Uses a socket and a set of bytes to request the NETBIOS name from a remote computer |
| | 740 | | /// </summary> |
| | 741 | | /// <param name="server"></param> |
| | 742 | | /// <param name="domain"></param> |
| | 743 | | /// <param name="netbios"></param> |
| | 744 | | /// <returns></returns> |
| 0 | 745 | | private static bool RequestNETBIOSNameFromComputer(string server, string domain, out string netbios) { |
| 0 | 746 | | var receiveBuffer = new byte[1024]; |
| 0 | 747 | | var requestSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); |
| 0 | 748 | | try { |
| | 749 | | //Set receive timeout to 1 second |
| 0 | 750 | | requestSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000); |
| | 751 | | EndPoint remoteEndpoint; |
| | 752 | |
|
| | 753 | | //We need to create an endpoint to bind too. If its an IP, just use that. |
| 0 | 754 | | if (IPAddress.TryParse(server, out var parsedAddress)) |
| 0 | 755 | | remoteEndpoint = new IPEndPoint(parsedAddress, 137); |
| | 756 | | else |
| | 757 | | //If its not an IP, we're going to try and resolve it from DNS |
| 0 | 758 | | try { |
| | 759 | | IPAddress address; |
| 0 | 760 | | if (server.Contains(".")) |
| 0 | 761 | | address = Dns |
| 0 | 762 | | .GetHostAddresses(server).First(x => x.AddressFamily == AddressFamily.InterNetwork); |
| | 763 | | else |
| 0 | 764 | | address = Dns.GetHostAddresses($"{server}.{domain}")[0]; |
| | 765 | |
|
| 0 | 766 | | if (address == null) { |
| 0 | 767 | | netbios = null; |
| 0 | 768 | | return false; |
| | 769 | | } |
| | 770 | |
|
| 0 | 771 | | remoteEndpoint = new IPEndPoint(address, 137); |
| 0 | 772 | | } catch { |
| | 773 | | //Failed to resolve an IP, so return null |
| 0 | 774 | | netbios = null; |
| 0 | 775 | | return false; |
| | 776 | | } |
| | 777 | |
|
| 0 | 778 | | var originEndpoint = new IPEndPoint(IPAddress.Any, 0); |
| 0 | 779 | | requestSocket.Bind(originEndpoint); |
| | 780 | |
|
| 0 | 781 | | try { |
| 0 | 782 | | requestSocket.SendTo(NameRequest, remoteEndpoint); |
| 0 | 783 | | var receivedByteCount = requestSocket.ReceiveFrom(receiveBuffer, ref remoteEndpoint); |
| 0 | 784 | | if (receivedByteCount >= 90) { |
| 0 | 785 | | netbios = new ASCIIEncoding().GetString(receiveBuffer, 57, 16).Trim('\0', ' '); |
| 0 | 786 | | return true; |
| | 787 | | } |
| | 788 | |
|
| 0 | 789 | | netbios = null; |
| 0 | 790 | | return false; |
| 0 | 791 | | } catch (SocketException) { |
| 0 | 792 | | netbios = null; |
| 0 | 793 | | return false; |
| | 794 | | } |
| 0 | 795 | | } finally { |
| | 796 | | //Make sure we close the socket if its open |
| 0 | 797 | | requestSocket.Close(); |
| 0 | 798 | | } |
| 0 | 799 | | } |
| | 800 | |
|
| | 801 | | /// <summary> |
| | 802 | | /// Created for testing purposes |
| | 803 | | /// </summary> |
| | 804 | | /// <returns></returns> |
| 0 | 805 | | public ActiveDirectorySecurityDescriptor MakeSecurityDescriptor() { |
| 0 | 806 | | return new ActiveDirectorySecurityDescriptor(new ActiveDirectorySecurity()); |
| 0 | 807 | | } |
| | 808 | |
|
| | 809 | | public async Task<(bool Success, TypedPrincipal Principal)> ConvertLocalWellKnownPrincipal( |
| | 810 | | SecurityIdentifier sid, |
| 0 | 811 | | string computerDomainSid, string computerDomain) { |
| 0 | 812 | | if (!WellKnownPrincipal.GetWellKnownPrincipal(sid.Value, out var common)) return (false, null); |
| | 813 | | //The "Everyone" and "Authenticated Users" principals are special and will be converted to the domain equiva |
| 0 | 814 | | if (sid.Value is "S-1-1-0" or "S-1-5-11") { |
| 0 | 815 | | return await GetWellKnownPrincipal(sid.Value, computerDomain); |
| | 816 | | } |
| | 817 | |
|
| | 818 | | //Use the computer object id + the RID of the sid we looked up to create our new principal |
| 0 | 819 | | var principal = new TypedPrincipal { |
| 0 | 820 | | ObjectIdentifier = $"{computerDomainSid}-{sid.Rid()}", |
| 0 | 821 | | ObjectType = common.ObjectType switch { |
| 0 | 822 | | Label.User => Label.LocalUser, |
| 0 | 823 | | Label.Group => Label.LocalGroup, |
| 0 | 824 | | _ => common.ObjectType |
| 0 | 825 | | } |
| 0 | 826 | | }; |
| | 827 | |
|
| 0 | 828 | | return (true, principal); |
| 0 | 829 | | } |
| | 830 | |
|
| 0 | 831 | | public async Task<bool> IsDomainController(string computerObjectId, string domainName) { |
| 0 | 832 | | if (_domainControllers.Contains(computerObjectId)) { |
| 0 | 833 | | return true; |
| | 834 | | } |
| | 835 | |
|
| 0 | 836 | | var resDomain = await GetDomainNameFromSid(domainName) is (false, var tempDomain) ? tempDomain : domainName; |
| 0 | 837 | | var filter = new LdapFilter().AddFilter(CommonFilters.SpecificSID(computerObjectId), true) |
| 0 | 838 | | .AddFilter(CommonFilters.DomainControllers, true); |
| 0 | 839 | | var result = await Query(new LdapQueryParameters() { |
| 0 | 840 | | DomainName = resDomain, |
| 0 | 841 | | Attributes = CommonProperties.ObjectID, |
| 0 | 842 | | LDAPFilter = filter.GetFilter(), |
| 0 | 843 | | }).DefaultIfEmpty(LdapResult<IDirectoryObject>.Fail()).FirstOrDefaultAsync(); |
| 0 | 844 | | if (result.IsSuccess) { |
| 0 | 845 | | _domainControllers.Add(computerObjectId); |
| 0 | 846 | | } |
| | 847 | |
|
| 0 | 848 | | return result.IsSuccess; |
| 0 | 849 | | } |
| | 850 | |
|
| 0 | 851 | | public async Task<(bool Success, TypedPrincipal Principal)> ResolveDistinguishedName(string distinguishedName) { |
| 0 | 852 | | if (_distinguishedNameCache.TryGetValue(distinguishedName, out var principal)) { |
| 0 | 853 | | return (true, principal); |
| | 854 | | } |
| | 855 | |
|
| 0 | 856 | | if (_unresolvablePrincipals.Contains(distinguishedName)) { |
| 0 | 857 | | return (false, default); |
| | 858 | | } |
| | 859 | |
|
| 0 | 860 | | var domain = Helpers.DistinguishedNameToDomain(distinguishedName); |
| 0 | 861 | | var result = await Query(new LdapQueryParameters { |
| 0 | 862 | | DomainName = domain, |
| 0 | 863 | | Attributes = CommonProperties.TypeResolutionProps, |
| 0 | 864 | | SearchBase = distinguishedName, |
| 0 | 865 | | SearchScope = SearchScope.Base, |
| 0 | 866 | | LDAPFilter = new LdapFilter().AddAllObjects().GetFilter() |
| 0 | 867 | | }).DefaultIfEmpty(LdapResult<IDirectoryObject>.Fail()).FirstOrDefaultAsync(); |
| | 868 | |
|
| 0 | 869 | | if (result.IsSuccess && result.Value.GetObjectIdentifier(out var id)) { |
| 0 | 870 | | var entry = result.Value; |
| | 871 | |
|
| 0 | 872 | | if (await GetWellKnownPrincipal(id, domain) is (true, var wellKnownPrincipal)) { |
| 0 | 873 | | _distinguishedNameCache.TryAdd(distinguishedName, wellKnownPrincipal); |
| 0 | 874 | | return (true, wellKnownPrincipal); |
| | 875 | | } |
| | 876 | |
|
| 0 | 877 | | entry.GetLabel(out var type); |
| 0 | 878 | | principal = new TypedPrincipal(id, type); |
| 0 | 879 | | _distinguishedNameCache.TryAdd(distinguishedName, principal); |
| 0 | 880 | | return (true, principal); |
| | 881 | | } |
| | 882 | |
|
| 0 | 883 | | try { |
| 0 | 884 | | using (var ctx = new PrincipalContext(ContextType.Domain)) { |
| 0 | 885 | | var lookupPrincipal = |
| 0 | 886 | | Principal.FindByIdentity(ctx, IdentityType.DistinguishedName, distinguishedName); |
| 0 | 887 | | if (lookupPrincipal != null) { |
| 0 | 888 | | var entry = ((DirectoryEntry)lookupPrincipal.GetUnderlyingObject()).ToDirectoryObject(); |
| 0 | 889 | | if (entry.GetObjectIdentifier(out var identifier) && entry.GetLabel(out var label)) { |
| 0 | 890 | | if (await GetWellKnownPrincipal(identifier, domain) is (true, var wellKnownPrincipal)) { |
| 0 | 891 | | _distinguishedNameCache.TryAdd(distinguishedName, wellKnownPrincipal); |
| 0 | 892 | | return (true, wellKnownPrincipal); |
| | 893 | | } |
| | 894 | |
|
| 0 | 895 | | principal = new TypedPrincipal(identifier, label); |
| 0 | 896 | | _distinguishedNameCache.TryAdd(distinguishedName, principal); |
| 0 | 897 | | return (true, new TypedPrincipal(identifier, label)); |
| | 898 | | } |
| 0 | 899 | | } |
| | 900 | |
|
| 0 | 901 | | return (false, default); |
| | 902 | | } |
| 0 | 903 | | } catch { |
| 0 | 904 | | _unresolvablePrincipals.Add(distinguishedName); |
| 0 | 905 | | return (false, default); |
| | 906 | | } |
| | 907 | |
|
| 0 | 908 | | } |
| | 909 | |
|
| 0 | 910 | | public async Task<(bool Success, string DSHeuristics)> GetDSHueristics(string domain, string dn) { |
| 0 | 911 | | var configPath = CommonPaths.CreateDNPath(CommonPaths.DirectoryServicePath, dn); |
| 0 | 912 | | var queryParameters = new LdapQueryParameters { |
| 0 | 913 | | Attributes = new[] { LDAPProperties.DSHeuristics }, |
| 0 | 914 | | SearchScope = SearchScope.Base, |
| 0 | 915 | | DomainName = domain, |
| 0 | 916 | | LDAPFilter = new LdapFilter().AddAllObjects().GetFilter(), |
| 0 | 917 | | NamingContext = NamingContext.Configuration, |
| 0 | 918 | | SearchBase = configPath |
| 0 | 919 | | }; |
| | 920 | |
|
| 0 | 921 | | var result = await Query(queryParameters).DefaultIfEmpty(LdapResult<IDirectoryObject>.Fail()) |
| 0 | 922 | | .FirstOrDefaultAsync(); |
| 0 | 923 | | if (result.IsSuccess && |
| 0 | 924 | | result.Value.TryGetProperty(LDAPProperties.DSHeuristics, out var dsh)) { |
| 0 | 925 | | return (true, dsh); |
| | 926 | | } |
| | 927 | |
|
| 0 | 928 | | return (false, null); |
| 0 | 929 | | } |
| | 930 | |
|
| 3 | 931 | | public void AddDomainController(string domainControllerSID) { |
| 3 | 932 | | _domainControllers.Add(domainControllerSID); |
| 3 | 933 | | } |
| | 934 | |
|
| 1 | 935 | | public async IAsyncEnumerable<OutputBase> GetWellKnownPrincipalOutput() { |
| 3 | 936 | | foreach (var wkp in SeenWellKnownPrincipals) { |
| 0 | 937 | | WellKnownPrincipal.GetWellKnownPrincipal(wkp.Value.WkpId, out var principal); |
| 0 | 938 | | OutputBase output = principal.ObjectType switch { |
| 0 | 939 | | Label.User => new User(), |
| 0 | 940 | | Label.Computer => new Computer(), |
| 0 | 941 | | Label.Group => new Group(), |
| 0 | 942 | | Label.GPO => new GPO(), |
| 0 | 943 | | Label.Domain => new OutputTypes.Domain(), |
| 0 | 944 | | Label.OU => new OU(), |
| 0 | 945 | | Label.Container => new Container(), |
| 0 | 946 | | Label.Configuration => new Container(), |
| 0 | 947 | | _ => throw new ArgumentOutOfRangeException() |
| 0 | 948 | | }; |
| | 949 | |
|
| 0 | 950 | | output.Properties.Add("name", $"{principal.ObjectIdentifier}@{wkp.Value.DomainName}".ToUpper()); |
| 0 | 951 | | if (await GetDomainSidFromDomainName(wkp.Value.DomainName) is (true, var sid)) { |
| 0 | 952 | | output.Properties.Add("domainsid", sid); |
| 0 | 953 | | } |
| | 954 | |
|
| 0 | 955 | | output.Properties.Add("domain", wkp.Value.DomainName.ToUpper()); |
| 0 | 956 | | output.ObjectIdentifier = wkp.Key; |
| 0 | 957 | | yield return output; |
| 0 | 958 | | } |
| | 959 | |
|
| 6 | 960 | | await foreach (var entdc in GetEnterpriseDCGroups()) { |
| 1 | 961 | | yield return entdc; |
| 1 | 962 | | } |
| 1 | 963 | | } |
| | 964 | |
|
| 1 | 965 | | private async IAsyncEnumerable<Group> GetEnterpriseDCGroups() { |
| 1 | 966 | | var grouped = new ConcurrentDictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); |
| 1 | 967 | | var forestSidToName = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase); |
| 7 | 968 | | foreach (var domainSid in _domainControllers.Values().GroupBy(x => |
| 6 | 969 | | new SecurityIdentifier(x).AccountDomainSid.Value)) { |
| 2 | 970 | | if (await GetDomainNameFromSid(domainSid.Key) is (true, var domainName) && |
| 2 | 971 | | await GetForest(domainName) is (true, var forestName) && |
| 4 | 972 | | await GetDomainSidFromDomainName(forestName) is (true, var forestDomainSid)) { |
| 2 | 973 | | forestSidToName.TryAdd(forestDomainSid, forestName); |
| 3 | 974 | | if (!grouped.ContainsKey(forestDomainSid)) { |
| 1 | 975 | | grouped[forestDomainSid] = []; |
| 1 | 976 | | } |
| | 977 | |
|
| 15 | 978 | | foreach (var k in domainSid) { |
| 3 | 979 | | grouped[forestDomainSid].Add(k); |
| 3 | 980 | | } |
| 2 | 981 | | } |
| 2 | 982 | | } |
| | 983 | |
|
| 6 | 984 | | foreach (var f in grouped) { |
| 1 | 985 | | if (!forestSidToName.TryGetValue(f.Key, out var forestName)) { |
| 0 | 986 | | continue; |
| | 987 | | } |
| 1 | 988 | | var group = new Group { ObjectIdentifier = $"{forestName}-S-1-5-9" }; |
| 1 | 989 | | group.Properties.Add("name", $"ENTERPRISE DOMAIN CONTROLLERS@{forestName}".ToUpper()); |
| 1 | 990 | | group.Properties.Add("domainsid", f.Key); |
| 1 | 991 | | group.Properties.Add("domain", forestName); |
| 4 | 992 | | group.Members = f.Value.Select(x => new TypedPrincipal(x, Label.Computer)).ToArray(); |
| 1 | 993 | | yield return group; |
| 1 | 994 | | } |
| 1 | 995 | | } |
| | 996 | |
|
| 0 | 997 | | public void SetLdapConfig(LdapConfig config) { |
| 0 | 998 | | _ldapConfig = config; |
| 0 | 999 | | _log.LogInformation("New LDAP Config Set:\n {ConfigString}", config.ToString()); |
| 0 | 1000 | | _connectionPool.Dispose(); |
| 0 | 1001 | | _connectionPool = new ConnectionPoolManager(_ldapConfig, scanner: _portScanner); |
| 0 | 1002 | | } |
| | 1003 | |
|
| 0 | 1004 | | public Task<(bool Success, string Message)> TestLdapConnection(string domain) { |
| 0 | 1005 | | return _connectionPool.TestDomainConnection(domain, false); |
| 0 | 1006 | | } |
| | 1007 | |
|
| 0 | 1008 | | public async Task<(bool Success, string Path)> GetNamingContextPath(string domain, NamingContext context) { |
| 0 | 1009 | | if (await _connectionPool.GetLdapConnection(domain, false) is (true, var wrapper, _)) { |
| 0 | 1010 | | _connectionPool.ReleaseConnection(wrapper); |
| 0 | 1011 | | if (wrapper.GetSearchBase(context, out var searchBase)) { |
| 0 | 1012 | | return (true, searchBase); |
| | 1013 | | } |
| 0 | 1014 | | } |
| | 1015 | |
|
| 0 | 1016 | | var property = context switch { |
| 0 | 1017 | | NamingContext.Default => LDAPProperties.DefaultNamingContext, |
| 0 | 1018 | | NamingContext.Configuration => LDAPProperties.ConfigurationNamingContext, |
| 0 | 1019 | | NamingContext.Schema => LDAPProperties.SchemaNamingContext, |
| 0 | 1020 | | _ => throw new ArgumentOutOfRangeException(nameof(context), context, null) |
| 0 | 1021 | | }; |
| | 1022 | |
|
| 0 | 1023 | | try { |
| 0 | 1024 | | var entry = CreateDirectoryEntry($"LDAP://{domain}/RootDSE"); |
| 0 | 1025 | | if (entry.TryGetProperty(property, out var searchBase)) { |
| 0 | 1026 | | return (true, searchBase); |
| | 1027 | | } |
| 0 | 1028 | | } catch { |
| | 1029 | | //pass |
| 0 | 1030 | | } |
| | 1031 | |
|
| 0 | 1032 | | if (GetDomain(domain, out var domainObj)) { |
| 0 | 1033 | | try { |
| 0 | 1034 | | var entry = domainObj.GetDirectoryEntry().ToDirectoryObject(); |
| 0 | 1035 | | if (entry.TryGetProperty(property, out var searchBase)) { |
| 0 | 1036 | | return (true, searchBase); |
| | 1037 | | } |
| 0 | 1038 | | } catch { |
| | 1039 | | //pass |
| 0 | 1040 | | } |
| | 1041 | |
|
| 0 | 1042 | | var name = domainObj.Name; |
| 0 | 1043 | | if (!string.IsNullOrWhiteSpace(name)) { |
| 0 | 1044 | | var tempPath = Helpers.DomainNameToDistinguishedName(name); |
| | 1045 | |
|
| 0 | 1046 | | var searchBase = context switch { |
| 0 | 1047 | | NamingContext.Configuration => $"CN=Configuration,{tempPath}", |
| 0 | 1048 | | NamingContext.Schema => $"CN=Schema,CN=Configuration,{tempPath}", |
| 0 | 1049 | | NamingContext.Default => tempPath, |
| 0 | 1050 | | _ => throw new ArgumentOutOfRangeException() |
| 0 | 1051 | | }; |
| | 1052 | |
|
| 0 | 1053 | | return (true, searchBase); |
| | 1054 | | } |
| 0 | 1055 | | } |
| | 1056 | |
|
| 0 | 1057 | | return (false, default); |
| 0 | 1058 | | } |
| | 1059 | |
|
| 0 | 1060 | | public void ResetUtils() { |
| 0 | 1061 | | _unresolvablePrincipals = new ConcurrentHashSet(StringComparer.OrdinalIgnoreCase); |
| 0 | 1062 | | _domainCache = new ConcurrentDictionary<string, Domain>(); |
| 0 | 1063 | | _domainControllers = new ConcurrentHashSet(StringComparer.OrdinalIgnoreCase); |
| 0 | 1064 | | _connectionPool?.Dispose(); |
| 0 | 1065 | | _connectionPool = new ConnectionPoolManager(_ldapConfig, scanner: _portScanner); |
| 0 | 1066 | | } |
| | 1067 | |
|
| 0 | 1068 | | private IDirectoryObject CreateDirectoryEntry(string path) { |
| 0 | 1069 | | if (_ldapConfig.Username != null) { |
| 0 | 1070 | | return new DirectoryEntry(path, _ldapConfig.Username, _ldapConfig.Password).ToDirectoryObject(); |
| | 1071 | | } |
| | 1072 | |
|
| 0 | 1073 | | return new DirectoryEntry(path).ToDirectoryObject(); |
| 0 | 1074 | | } |
| | 1075 | |
|
| 0 | 1076 | | public void Dispose() { |
| 0 | 1077 | | _connectionPool?.Dispose(); |
| 0 | 1078 | | } |
| | 1079 | |
|
| | 1080 | | internal static bool ResolveLabel(string objectIdentifier, string distinguishedName, string samAccountType, |
| 27 | 1081 | | string[] objectClasses, int flags, out Label type) { |
| 27 | 1082 | | type = Label.Base; |
| 27 | 1083 | | if (objectIdentifier != null && |
| 28 | 1084 | | WellKnownPrincipal.GetWellKnownPrincipal(objectIdentifier, out var principal)) { |
| 1 | 1085 | | type = principal.ObjectType; |
| 1 | 1086 | | return true; |
| | 1087 | | } |
| | 1088 | |
|
| | 1089 | | //Override GMSA/MSA account to treat them as users for the graph |
| 26 | 1090 | | if (objectClasses != null && |
| 26 | 1091 | | (objectClasses.Contains(ObjectClass.MSAClass, StringComparer.OrdinalIgnoreCase) || |
| 29 | 1092 | | objectClasses.Contains(ObjectClass.GMSAClass, StringComparer.OrdinalIgnoreCase))) { |
| 3 | 1093 | | type = Label.User; |
| 3 | 1094 | | return true; |
| | 1095 | | } |
| | 1096 | |
|
| 32 | 1097 | | if (samAccountType != null) { |
| 9 | 1098 | | var objectType = Helpers.SamAccountTypeToType(samAccountType); |
| 18 | 1099 | | if (objectType != Label.Base) { |
| 9 | 1100 | | type = objectType; |
| 9 | 1101 | | return true; |
| | 1102 | | } |
| 0 | 1103 | | } |
| | 1104 | |
|
| 15 | 1105 | | if (objectClasses == null || objectClasses.Length == 0) { |
| 1 | 1106 | | type = Label.Base; |
| 1 | 1107 | | return false; |
| | 1108 | | } |
| | 1109 | |
|
| 13 | 1110 | | if (objectClasses.Contains(ObjectClass.GroupPolicyContainerClass, StringComparer.OrdinalIgnoreCase)) |
| 1 | 1111 | | type = Label.GPO; |
| 12 | 1112 | | else if (objectClasses.Contains(ObjectClass.OrganizationalUnitClass, StringComparer.OrdinalIgnoreCase)) |
| 0 | 1113 | | type = Label.OU; |
| 12 | 1114 | | else if (objectClasses.Contains(ObjectClass.DomainClass, StringComparer.OrdinalIgnoreCase)) |
| 1 | 1115 | | type = Label.Domain; |
| 11 | 1116 | | else if (objectClasses.Contains(ObjectClass.ContainerClass, StringComparer.OrdinalIgnoreCase)) |
| 1 | 1117 | | type = Label.Container; |
| 10 | 1118 | | else if (objectClasses.Contains(ObjectClass.ConfigurationClass, StringComparer.OrdinalIgnoreCase)) |
| 1 | 1119 | | type = Label.Configuration; |
| 9 | 1120 | | else if (objectClasses.Contains(ObjectClass.PKICertificateTemplateClass, StringComparer.OrdinalIgnoreCase)) |
| 1 | 1121 | | type = Label.CertTemplate; |
| 8 | 1122 | | else if (objectClasses.Contains(ObjectClass.PKIEnrollmentServiceClass, StringComparer.OrdinalIgnoreCase)) |
| 1 | 1123 | | type = Label.EnterpriseCA; |
| 7 | 1124 | | else if (objectClasses.Contains(ObjectClass.CertificationAuthorityClass, |
| 11 | 1125 | | StringComparer.OrdinalIgnoreCase)) { |
| 4 | 1126 | | if (distinguishedName.IndexOf(DirectoryPaths.RootCALocation, StringComparison.OrdinalIgnoreCase) >= 0) |
| 1 | 1127 | | type = Label.RootCA; |
| 4 | 1128 | | if (distinguishedName.IndexOf(DirectoryPaths.AIACALocation, StringComparison.OrdinalIgnoreCase) >= 0) |
| 1 | 1129 | | type = Label.AIACA; |
| 4 | 1130 | | if (distinguishedName.IndexOf(DirectoryPaths.NTAuthStoreLocation, StringComparison.OrdinalIgnoreCase) >= |
| 4 | 1131 | | 0) |
| 2 | 1132 | | type = Label.NTAuthStore; |
| 9 | 1133 | | } else if (objectClasses.Contains(ObjectClass.OIDContainerClass, StringComparer.OrdinalIgnoreCase)) { |
| 2 | 1134 | | if (distinguishedName.StartsWith(DirectoryPaths.OIDContainerLocation, |
| 2 | 1135 | | StringComparison.OrdinalIgnoreCase)) |
| 1 | 1136 | | type = Label.Container; |
| 2 | 1137 | | else if (flags == 2) { |
| 1 | 1138 | | type = Label.IssuancePolicy; |
| 1 | 1139 | | } |
| 2 | 1140 | | } |
| | 1141 | |
|
| 13 | 1142 | | return type != Label.Base; |
| 27 | 1143 | | } |
| | 1144 | |
|
| | 1145 | | public static async Task<(bool Success, ResolvedSearchResult ResolvedResult)> ResolveSearchResult( |
| 8 | 1146 | | IDirectoryObject directoryObject, ILdapUtils utils) { |
| 9 | 1147 | | if (!directoryObject.GetObjectIdentifier(out var objectIdentifier)) { |
| 1 | 1148 | | return (false, default); |
| | 1149 | | } |
| | 1150 | |
|
| 7 | 1151 | | var res = new ResolvedSearchResult { |
| 7 | 1152 | | ObjectId = objectIdentifier |
| 7 | 1153 | | }; |
| | 1154 | |
|
| | 1155 | | //If the object is deleted, we can short circuit the rest of this logic as we don't really care about anythi |
| 8 | 1156 | | if (directoryObject.IsDeleted()) { |
| 1 | 1157 | | res.Deleted = true; |
| 1 | 1158 | | return (true, res); |
| | 1159 | | } |
| | 1160 | |
|
| 11 | 1161 | | if (directoryObject.TryGetLongProperty(LDAPProperties.UserAccountControl, out var rawUac)) { |
| 5 | 1162 | | var flags = (UacFlags)rawUac; |
| 10 | 1163 | | if (flags.HasFlag(UacFlags.ServerTrustAccount)) { |
| 5 | 1164 | | res.IsDomainController = true; |
| 5 | 1165 | | utils.AddDomainController(objectIdentifier); |
| 5 | 1166 | | } |
| 5 | 1167 | | } |
| | 1168 | |
|
| | 1169 | | string domain; |
| | 1170 | |
|
| 8 | 1171 | | if (directoryObject.TryGetDistinguishedName(out var distinguishedName)) { |
| 2 | 1172 | | domain = Helpers.DistinguishedNameToDomain(distinguishedName); |
| 6 | 1173 | | } else { |
| 4 | 1174 | | if (objectIdentifier.StartsWith("S-1-5") && |
| 8 | 1175 | | await utils.GetDomainNameFromSid(objectIdentifier) is (true, var domainName)) { |
| 4 | 1176 | | domain = domainName; |
| 4 | 1177 | | } else { |
| 0 | 1178 | | return (false, default); |
| | 1179 | | } |
| 4 | 1180 | | } |
| | 1181 | |
|
| | 1182 | | string domainSid; |
| 6 | 1183 | | var match = SIDRegex.Match(objectIdentifier); |
| 12 | 1184 | | if (match.Success) { |
| 6 | 1185 | | domainSid = match.Groups[1].Value; |
| 6 | 1186 | | } else if (await utils.GetDomainSidFromDomainName(domain) is (true, var sid)) { |
| 0 | 1187 | | domainSid = sid; |
| 0 | 1188 | | } else { |
| 0 | 1189 | | Logging.Logger.LogWarning("Failed to resolve domain sid for object {Identifier}", objectIdentifier); |
| 0 | 1190 | | domainSid = null; |
| 0 | 1191 | | } |
| | 1192 | |
|
| 6 | 1193 | | res.Domain = domain; |
| 6 | 1194 | | res.DomainSid = domainSid; |
| | 1195 | |
|
| 6 | 1196 | | if (WellKnownPrincipal.GetWellKnownPrincipal(objectIdentifier, out var wellKnownPrincipal)) { |
| 0 | 1197 | | res.DisplayName = $"{wellKnownPrincipal.ObjectIdentifier}@{domain}"; |
| 0 | 1198 | | res.ObjectType = wellKnownPrincipal.ObjectType; |
| 0 | 1199 | | if (await utils.GetWellKnownPrincipal(objectIdentifier, domain) is (true, var convertedPrincipal)) { |
| 0 | 1200 | | res.ObjectId = convertedPrincipal.ObjectIdentifier; |
| 0 | 1201 | | } |
| | 1202 | |
|
| 0 | 1203 | | return (true, res); |
| | 1204 | | } |
| | 1205 | |
|
| 6 | 1206 | | if (!directoryObject.GetLabel(out var label)) { |
| 0 | 1207 | | if (await utils.ResolveIDAndType(objectIdentifier, domain) is (true, var typedPrincipal)) { |
| 0 | 1208 | | label = typedPrincipal.ObjectType; |
| 0 | 1209 | | } |
| 0 | 1210 | | } |
| | 1211 | |
|
| 7 | 1212 | | if (directoryObject.IsMSA() || directoryObject.IsGMSA()) { |
| 1 | 1213 | | label = Label.User; |
| 1 | 1214 | | } |
| | 1215 | |
|
| 6 | 1216 | | res.ObjectType = label; |
| | 1217 | |
|
| 6 | 1218 | | directoryObject.TryGetProperty(LDAPProperties.SAMAccountName, out var samAccountName); |
| | 1219 | |
|
| 6 | 1220 | | switch (label) { |
| | 1221 | | case Label.User: |
| | 1222 | | case Label.Group: |
| | 1223 | | case Label.Base: |
| 1 | 1224 | | res.DisplayName = $"{samAccountName}@{domain}"; |
| 1 | 1225 | | break; |
| 5 | 1226 | | case Label.Computer: { |
| 5 | 1227 | | var shortName = samAccountName?.TrimEnd('$'); |
| 7 | 1228 | | if (directoryObject.TryGetProperty(LDAPProperties.DNSHostName, out var dns)) { |
| 2 | 1229 | | res.DisplayName = dns; |
| 5 | 1230 | | } else if (!string.IsNullOrWhiteSpace(shortName)) { |
| 0 | 1231 | | res.DisplayName = $"{shortName}.{domain}"; |
| 3 | 1232 | | } else if (directoryObject.TryGetProperty(LDAPProperties.CanonicalName, |
| 4 | 1233 | | out var canonicalName)) { |
| 1 | 1234 | | res.DisplayName = $"{canonicalName}.{domain}"; |
| 4 | 1235 | | } else if (directoryObject.TryGetProperty(LDAPProperties.Name, out var name)) { |
| 1 | 1236 | | res.DisplayName = $"{name}.{domain}"; |
| 2 | 1237 | | } else { |
| 1 | 1238 | | res.DisplayName = $"UNKNOWN.{domain}"; |
| 1 | 1239 | | } |
| | 1240 | |
|
| 5 | 1241 | | break; |
| | 1242 | | } |
| | 1243 | | case Label.GPO: |
| 0 | 1244 | | case Label.IssuancePolicy: { |
| 0 | 1245 | | if (directoryObject.TryGetProperty(LDAPProperties.DisplayName, out var displayName)) { |
| 0 | 1246 | | res.DisplayName = $"{displayName}@{domain}"; |
| 0 | 1247 | | } else if (directoryObject.TryGetProperty(LDAPProperties.CanonicalName, |
| 0 | 1248 | | out var canonicalName)) { |
| 0 | 1249 | | res.DisplayName = $"{canonicalName}@{domain}"; |
| 0 | 1250 | | } else { |
| 0 | 1251 | | res.DisplayName = $"UNKNOWN@{domain}"; |
| 0 | 1252 | | } |
| | 1253 | |
|
| 0 | 1254 | | break; |
| | 1255 | | } |
| | 1256 | | case Label.Domain: |
| 0 | 1257 | | res.DisplayName = domain; |
| 0 | 1258 | | break; |
| 0 | 1259 | | case Label.OU: { |
| 0 | 1260 | | if (directoryObject.TryGetProperty(LDAPProperties.Name, out var name)) { |
| 0 | 1261 | | res.DisplayName = $"{name}@{domain}"; |
| 0 | 1262 | | } else if (directoryObject.TryGetProperty(LDAPProperties.OU, out var ou)) { |
| 0 | 1263 | | res.DisplayName = $"{ou}@{domain}"; |
| 0 | 1264 | | } else { |
| 0 | 1265 | | res.DisplayName = $"UNKNOWN@{domain}"; |
| 0 | 1266 | | } |
| | 1267 | |
|
| 0 | 1268 | | break; |
| | 1269 | | } |
| 0 | 1270 | | case Label.Container: { |
| 0 | 1271 | | if (directoryObject.TryGetProperty(LDAPProperties.Name, out var name)) { |
| 0 | 1272 | | res.DisplayName = $"{name}@{domain}"; |
| 0 | 1273 | | } else if (directoryObject.TryGetProperty(LDAPProperties.CanonicalName, |
| 0 | 1274 | | out var canonicalName)) { |
| 0 | 1275 | | res.DisplayName = $"{canonicalName}@{domain}"; |
| 0 | 1276 | | } else { |
| 0 | 1277 | | res.DisplayName = $"UNKNOWN@{domain}"; |
| 0 | 1278 | | } |
| | 1279 | |
|
| 0 | 1280 | | break; |
| | 1281 | | } |
| | 1282 | | case Label.Configuration: |
| | 1283 | | case Label.RootCA: |
| | 1284 | | case Label.AIACA: |
| | 1285 | | case Label.NTAuthStore: |
| | 1286 | | case Label.EnterpriseCA: |
| 0 | 1287 | | case Label.CertTemplate: { |
| 0 | 1288 | | if (directoryObject.TryGetProperty(LDAPProperties.Name, out var name)) { |
| 0 | 1289 | | res.DisplayName = $"{name}@{domain}"; |
| 0 | 1290 | | } else { |
| 0 | 1291 | | res.DisplayName = $"UNKNOWN@{domain}"; |
| 0 | 1292 | | } |
| | 1293 | |
|
| 0 | 1294 | | break; |
| | 1295 | | } |
| | 1296 | | default: |
| 0 | 1297 | | throw new ArgumentOutOfRangeException(); |
| | 1298 | | } |
| | 1299 | |
|
| 6 | 1300 | | res.DisplayName = res.DisplayName.ToUpper(); |
| 6 | 1301 | | return (true, res); |
| 8 | 1302 | | } |
| | 1303 | | } |
| | 1304 | | } |