| | 1 | | using System; |
| | 2 | | using System.Collections.Concurrent; |
| | 3 | | using System.Collections.Generic; |
| | 4 | | using System.DirectoryServices.Protocols; |
| | 5 | | using System.IO; |
| | 6 | | using System.Linq; |
| | 7 | | using System.Text.RegularExpressions; |
| | 8 | | using System.Threading.Tasks; |
| | 9 | | using System.Xml.XPath; |
| | 10 | | using Microsoft.Extensions.Logging; |
| | 11 | | using SharpHoundCommonLib.Enums; |
| | 12 | | using SharpHoundCommonLib.LDAPQueries; |
| | 13 | | using SharpHoundCommonLib.OutputTypes; |
| | 14 | |
|
| | 15 | | namespace SharpHoundCommonLib.Processors { |
| | 16 | | public class GPOLocalGroupProcessor { |
| 1 | 17 | | private static readonly Regex KeyRegex = new(@"(.+?)\s*=(.*)", RegexOptions.Compiled); |
| | 18 | |
|
| 1 | 19 | | private static readonly Regex MemberRegex = |
| 1 | 20 | | new(@"\[Group Membership\](.*)(?:\[|$)", RegexOptions.Compiled | RegexOptions.Singleline); |
| | 21 | |
|
| 1 | 22 | | private static readonly Regex MemberLeftRegex = |
| 1 | 23 | | new(@"(.*(?:S-1-5-32-544|S-1-5-32-555|S-1-5-32-562|S-1-5-32-580)__Members)", RegexOptions.Compiled | |
| 1 | 24 | | RegexOptions.IgnoreCase); |
| | 25 | |
|
| 1 | 26 | | private static readonly Regex MemberRightRegex = |
| 1 | 27 | | new(@"(S-1-5-32-544|S-1-5-32-555|S-1-5-32-562|S-1-5-32-580)", RegexOptions.Compiled | |
| 1 | 28 | | RegexOptions.IgnoreCase); |
| | 29 | |
|
| 1 | 30 | | private static readonly Regex ExtractRid = |
| 1 | 31 | | new(@"S-1-5-32-([0-9]{3})", RegexOptions.Compiled | RegexOptions.IgnoreCase); |
| | 32 | |
|
| 1 | 33 | | private static readonly ConcurrentDictionary<string, List<GroupAction>> GpoActionCache = new(); |
| | 34 | |
|
| 1 | 35 | | private static readonly Dictionary<string, LocalGroupRids> ValidGroupNames = |
| 1 | 36 | | new(StringComparer.OrdinalIgnoreCase) { |
| 1 | 37 | | { "Administrators", LocalGroupRids.Administrators }, |
| 1 | 38 | | { "Remote Desktop Users", LocalGroupRids.RemoteDesktopUsers }, |
| 1 | 39 | | { "Remote Management Users", LocalGroupRids.PSRemote }, |
| 1 | 40 | | { "Distributed COM Users", LocalGroupRids.DcomUsers } |
| 1 | 41 | | }; |
| | 42 | |
|
| | 43 | | private readonly ILogger _log; |
| | 44 | |
|
| | 45 | | private readonly ILdapUtils _utils; |
| | 46 | |
|
| 22 | 47 | | public GPOLocalGroupProcessor(ILdapUtils utils, ILogger log = null) { |
| 11 | 48 | | _utils = utils; |
| 11 | 49 | | _log = log ?? Logging.LogProvider.CreateLogger("GPOLocalGroupProc"); |
| 11 | 50 | | } |
| | 51 | |
|
| 0 | 52 | | public Task<ResultingGPOChanges> ReadGPOLocalGroups(IDirectoryObject entry) { |
| 0 | 53 | | if (entry.TryGetProperty(LDAPProperties.GPLink, out var links) && entry.TryGetDistinguishedName(out var dn)) |
| 0 | 54 | | return ReadGPOLocalGroups(links, dn); |
| | 55 | | } |
| | 56 | |
|
| 0 | 57 | | return Task.FromResult(new ResultingGPOChanges()); |
| 0 | 58 | | } |
| | 59 | |
|
| 4 | 60 | | public async Task<ResultingGPOChanges> ReadGPOLocalGroups(string gpLink, string distinguishedName) { |
| 4 | 61 | | var ret = new ResultingGPOChanges(); |
| | 62 | | //If the gplink property is null, we don't need to process anything |
| 4 | 63 | | if (gpLink == null) |
| 1 | 64 | | return ret; |
| | 65 | |
|
| | 66 | | string domain; |
| | 67 | | //If our dn is null, use our default domain |
| 5 | 68 | | if (string.IsNullOrEmpty(distinguishedName)) { |
| 3 | 69 | | if (!_utils.GetDomain(out var d)) { |
| 1 | 70 | | return ret; |
| | 71 | | } |
| | 72 | |
|
| 1 | 73 | | domain = d.Name; |
| 2 | 74 | | } else { |
| 1 | 75 | | domain = Helpers.DistinguishedNameToDomain(distinguishedName); |
| 1 | 76 | | } |
| | 77 | |
|
| | 78 | | // First lets check if this OU actually has computers that it contains. If not, then we'll ignore it. |
| | 79 | | // Its cheaper to fetch the affected computers from LDAP first and then process the GPLinks |
| 2 | 80 | | var affectedComputers = new List<TypedPrincipal>(); |
| 10 | 81 | | await foreach (var result in _utils.Query(new LdapQueryParameters() { |
| 2 | 82 | | LDAPFilter = new LdapFilter().AddComputersNoMSAs().GetFilter(), |
| 2 | 83 | | Attributes = CommonProperties.ObjectSID, |
| 2 | 84 | | SearchBase = distinguishedName, |
| 2 | 85 | | DomainName = domain |
| 4 | 86 | | })) { |
| 2 | 87 | | if (!result.IsSuccess) { |
| 0 | 88 | | break; |
| | 89 | | } |
| | 90 | |
|
| 2 | 91 | | var entry = result.Value; |
| 2 | 92 | | if (!entry.TryGetSecurityIdentifier(out var sid)) { |
| 0 | 93 | | continue; |
| | 94 | | } |
| | 95 | |
|
| 2 | 96 | | affectedComputers.Add(new TypedPrincipal(sid, Label.Computer)); |
| 2 | 97 | | } |
| | 98 | |
|
| | 99 | | //If there's no computers then we don't care about this OU |
| 2 | 100 | | if (affectedComputers.Count == 0) |
| 0 | 101 | | return ret; |
| | 102 | |
|
| 2 | 103 | | var enforced = new List<string>(); |
| 2 | 104 | | var unenforced = new List<string>(); |
| | 105 | |
|
| | 106 | | // Split our link property up and remove disabled links |
| 14 | 107 | | foreach (var link in Helpers.SplitGPLinkProperty(gpLink)) |
| 4 | 108 | | switch (link.Status) { |
| | 109 | | case "0": |
| 2 | 110 | | unenforced.Add(link.DistinguishedName); |
| 2 | 111 | | break; |
| | 112 | | case "2": |
| 2 | 113 | | enforced.Add(link.DistinguishedName); |
| 2 | 114 | | break; |
| | 115 | | } |
| | 116 | |
|
| | 117 | | //Set up our links in the correct order. |
| | 118 | | //Enforced links override unenforced, and also respect the order in which they are placed in the GPLink prop |
| 2 | 119 | | var orderedLinks = new List<string>(); |
| 2 | 120 | | orderedLinks.AddRange(unenforced); |
| 2 | 121 | | orderedLinks.AddRange(enforced); |
| | 122 | |
|
| 2 | 123 | | var data = new Dictionary<LocalGroupRids, GroupResults>(); |
| 36 | 124 | | foreach (var rid in Enum.GetValues(typeof(LocalGroupRids))) data[(LocalGroupRids)rid] = new GroupResults(); |
| | 125 | |
|
| 18 | 126 | | foreach (var linkDn in orderedLinks) { |
| 8 | 127 | | if (!GpoActionCache.TryGetValue(linkDn.ToLower(), out var actions)) { |
| 4 | 128 | | actions = new List<GroupAction>(); |
| | 129 | |
|
| 4 | 130 | | var gpoDomain = Helpers.DistinguishedNameToDomain(linkDn); |
| 4 | 131 | | var result = await _utils.Query(new LdapQueryParameters() { |
| 4 | 132 | | LDAPFilter = new LdapFilter().AddAllObjects().GetFilter(), |
| 4 | 133 | | SearchScope = SearchScope.Base, |
| 4 | 134 | | Attributes = CommonProperties.GPCFileSysPath, |
| 4 | 135 | | SearchBase = linkDn, |
| 4 | 136 | | DomainName = gpoDomain |
| 4 | 137 | | }).DefaultIfEmpty(LdapResult<IDirectoryObject>.Fail()).FirstOrDefaultAsync(); |
| | 138 | |
|
| 7 | 139 | | if (!result.IsSuccess) { |
| 3 | 140 | | continue; |
| | 141 | | } |
| | 142 | |
|
| 1 | 143 | | if (!result.Value.TryGetProperty(LDAPProperties.GPCFileSYSPath, out var filePath)) { |
| 0 | 144 | | GpoActionCache.TryAdd(linkDn, actions); |
| 0 | 145 | | continue; |
| | 146 | | } |
| | 147 | |
|
| | 148 | | //Add the actions for each file. The GPO template file actions will override the XML file actions |
| 9 | 149 | | await foreach (var item in ProcessGPOXmlFile(filePath, gpoDomain)) actions.Add(item); |
| 3 | 150 | | await foreach (var item in ProcessGPOTemplateFile(filePath, gpoDomain)) actions.Add(item); |
| 1 | 151 | | } |
| | 152 | |
|
| | 153 | | //Cache the actions for this GPO for later |
| 1 | 154 | | GpoActionCache.TryAdd(linkDn.ToLower(), actions); |
| | 155 | |
|
| | 156 | | //If there are no actions, then we can move on from this GPO |
| 1 | 157 | | if (actions.Count == 0) |
| 0 | 158 | | continue; |
| | 159 | |
|
| | 160 | | //First lets process restricted members |
| 3 | 161 | | var restrictedMemberSets = actions.Where(x => x.Target == GroupActionTarget.RestrictedMember) |
| 1 | 162 | | .GroupBy(x => x.TargetRid); |
| | 163 | |
|
| 3 | 164 | | foreach (var set in restrictedMemberSets) { |
| 0 | 165 | | var results = data[set.Key]; |
| 0 | 166 | | var members = set.Select(x => x.ToTypedPrincipal()).ToList(); |
| 0 | 167 | | results.RestrictedMember = members; |
| 0 | 168 | | data[set.Key] = results; |
| 0 | 169 | | } |
| | 170 | |
|
| | 171 | | //Next add in our restricted MemberOf sets |
| 3 | 172 | | var restrictedMemberOfSets = actions.Where(x => x.Target == GroupActionTarget.RestrictedMemberOf) |
| 1 | 173 | | .GroupBy(x => x.TargetRid); |
| | 174 | |
|
| 3 | 175 | | foreach (var set in restrictedMemberOfSets) { |
| 0 | 176 | | var results = data[set.Key]; |
| 0 | 177 | | var members = set.Select(x => x.ToTypedPrincipal()).ToList(); |
| 0 | 178 | | results.RestrictedMemberOf = members; |
| 0 | 179 | | data[set.Key] = results; |
| 0 | 180 | | } |
| | 181 | |
|
| | 182 | | // Now work through the LocalGroup targets |
| 3 | 183 | | var localGroupSets = actions.Where(x => x.Target == GroupActionTarget.LocalGroup) |
| 3 | 184 | | .GroupBy(x => x.TargetRid); |
| | 185 | |
|
| 6 | 186 | | foreach (var set in localGroupSets) { |
| 1 | 187 | | var results = data[set.Key]; |
| 9 | 188 | | foreach (var temp in set) { |
| 2 | 189 | | var res = temp.ToTypedPrincipal(); |
| 2 | 190 | | var newMembers = results.LocalGroups; |
| 2 | 191 | | switch (temp.Action) { |
| | 192 | | case GroupActionOperation.Add: |
| 0 | 193 | | newMembers.Add(res); |
| 0 | 194 | | break; |
| | 195 | | case GroupActionOperation.Delete: |
| 0 | 196 | | newMembers.RemoveAll(x => x.ObjectIdentifier == res.ObjectIdentifier); |
| 0 | 197 | | break; |
| | 198 | | case GroupActionOperation.DeleteUsers: |
| 1 | 199 | | newMembers.RemoveAll(x => x.ObjectType == Label.User); |
| 1 | 200 | | break; |
| | 201 | | case GroupActionOperation.DeleteGroups: |
| 1 | 202 | | newMembers.RemoveAll(x => x.ObjectType == Label.Group); |
| 1 | 203 | | break; |
| | 204 | | } |
| | 205 | |
|
| 2 | 206 | | data[set.Key].LocalGroups = newMembers; |
| 2 | 207 | | } |
| 1 | 208 | | } |
| 1 | 209 | | } |
| | 210 | |
|
| 2 | 211 | | ret.AffectedComputers = affectedComputers.ToArray(); |
| | 212 | |
|
| | 213 | | //At this point, we've resolved individual add/substract methods for each linked GPO. |
| | 214 | | //Now we need to actually squish them together into the resulting set of changes |
| 36 | 215 | | foreach (var kvp in data) { |
| 10 | 216 | | var key = kvp.Key; |
| 10 | 217 | | var val = kvp.Value; |
| 10 | 218 | | var rm = val.RestrictedMember; |
| 10 | 219 | | var rmo = val.RestrictedMemberOf; |
| 10 | 220 | | var gm = val.LocalGroups; |
| | 221 | |
|
| 10 | 222 | | var final = new List<TypedPrincipal>(); |
| | 223 | |
|
| | 224 | | // If we're setting RestrictedMembers, it overrides LocalGroups due to order of operations. Restricted M |
| 10 | 225 | | final.AddRange(rmo); |
| 10 | 226 | | final.AddRange(rm.Count > 0 ? rm : gm); |
| | 227 | |
|
| 10 | 228 | | var finalArr = final.Distinct().ToArray(); |
| | 229 | |
|
| 10 | 230 | | switch (key) { |
| | 231 | | case LocalGroupRids.Administrators: |
| 2 | 232 | | ret.LocalAdmins = finalArr; |
| 2 | 233 | | break; |
| | 234 | | case LocalGroupRids.RemoteDesktopUsers: |
| 2 | 235 | | ret.RemoteDesktopUsers = finalArr; |
| 2 | 236 | | break; |
| | 237 | | case LocalGroupRids.DcomUsers: |
| 2 | 238 | | ret.DcomUsers = finalArr; |
| 2 | 239 | | break; |
| | 240 | | case LocalGroupRids.PSRemote: |
| 2 | 241 | | ret.PSRemoteUsers = finalArr; |
| 2 | 242 | | break; |
| | 243 | | } |
| 10 | 244 | | } |
| | 245 | |
|
| 2 | 246 | | return ret; |
| 4 | 247 | | } |
| | 248 | |
|
| | 249 | | /// <summary> |
| | 250 | | /// Parses a GPO GptTmpl.inf file and pulls group membership changes out |
| | 251 | | /// </summary> |
| | 252 | | /// <param name="basePath"></param> |
| | 253 | | /// <param name="gpoDomain"></param> |
| | 254 | | /// <returns></returns> |
| 5 | 255 | | internal async IAsyncEnumerable<GroupAction> ProcessGPOTemplateFile(string basePath, string gpoDomain) { |
| 5 | 256 | | var templatePath = Path.Combine(basePath, "MACHINE", "Microsoft", "Windows NT", "SecEdit", "GptTmpl.inf"); |
| | 257 | |
|
| 5 | 258 | | if (!File.Exists(templatePath)) |
| 1 | 259 | | yield break; |
| | 260 | |
|
| | 261 | | FileStream fs; |
| 4 | 262 | | try { |
| 4 | 263 | | fs = new FileStream(templatePath, FileMode.Open, FileAccess.Read); |
| 4 | 264 | | } |
| 0 | 265 | | catch { |
| 0 | 266 | | yield break; |
| | 267 | | } |
| | 268 | |
|
| 4 | 269 | | using var reader = new StreamReader(fs); |
| 4 | 270 | | var content = await reader.ReadToEndAsync(); |
| 4 | 271 | | var memberMatch = MemberRegex.Match(content); |
| | 272 | |
|
| 4 | 273 | | if (!memberMatch.Success) |
| 1 | 274 | | yield break; |
| | 275 | |
|
| | 276 | | //We've got a match! Lets figure out whats going on |
| 3 | 277 | | var memberText = memberMatch.Groups[1].Value.Trim(); |
| | 278 | | //Split our text into individual lines |
| 3 | 279 | | var memberLines = Regex.Split(memberText, @"\r\n|\r|\n"); |
| | 280 | |
|
| 36 | 281 | | foreach (var memberLine in memberLines) { |
| | 282 | | //Check if the Key regex matches (S-1-5.*_memberof=blah) |
| 9 | 283 | | var keyMatch = KeyRegex.Match(memberLine); |
| | 284 | |
|
| 9 | 285 | | if (!keyMatch.Success) |
| 0 | 286 | | continue; |
| | 287 | |
|
| 9 | 288 | | var key = keyMatch.Groups[1].Value.Trim(); |
| 9 | 289 | | var val = keyMatch.Groups[2].Value.Trim(); |
| | 290 | |
|
| 9 | 291 | | var leftMatch = MemberLeftRegex.Match(key); |
| 9 | 292 | | var rightMatches = MemberRightRegex.Matches(val); |
| | 293 | |
|
| | 294 | | //If leftmatch is a success, the members of a group are being explicitly set |
| 12 | 295 | | if (leftMatch.Success) { |
| 3 | 296 | | var extracted = ExtractRid.Match(leftMatch.Value); |
| 3 | 297 | | var rid = int.Parse(extracted.Groups[1].Value); |
| | 298 | |
|
| 3 | 299 | | if (Enum.IsDefined(typeof(LocalGroupRids), rid)) |
| | 300 | | //Loop over the members in the match, and try to convert them to SIDs |
| 18 | 301 | | foreach (var member in val.Split(',')) { |
| 4 | 302 | | if (await GetSid(member.Trim('*'), gpoDomain) is (true, var res)) { |
| 1 | 303 | | yield return new GroupAction { |
| 1 | 304 | | Target = GroupActionTarget.RestrictedMember, |
| 1 | 305 | | Action = GroupActionOperation.Add, |
| 1 | 306 | | TargetSid = res.ObjectIdentifier, |
| 1 | 307 | | TargetType = res.ObjectType, |
| 1 | 308 | | TargetRid = (LocalGroupRids)rid |
| 1 | 309 | | }; |
| 1 | 310 | | } |
| 3 | 311 | | } |
| 3 | 312 | | } |
| | 313 | |
|
| | 314 | | //If right match is a success, a group has been set as a member of one of our local groups |
| 9 | 315 | | var index = key.IndexOf("MemberOf", StringComparison.CurrentCultureIgnoreCase); |
| 12 | 316 | | if (rightMatches.Count > 0 && index > 0) { |
| 3 | 317 | | var account = key.Trim('*').Substring(0, index - 3).ToUpper(); |
| | 318 | |
|
| 4 | 319 | | if (await GetSid(account, gpoDomain) is (true, var res)) { |
| 6 | 320 | | foreach (var match in rightMatches) { |
| 1 | 321 | | var rid = int.Parse(ExtractRid.Match(match.ToString()).Groups[1].Value); |
| 1 | 322 | | if (!Enum.IsDefined(typeof(LocalGroupRids), rid)) continue; |
| | 323 | |
|
| 1 | 324 | | var targetGroup = (LocalGroupRids)rid; |
| 1 | 325 | | yield return new GroupAction { |
| 1 | 326 | | Target = GroupActionTarget.RestrictedMemberOf, |
| 1 | 327 | | Action = GroupActionOperation.Add, |
| 1 | 328 | | TargetRid = targetGroup, |
| 1 | 329 | | TargetSid = res.ObjectIdentifier, |
| 1 | 330 | | TargetType = res.ObjectType |
| 1 | 331 | | }; |
| 1 | 332 | | } |
| 1 | 333 | | } |
| 3 | 334 | | } |
| 9 | 335 | | } |
| 5 | 336 | | } |
| | 337 | |
|
| | 338 | | /// <summary> |
| | 339 | | /// Resolves a SID to its type |
| | 340 | | /// </summary> |
| | 341 | | /// <param name="account"></param> |
| | 342 | | /// <param name="domainName"></param> |
| | 343 | | /// <returns></returns> |
| 20 | 344 | | private async Task<(bool Success, TypedPrincipal Principal)> GetSid(string account, string domainName) { |
| 37 | 345 | | if (!account.StartsWith("S-1-", StringComparison.CurrentCulture)) { |
| | 346 | | string user; |
| | 347 | | string domain; |
| 29 | 348 | | if (account.Contains('\\')) { |
| | 349 | | //The account is in the format DOMAIN\\username |
| 12 | 350 | | var split = account.Split('\\'); |
| 12 | 351 | | domain = split[0]; |
| 12 | 352 | | user = split[1]; |
| 12 | 353 | | } |
| 5 | 354 | | else { |
| | 355 | | //The account is just a username, so try with the current domain |
| 5 | 356 | | domain = domainName; |
| 5 | 357 | | user = account; |
| 5 | 358 | | } |
| | 359 | |
|
| 17 | 360 | | user = user.ToUpper(); |
| | 361 | |
|
| | 362 | | //Try to resolve as a user object first |
| 17 | 363 | | var (success, res) = await _utils.ResolveAccountName(user, domain); |
| 17 | 364 | | if (success) |
| 8 | 365 | | return (true, res); |
| | 366 | |
|
| 9 | 367 | | return await _utils.ResolveAccountName($"{user}$", domain); |
| | 368 | | } |
| | 369 | |
|
| | 370 | | //The element is just a sid, so return it straight |
| 3 | 371 | | return await _utils.ResolveIDAndType(account, domainName); |
| 20 | 372 | | } |
| | 373 | |
|
| | 374 | | /// <summary> |
| | 375 | | /// Parses a GPO Groups.xml file and pulls group membership changes out |
| | 376 | | /// </summary> |
| | 377 | | /// <param name="basePath"></param> |
| | 378 | | /// <param name="gpoDomain"></param> |
| | 379 | | /// <returns>A list of GPO "Actions"</returns> |
| 4 | 380 | | internal async IAsyncEnumerable<GroupAction> ProcessGPOXmlFile(string basePath, string gpoDomain) { |
| 4 | 381 | | var xmlPath = Path.Combine(basePath, "MACHINE", "Preferences", "Groups", "Groups.xml"); |
| | 382 | |
|
| | 383 | | //If the file doesn't exist, then just return |
| 4 | 384 | | if (!File.Exists(xmlPath)) |
| 1 | 385 | | yield break; |
| | 386 | |
|
| | 387 | | //Create an XPathDocument to let us navigate the XML |
| | 388 | | XPathDocument doc; |
| 3 | 389 | | try { |
| 3 | 390 | | doc = new XPathDocument(xmlPath); |
| 3 | 391 | | } |
| 0 | 392 | | catch (Exception e) { |
| 0 | 393 | | _log.LogError(e, "error reading GPO XML file {File}", xmlPath); |
| 0 | 394 | | yield break; |
| | 395 | | } |
| | 396 | |
|
| 3 | 397 | | var navigator = doc.CreateNavigator(); |
| | 398 | | //Grab all the Groups nodes |
| 3 | 399 | | var groupsNodes = navigator.Select("/Groups"); |
| | 400 | |
|
| 9 | 401 | | while (groupsNodes.MoveNext()) { |
| 3 | 402 | | var current = groupsNodes.Current; |
| | 403 | | //If disable is set to 1, then this Group wont apply |
| 3 | 404 | | if (current.GetAttribute("disabled", "") is "1") |
| 1 | 405 | | continue; |
| | 406 | |
|
| 2 | 407 | | var groupNodes = current.Select("Group"); |
| 22 | 408 | | while (groupNodes.MoveNext()) { |
| | 409 | | //Grab the properties for each Group node. Current path is /Groups/Group |
| 10 | 410 | | var groupProperties = groupNodes.Current.Select("Properties"); |
| 30 | 411 | | while (groupProperties.MoveNext()) { |
| 10 | 412 | | var currentProperties = groupProperties.Current; |
| 10 | 413 | | var action = currentProperties.GetAttribute("action", ""); |
| | 414 | |
|
| | 415 | | //The only action that works for built in groups is Update. |
| 10 | 416 | | if (!action.Equals("u", StringComparison.OrdinalIgnoreCase)) |
| 2 | 417 | | continue; |
| | 418 | |
|
| 8 | 419 | | var groupSid = currentProperties.GetAttribute("groupSid", "")?.Trim(); |
| 8 | 420 | | var groupName = currentProperties.GetAttribute("groupName", "")?.Trim(); |
| | 421 | |
|
| | 422 | | //Next is to determine what group is being updated. |
| | 423 | |
|
| 8 | 424 | | var targetGroup = LocalGroupRids.None; |
| 12 | 425 | | if (!string.IsNullOrWhiteSpace(groupSid)) { |
| | 426 | | //Use a regex to match and attempt to extract the RID |
| 4 | 427 | | var s = ExtractRid.Match(groupSid); |
| 8 | 428 | | if (s.Success) { |
| 4 | 429 | | var rid = int.Parse(s.Groups[1].Value); |
| 4 | 430 | | if (Enum.IsDefined(typeof(LocalGroupRids), rid)) |
| 4 | 431 | | targetGroup = (LocalGroupRids)rid; |
| 4 | 432 | | } |
| 4 | 433 | | } |
| | 434 | |
|
| 8 | 435 | | if (!string.IsNullOrWhiteSpace(groupName) && targetGroup == LocalGroupRids.None) |
| 4 | 436 | | ValidGroupNames.TryGetValue(groupName, out targetGroup); |
| | 437 | |
|
| | 438 | | //If targetGroup is still None, we've failed to resolve a group target. No point in continuing |
| 8 | 439 | | if (targetGroup == LocalGroupRids.None) |
| 2 | 440 | | continue; |
| | 441 | |
|
| 6 | 442 | | var deleteUsers = currentProperties.GetAttribute("deleteAllUsers", "") == "1"; |
| 6 | 443 | | var deleteGroups = currentProperties.GetAttribute("deleteAllGroups", "") == "1"; |
| | 444 | |
|
| 6 | 445 | | if (deleteUsers) |
| 2 | 446 | | yield return new GroupAction { |
| 2 | 447 | | Action = GroupActionOperation.DeleteUsers, |
| 2 | 448 | | Target = GroupActionTarget.LocalGroup, |
| 2 | 449 | | TargetRid = targetGroup |
| 2 | 450 | | }; |
| | 451 | |
|
| 6 | 452 | | if (deleteGroups) |
| 2 | 453 | | yield return new GroupAction { |
| 2 | 454 | | Action = GroupActionOperation.DeleteGroups, |
| 2 | 455 | | Target = GroupActionTarget.LocalGroup, |
| 2 | 456 | | TargetRid = targetGroup |
| 2 | 457 | | }; |
| | 458 | |
|
| | 459 | | //Get all the actual members being added |
| 6 | 460 | | var members = currentProperties.Select("Members/Member"); |
| 34 | 461 | | while (members.MoveNext()) { |
| 14 | 462 | | var memberAction = members.Current.GetAttribute("action", "") |
| 14 | 463 | | .Equals("ADD", StringComparison.OrdinalIgnoreCase) |
| 14 | 464 | | ? GroupActionOperation.Add |
| 14 | 465 | | : GroupActionOperation.Delete; |
| | 466 | |
|
| 14 | 467 | | var memberName = members.Current.GetAttribute("name", ""); |
| 14 | 468 | | var memberSid = members.Current.GetAttribute("sid", ""); |
| | 469 | |
|
| 14 | 470 | | var ga = new GroupAction { |
| 14 | 471 | | Action = memberAction |
| 14 | 472 | | }; |
| | 473 | |
|
| | 474 | | //If we have a memberSid, this is the best case scenario |
| 24 | 475 | | if (!string.IsNullOrWhiteSpace(memberSid)) { |
| 10 | 476 | | if (await _utils.ResolveIDAndType(memberSid, gpoDomain) is (true, var res)) { |
| 0 | 477 | | ga.Target = GroupActionTarget.LocalGroup; |
| 0 | 478 | | ga.TargetSid = memberSid; |
| 0 | 479 | | ga.TargetType = res.ObjectType; |
| 0 | 480 | | ga.TargetRid = targetGroup; |
| | 481 | |
|
| 0 | 482 | | yield return ga; |
| 0 | 483 | | } |
| 10 | 484 | | } |
| | 485 | |
|
| | 486 | | //If we have a memberName, we need to resolve it to a SID/Type |
| 28 | 487 | | if (!string.IsNullOrWhiteSpace(memberName)) { |
| 21 | 488 | | if (await GetSid(memberName, gpoDomain) is (true, var res)) { |
| 7 | 489 | | ga.Target = GroupActionTarget.LocalGroup; |
| 7 | 490 | | ga.TargetSid = res.ObjectIdentifier; |
| 7 | 491 | | ga.TargetType = res.ObjectType; |
| 7 | 492 | | ga.TargetRid = targetGroup; |
| 7 | 493 | | yield return ga; |
| 7 | 494 | | } |
| 14 | 495 | | } |
| 14 | 496 | | } |
| 6 | 497 | | } |
| 10 | 498 | | } |
| 2 | 499 | | } |
| 4 | 500 | | } |
| | 501 | |
|
| | 502 | | /// <summary> |
| | 503 | | /// Represents an action from a GPO |
| | 504 | | /// </summary> |
| | 505 | | internal class GroupAction { |
| 26 | 506 | | internal GroupActionOperation Action { get; set; } |
| 23 | 507 | | internal GroupActionTarget Target { get; set; } |
| 16 | 508 | | internal string TargetSid { get; set; } |
| 16 | 509 | | internal Label TargetType { get; set; } |
| 19 | 510 | | internal LocalGroupRids TargetRid { get; set; } |
| | 511 | |
|
| 3 | 512 | | public TypedPrincipal ToTypedPrincipal() { |
| 3 | 513 | | return new TypedPrincipal { |
| 3 | 514 | | ObjectIdentifier = TargetSid, |
| 3 | 515 | | ObjectType = TargetType |
| 3 | 516 | | }; |
| 3 | 517 | | } |
| | 518 | |
|
| 1 | 519 | | protected bool Equals(GroupAction other) { |
| 1 | 520 | | return Action == other.Action && Target == other.Target && TargetSid == other.TargetSid && TargetType == |
| 1 | 521 | | } |
| | 522 | |
|
| 1 | 523 | | public override bool Equals(object obj) { |
| 1 | 524 | | if (ReferenceEquals(null, obj)) return false; |
| 1 | 525 | | if (ReferenceEquals(this, obj)) return true; |
| 1 | 526 | | if (obj.GetType() != this.GetType()) return false; |
| 1 | 527 | | return Equals((GroupAction)obj); |
| 1 | 528 | | } |
| | 529 | |
|
| 0 | 530 | | public override int GetHashCode() { |
| 0 | 531 | | unchecked { |
| 0 | 532 | | var hashCode = (int)Action; |
| 0 | 533 | | hashCode = (hashCode * 397) ^ (int)Target; |
| 0 | 534 | | hashCode = (hashCode * 397) ^ (TargetSid != null ? TargetSid.GetHashCode() : 0); |
| 0 | 535 | | hashCode = (hashCode * 397) ^ (int)TargetType; |
| 0 | 536 | | hashCode = (hashCode * 397) ^ (int)TargetRid; |
| 0 | 537 | | return hashCode; |
| | 538 | | } |
| 0 | 539 | | } |
| | 540 | |
|
| 1 | 541 | | public override string ToString() { |
| 1 | 542 | | return |
| 1 | 543 | | $"{nameof(Action)}: {Action}, {nameof(Target)}: {Target}, {nameof(TargetSid)}: {TargetSid}, {nameof( |
| 1 | 544 | | } |
| | 545 | | } |
| | 546 | |
|
| | 547 | | /// <summary> |
| | 548 | | /// Storage for each different group type |
| | 549 | | /// </summary> |
| | 550 | | public class GroupResults { |
| 10 | 551 | | public List<TypedPrincipal> LocalGroups = new(); |
| 10 | 552 | | public List<TypedPrincipal> RestrictedMember = new(); |
| 10 | 553 | | public List<TypedPrincipal> RestrictedMemberOf = new(); |
| | 554 | | } |
| | 555 | |
|
| | 556 | | internal enum GroupActionOperation { |
| | 557 | | Add, |
| | 558 | | Delete, |
| | 559 | | DeleteUsers, |
| | 560 | | DeleteGroups |
| | 561 | | } |
| | 562 | |
|
| | 563 | | internal enum GroupActionTarget { |
| | 564 | | RestrictedMemberOf, |
| | 565 | | RestrictedMember, |
| | 566 | | LocalGroup |
| | 567 | | } |
| | 568 | |
|
| | 569 | | internal enum LocalGroupRids { |
| | 570 | | None = 0, |
| | 571 | | Administrators = 544, |
| | 572 | | RemoteDesktopUsers = 555, |
| | 573 | | DcomUsers = 562, |
| | 574 | | PSRemote = 580 |
| | 575 | | } |
| | 576 | | } |
| | 577 | | } |