| | 1 | | using System; |
| | 2 | | using System.Collections.Concurrent; |
| | 3 | | using System.Collections.Generic; |
| | 4 | | using System.Security.Principal; |
| | 5 | | using System.Threading.Tasks; |
| | 6 | | using Microsoft.Extensions.Logging; |
| | 7 | | using SharpHoundCommonLib.Enums; |
| | 8 | | using SharpHoundCommonLib.OutputTypes; |
| | 9 | | using SharpHoundRPC; |
| | 10 | | using SharpHoundRPC.Shared; |
| | 11 | | using SharpHoundRPC.Wrappers; |
| | 12 | |
|
| | 13 | | namespace SharpHoundCommonLib.Processors |
| | 14 | | { |
| | 15 | | public class LocalGroupProcessor |
| | 16 | | { |
| | 17 | | public delegate Task ComputerStatusDelegate(CSVComputerStatus status); |
| | 18 | | private readonly ILogger _log; |
| | 19 | | private readonly ILdapUtils _utils; |
| | 20 | |
|
| 5 | 21 | | public LocalGroupProcessor(ILdapUtils utils, ILogger log = null) |
| 5 | 22 | | { |
| 5 | 23 | | _utils = utils; |
| 5 | 24 | | _log = log ?? Logging.LogProvider.CreateLogger("LocalGroupProcessor"); |
| 5 | 25 | | } |
| | 26 | |
|
| | 27 | | public event ComputerStatusDelegate ComputerStatusEvent; |
| | 28 | |
|
| | 29 | | public virtual SharpHoundRPC.Result<ISAMServer> OpenSamServer(string computerName) |
| 0 | 30 | | { |
| 0 | 31 | | var result = SAMServer.OpenServer(computerName); |
| 0 | 32 | | if (result.IsFailed) |
| 0 | 33 | | { |
| 0 | 34 | | return SharpHoundRPC.Result<ISAMServer>.Fail(result.SError); |
| | 35 | | } |
| | 36 | |
|
| 0 | 37 | | return SharpHoundRPC.Result<ISAMServer>.Ok(result.Value); |
| 0 | 38 | | } |
| | 39 | |
|
| | 40 | | public IAsyncEnumerable<LocalGroupAPIResult> GetLocalGroups(ResolvedSearchResult result) |
| 0 | 41 | | { |
| 0 | 42 | | return GetLocalGroups(result.DisplayName, result.ObjectId, result.Domain, result.IsDomainController); |
| 0 | 43 | | } |
| | 44 | |
|
| | 45 | | /// <summary> |
| | 46 | | /// Gets local groups from a computer |
| | 47 | | /// </summary> |
| | 48 | | /// <param name="computerName"></param> |
| | 49 | | /// <param name="computerObjectId">The objectsid of the computer in the domain</param> |
| | 50 | | /// <param name="computerDomain">The domain the computer belongs too</param> |
| | 51 | | /// <param name="isDomainController">Is the computer a domain controller</param> |
| | 52 | | /// <param name="timeout"></param> |
| | 53 | | /// <returns></returns> |
| | 54 | | public async IAsyncEnumerable<LocalGroupAPIResult> GetLocalGroups(string computerName, string computerObjectId, |
| | 55 | | string computerDomain, bool isDomainController, TimeSpan timeout = default) |
| 3 | 56 | | { |
| 5 | 57 | | if (timeout == default) { |
| 2 | 58 | | timeout = TimeSpan.FromMinutes(2); |
| 2 | 59 | | } |
| | 60 | |
|
| | 61 | | //Open a handle to the server |
| 6 | 62 | | var openServerResult = await Task.Run(() => OpenSamServer(computerName)).TimeoutAfter(timeout); |
| 3 | 63 | | if (openServerResult.IsFailed) |
| 1 | 64 | | { |
| 1 | 65 | | _log.LogTrace("OpenServer failed on {ComputerName}: {Error}", computerName, openServerResult.SError); |
| 1 | 66 | | await SendComputerStatus(new CSVComputerStatus |
| 1 | 67 | | { |
| 1 | 68 | | Task = "SamConnect", |
| 1 | 69 | | ComputerName = computerName, |
| 1 | 70 | | Status = openServerResult.SError |
| 1 | 71 | | }); |
| 1 | 72 | | yield break; |
| | 73 | | } |
| | 74 | |
|
| 2 | 75 | | var server = openServerResult.Value; |
| 2 | 76 | | var typeCache = new ConcurrentDictionary<string, CachedLocalItem>(); |
| | 77 | |
|
| | 78 | | //Try to get the machine sid for the computer if its not already cached |
| | 79 | | SecurityIdentifier machineSid; |
| 4 | 80 | | if (!Cache.GetMachineSid(computerObjectId, out var tempMachineSid)) { |
| 4 | 81 | | var getMachineSidResult = await Task.Run(() => server.GetMachineSid()).TimeoutAfter(timeout); |
| 2 | 82 | | if (getMachineSidResult.IsFailed) |
| 0 | 83 | | { |
| 0 | 84 | | _log.LogTrace("GetMachineSid failed on {ComputerName}: {Error}", computerName, getMachineSidResult.S |
| 0 | 85 | | await SendComputerStatus(new CSVComputerStatus |
| 0 | 86 | | { |
| 0 | 87 | | Status = getMachineSidResult.SError, |
| 0 | 88 | | ComputerName = computerName, |
| 0 | 89 | | Task = "GetMachineSid" |
| 0 | 90 | | }); |
| | 91 | | //If we can't get a machine sid, we wont be able to make local principals with unique object ids, or |
| 0 | 92 | | _log.LogWarning("Unable to get machineSid for {Computer}: {Status}. Abandoning local group processin |
| 0 | 93 | | yield break; |
| | 94 | | } |
| | 95 | |
|
| 2 | 96 | | machineSid = getMachineSidResult.Value; |
| 2 | 97 | | Cache.AddMachineSid(computerObjectId, machineSid.Value); |
| 2 | 98 | | } |
| | 99 | | else |
| 0 | 100 | | { |
| 0 | 101 | | machineSid = new SecurityIdentifier(tempMachineSid); |
| 0 | 102 | | } |
| | 103 | |
|
| | 104 | | //Get all available domains in the server |
| 4 | 105 | | var getDomainsResult = await Task.Run(() => server.GetDomains()).TimeoutAfter(timeout); |
| 2 | 106 | | if (getDomainsResult.IsFailed) |
| 0 | 107 | | { |
| 0 | 108 | | _log.LogTrace("GetDomains failed on {ComputerName}: {Error}", computerName, getDomainsResult.SError); |
| 0 | 109 | | await SendComputerStatus(new CSVComputerStatus |
| 0 | 110 | | { |
| 0 | 111 | | Task = "GetDomains", |
| 0 | 112 | | ComputerName = computerName, |
| 0 | 113 | | Status = getDomainsResult.SError |
| 0 | 114 | | }); |
| 0 | 115 | | yield break; |
| | 116 | | } |
| | 117 | |
|
| | 118 | | //Loop over each domain result and process its member groups |
| 12 | 119 | | foreach (var domainResult in getDomainsResult.Value) |
| 3 | 120 | | { |
| | 121 | | //Skip non-builtin domains on domain controllers |
| 3 | 122 | | if (isDomainController && !domainResult.Name.Equals("builtin", StringComparison.OrdinalIgnoreCase)) |
| 0 | 123 | | continue; |
| | 124 | |
|
| | 125 | | //Open a handle to the domain |
| 6 | 126 | | var openDomainResult = await Task.Run(() => server.OpenDomain(domainResult.Name)).TimeoutAfter(timeout); |
| 3 | 127 | | if (openDomainResult.IsFailed) |
| 0 | 128 | | { |
| 0 | 129 | | _log.LogTrace("Failed to open domain {Domain} on {ComputerName}: {Error}", domainResult.Name, comput |
| 0 | 130 | | await SendComputerStatus(new CSVComputerStatus |
| 0 | 131 | | { |
| 0 | 132 | | Task = $"OpenDomain - {domainResult.Name}", |
| 0 | 133 | | ComputerName = computerName, |
| 0 | 134 | | Status = openDomainResult.SError |
| 0 | 135 | | }); |
| 0 | 136 | | if (openDomainResult.IsTimeout) { |
| 0 | 137 | | yield break; |
| | 138 | | } |
| 0 | 139 | | continue; |
| | 140 | | } |
| | 141 | |
|
| 3 | 142 | | var domain = openDomainResult.Value; |
| | 143 | |
|
| | 144 | | //Open a handle to the available aliases |
| 6 | 145 | | var getAliasesResult = await Task.Run(() => domain.GetAliases()).TimeoutAfter(timeout); |
| | 146 | |
|
| 3 | 147 | | if (getAliasesResult.IsFailed) |
| 0 | 148 | | { |
| 0 | 149 | | _log.LogTrace("Failed to open Aliases on Domain {Domain} on on {ComputerName}: {Error}", domainResul |
| 0 | 150 | | await SendComputerStatus(new CSVComputerStatus |
| 0 | 151 | | { |
| 0 | 152 | | Task = $"GetAliases - {domainResult.Name}", |
| 0 | 153 | | ComputerName = computerName, |
| 0 | 154 | | Status = getAliasesResult.SError |
| 0 | 155 | | }); |
| | 156 | |
|
| 0 | 157 | | if (getAliasesResult.IsTimeout) { |
| 0 | 158 | | yield break; |
| | 159 | | } |
| 0 | 160 | | continue; |
| | 161 | | } |
| | 162 | |
|
| 19 | 163 | | foreach (var alias in getAliasesResult.Value) |
| 5 | 164 | | { |
| 5 | 165 | | _log.LogTrace("Opening alias {Alias} with RID {Rid} in domain {Domain} on computer {ComputerName}", |
| | 166 | | //Try and resolve the group name using several different criteria |
| 5 | 167 | | var resolvedName = await ResolveGroupName(alias.Name, computerName, computerObjectId, computerDomain |
| 5 | 168 | | isDomainController, |
| 5 | 169 | | domainResult.Name.Equals("builtin", StringComparison.OrdinalIgnoreCase)); |
| | 170 | |
|
| 5 | 171 | | var ret = new LocalGroupAPIResult |
| 5 | 172 | | { |
| 5 | 173 | | Name = resolvedName.PrincipalName, |
| 5 | 174 | | ObjectIdentifier = resolvedName.ObjectId |
| 5 | 175 | | }; |
| | 176 | |
|
| | 177 | | //Open a handle to the alias |
| 10 | 178 | | var openAliasResult = await Task.Run(() => domain.OpenAlias(alias.Rid)).TimeoutAfter(timeout); |
| 5 | 179 | | if (openAliasResult.IsFailed) |
| 0 | 180 | | { |
| 0 | 181 | | _log.LogTrace("Failed to open alias {Alias} with RID {Rid} in domain {Domain} on computer {Compu |
| 0 | 182 | | await SendComputerStatus(new CSVComputerStatus |
| 0 | 183 | | { |
| 0 | 184 | | Task = $"OpenAlias - {alias.Name}", |
| 0 | 185 | | ComputerName = computerName, |
| 0 | 186 | | Status = openAliasResult.SError |
| 0 | 187 | | }); |
| 0 | 188 | | ret.Collected = false; |
| 0 | 189 | | ret.FailureReason = $"SamOpenAliasInDomain failed with status {openAliasResult.SError}"; |
| 0 | 190 | | yield return ret; |
| 0 | 191 | | if (openAliasResult.IsTimeout) { |
| 0 | 192 | | yield break; |
| | 193 | | } |
| 0 | 194 | | continue; |
| | 195 | | } |
| | 196 | |
|
| 5 | 197 | | var localGroup = openAliasResult.Value; |
| | 198 | | //Call GetMembersInAlias to get raw group members |
| 10 | 199 | | var getMembersResult = await Task.Run(() => localGroup.GetMembers()).TimeoutAfter(timeout); |
| 5 | 200 | | if (getMembersResult.IsFailed) |
| 0 | 201 | | { |
| 0 | 202 | | _log.LogTrace("Failed to get members in alias {Alias} with RID {Rid} in domain {Domain} on compu |
| 0 | 203 | | await SendComputerStatus(new CSVComputerStatus |
| 0 | 204 | | { |
| 0 | 205 | | Task = $"GetMembersInAlias - {alias.Name}", |
| 0 | 206 | | ComputerName = computerName, |
| 0 | 207 | | Status = getMembersResult.SError |
| 0 | 208 | | }); |
| 0 | 209 | | ret.Collected = false; |
| 0 | 210 | | ret.FailureReason = $"SamGetMembersInAlias failed with status {getMembersResult.SError}"; |
| 0 | 211 | | yield return ret; |
| 0 | 212 | | if (getMembersResult.IsTimeout) { |
| 0 | 213 | | yield break; |
| | 214 | | } |
| 0 | 215 | | continue; |
| | 216 | | } |
| | 217 | |
|
| 5 | 218 | | await SendComputerStatus(new CSVComputerStatus |
| 5 | 219 | | { |
| 5 | 220 | | Task = $"GetMembersInAlias - {alias.Name}", |
| 5 | 221 | | ComputerName = computerName, |
| 5 | 222 | | Status = CSVComputerStatus.StatusSuccess |
| 5 | 223 | | }); |
| | 224 | |
|
| 5 | 225 | | var results = new List<TypedPrincipal>(); |
| 5 | 226 | | var names = new List<NamedPrincipal>(); |
| | 227 | |
|
| 37 | 228 | | foreach (var securityIdentifier in getMembersResult.Value) |
| 11 | 229 | | { |
| 11 | 230 | | _log.LogTrace("Got member sid {Sid} in alias {Alias} with RID {Rid} in domain {Domain} on comput |
| | 231 | | //Check if the sid is one of our filtered ones. Throw it out if it is |
| 11 | 232 | | if (Helpers.IsSidFiltered(securityIdentifier.Value)) |
| 1 | 233 | | continue; |
| | 234 | |
|
| 10 | 235 | | var sidValue = securityIdentifier.Value; |
| | 236 | |
|
| 10 | 237 | | if (isDomainController) |
| 5 | 238 | | { |
| 5 | 239 | | var result = await ResolveDomainControllerPrincipal(sidValue, computerDomain); |
| 7 | 240 | | if (result != null) results.Add(result); |
| 5 | 241 | | continue; |
| | 242 | | } |
| | 243 | |
|
| | 244 | | //If we get a local well known principal, we need to convert it using the computer's objectid |
| 5 | 245 | | if (await _utils.ConvertLocalWellKnownPrincipal(securityIdentifier, computerObjectId, computerDo |
| 1 | 246 | | { |
| | 247 | | //If the principal is null, it means we hit a weird edge case, but this is a local well know |
| 1 | 248 | | results.Add(principal); |
| 1 | 249 | | continue; |
| | 250 | | } |
| | 251 | |
|
| | 252 | | //If the security identifier starts with the machine sid, we need to resolve it as a local objec |
| 4 | 253 | | if (securityIdentifier.IsEqualDomainSid(machineSid)) |
| 3 | 254 | | { |
| | 255 | | //Check if we've already previously resolved and cached this sid |
| 3 | 256 | | if (typeCache.TryGetValue(sidValue, out var cachedLocalItem)) |
| 0 | 257 | | { |
| 0 | 258 | | results.Add(new TypedPrincipal |
| 0 | 259 | | { |
| 0 | 260 | | ObjectIdentifier = sidValue, |
| 0 | 261 | | ObjectType = cachedLocalItem.Type |
| 0 | 262 | | }); |
| | 263 | |
|
| 0 | 264 | | names.Add(new NamedPrincipal |
| 0 | 265 | | { |
| 0 | 266 | | ObjectId = sidValue, |
| 0 | 267 | | PrincipalName = cachedLocalItem.Name |
| 0 | 268 | | }); |
| | 269 | | //Move on |
| 0 | 270 | | continue; |
| | 271 | | } |
| | 272 | |
|
| | 273 | | //Attempt to lookup the principal in the server directly |
| 3 | 274 | | var lookupUserResult = server.LookupPrincipalBySid(securityIdentifier); |
| 3 | 275 | | if (lookupUserResult.IsFailed) |
| 0 | 276 | | { |
| 0 | 277 | | _log.LogTrace("Unable to resolve local sid {SID}: {Error}", sidValue, lookupUserResult.S |
| 0 | 278 | | continue; |
| | 279 | | } |
| | 280 | |
|
| 3 | 281 | | var (name, use) = lookupUserResult.Value; |
| 3 | 282 | | var objectType = use switch |
| 3 | 283 | | { |
| 2 | 284 | | SharedEnums.SidNameUse.User => Label.LocalUser, |
| 0 | 285 | | SharedEnums.SidNameUse.Group => Label.LocalGroup, |
| 1 | 286 | | SharedEnums.SidNameUse.Alias => Label.LocalGroup, |
| 0 | 287 | | _ => Label.Base |
| 3 | 288 | | }; |
| | 289 | |
|
| | 290 | | // Cache whatever we looked up for future lookups |
| 3 | 291 | | typeCache.TryAdd(sidValue, new CachedLocalItem(name, objectType)); |
| | 292 | |
|
| | 293 | | // Throw out local users |
| 3 | 294 | | if (objectType == Label.LocalUser) |
| 2 | 295 | | continue; |
| | 296 | |
|
| 1 | 297 | | var newSid = $"{computerObjectId}-{securityIdentifier.Rid()}"; |
| | 298 | |
|
| 1 | 299 | | results.Add(new TypedPrincipal |
| 1 | 300 | | { |
| 1 | 301 | | ObjectIdentifier = newSid, |
| 1 | 302 | | ObjectType = objectType |
| 1 | 303 | | }); |
| | 304 | |
|
| 1 | 305 | | names.Add(new NamedPrincipal |
| 1 | 306 | | { |
| 1 | 307 | | PrincipalName = name, |
| 1 | 308 | | ObjectId = newSid |
| 1 | 309 | | }); |
| 1 | 310 | | continue; |
| | 311 | | } |
| | 312 | |
|
| | 313 | | //If we get here, we most likely have a domain principal in a local group |
| 1 | 314 | | var resolvedPrincipal = await _utils.ResolveIDAndType(sidValue, computerDomain); |
| 2 | 315 | | if (resolvedPrincipal.Success) results.Add(resolvedPrincipal.Principal); |
| 1 | 316 | | } |
| | 317 | |
|
| 5 | 318 | | ret.Collected = true; |
| 5 | 319 | | ret.LocalNames = names.ToArray(); |
| 5 | 320 | | ret.Results = results.ToArray(); |
| 5 | 321 | | yield return ret; |
| 5 | 322 | | } |
| 3 | 323 | | } |
| 3 | 324 | | } |
| | 325 | |
|
| | 326 | | private async Task<TypedPrincipal> ResolveDomainControllerPrincipal(string sid, string computerDomain) |
| 5 | 327 | | { |
| | 328 | | //If the server is a domain controller and we have a well known group, use the domain value |
| 5 | 329 | | if (await _utils.GetWellKnownPrincipal(sid, computerDomain) is (true, var wellKnown)) |
| 1 | 330 | | return wellKnown; |
| 4 | 331 | | return (await _utils.ResolveIDAndType(sid, computerDomain)).Principal; |
| 5 | 332 | | } |
| | 333 | |
|
| | 334 | | private async Task<NamedPrincipal> ResolveGroupName(string baseName, string computerName, string computerDomainS |
| | 335 | | string domainName, int groupRid, bool isDc, bool isBuiltIn) |
| 7 | 336 | | { |
| 7 | 337 | | if (isDc) |
| 3 | 338 | | { |
| 3 | 339 | | if (isBuiltIn) |
| 3 | 340 | | { |
| | 341 | | //If this is the builtin group on the DC, the groups correspond to the domain well known groups |
| 3 | 342 | | if (await _utils.GetWellKnownPrincipal($"S-1-5-32-{groupRid}".ToUpper(), domainName) is (true, var p |
| 3 | 343 | | return new NamedPrincipal |
| 3 | 344 | | { |
| 3 | 345 | | ObjectId = principal.ObjectIdentifier, |
| 3 | 346 | | PrincipalName = "IGNOREME" |
| 3 | 347 | | }; |
| 0 | 348 | | } |
| | 349 | |
|
| 0 | 350 | | if (computerDomainSid == null) |
| 0 | 351 | | return null; |
| | 352 | | //We shouldn't hit this provided our isDC logic is correct since we're skipping non-builtin groups |
| 0 | 353 | | return new NamedPrincipal |
| 0 | 354 | | { |
| 0 | 355 | | ObjectId = $"{computerDomainSid}-{groupRid}".ToUpper(), |
| 0 | 356 | | PrincipalName = "IGNOREME" |
| 0 | 357 | | }; |
| | 358 | | } |
| | 359 | |
|
| 4 | 360 | | if (computerDomainSid == null) |
| 0 | 361 | | return null; |
| | 362 | | //Take the local machineSid, append the groupRid, and make a name from the group name + computername |
| 4 | 363 | | return new NamedPrincipal |
| 4 | 364 | | { |
| 4 | 365 | | ObjectId = $"{computerDomainSid}-{groupRid}", |
| 4 | 366 | | PrincipalName = $"{baseName}@{computerName}".ToUpper() |
| 4 | 367 | | }; |
| 7 | 368 | | } |
| | 369 | |
|
| | 370 | | private async Task SendComputerStatus(CSVComputerStatus status) |
| 6 | 371 | | { |
| 7 | 372 | | if (ComputerStatusEvent is not null) await ComputerStatusEvent(status); |
| 6 | 373 | | } |
| | 374 | | } |
| | 375 | | } |