예제 #1
0
        public static PrincipalContextEx Get_PrincipalContext(Args_Get_PrincipalContext args = null)
        {
            if (args == null)
            {
                args = new Args_Get_PrincipalContext();
            }

            try
            {
                var ConnectTarget  = string.Empty;
                var ObjectIdentity = string.Empty;
                System.DirectoryServices.AccountManagement.PrincipalContext Context = null;
                if (!string.IsNullOrEmpty(args.Domain) || args.Identity.IsRegexMatch(@".+\\.+"))
                {
                    if (args.Identity.IsRegexMatch(@".+\\.+"))
                    {
                        // DOMAIN\groupname
                        var ConvertedIdentity = ConvertADName.Convert_ADName(new Args_Convert_ADName {
                            Identity = new[] { args.Identity }
                        }).FirstOrDefault();
                        if (ConvertedIdentity != null)
                        {
                            ConnectTarget  = ConvertedIdentity.Substring(0, ConvertedIdentity.IndexOf('/'));
                            ObjectIdentity = args.Identity.Split('\\')[1];
                            Logger.Write_Verbose($@"[Get-PrincipalContext] Binding to domain '{ConnectTarget}'");
                        }
                    }
                    else
                    {
                        ObjectIdentity = args.Identity;
                        Logger.Write_Verbose($@"[Get-PrincipalContext] Binding to domain '{args.Domain}'");
                        ConnectTarget = args.Domain;
                    }

                    if (args.Credential != null)
                    {
                        Logger.Write_Verbose($@"[Get-PrincipalContext] Using alternate credentials");
                        Context = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, ConnectTarget, args.Credential.UserName, args.Credential.Password);
                    }
                    else
                    {
                        Context = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, ConnectTarget);
                    }
                }
                else
                {
                    if (args.Credential != null)
                    {
                        Logger.Write_Verbose($@"[Get-PrincipalContext] Using alternate credentials");
                        var DomainName = GetDomain.Get_Domain().Name;
                        Context = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, DomainName, args.Credential.UserName, args.Credential.Password);
                    }
                    else
                    {
                        Context = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain);
                    }
                    ObjectIdentity = args.Identity;
                }

                return(new PrincipalContextEx
                {
                    Context = Context,
                    Identity = ObjectIdentity
                });
            }
            catch (Exception e)
            {
                Logger.Write_Warning($@"[Get-PrincipalContext] Error creating binding for object ('{args.Identity}') context : {e}");
            }

            return(null);
        }
예제 #2
0
        public static IEnumerable <object> Get_DomainGroup(Args_Get_DomainGroup args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainGroup();
            }

            var SearcherArguments = new Args_Get_DomainSearcher
            {
                Domain          = args.Domain,
                Properties      = args.Properties,
                SearchBase      = args.SearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                SecurityMasks   = args.SecurityMasks,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            var ObjectArguments = new Args_Get_DomainObject
            {
                Domain          = args.Domain,
                Properties      = args.Properties,
                SearchBase      = args.SearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                SecurityMasks   = args.SecurityMasks,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            var GroupSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
            var Groups        = new List <object>();

            if (GroupSearcher != null)
            {
                if (args.MemberIdentity != null)
                {
                    string[] OldProperties = null;
                    if (args.Properties != null)
                    {
                        OldProperties = SearcherArguments.Properties;
                    }

                    ObjectArguments.Identity = args.MemberIdentity;
                    ObjectArguments.Raw      = true;

                    var Objects = GetDomainObject.Get_DomainObject(ObjectArguments);
                    if (Objects != null)
                    {
                    }
                    foreach (SearchResult obj in Objects)
                    {
                        // convert the user/group to a directory entry
                        var ObjectDirectoryEntry = obj.GetDirectoryEntry();

                        // cause the cache to calculate the token groups for the user/group
                        ObjectDirectoryEntry.RefreshCache(new string[] { @"tokenGroups" });
                        foreach (byte[] tokenGroup in ObjectDirectoryEntry.Properties[@"tokenGroups"])
                        {
                            // convert the token group sid
                            var GroupSid = new System.Security.Principal.SecurityIdentifier(tokenGroup, 0).Value;

                            // ignore the built in groups
                            if (new Regex(@"^S-1-5-32-.*").Match(GroupSid).Success == false)
                            {
                                ObjectArguments.Identity = new string[] { GroupSid };
                                ObjectArguments.Raw      = false;
                                if (OldProperties != null)
                                {
                                    ObjectArguments.Properties = OldProperties;
                                }
                                var Group = GetDomainObject.Get_DomainObject(ObjectArguments);
                                if (Group != null)
                                {
                                    Groups.AddRange(Group);
                                }
                            }
                        }
                    }
                }
                else
                {
                    var IdentityFilter = "";
                    var Filter         = "";
                    if (args.Identity != null)
                    {
                        foreach (var samName in args.Identity)
                        {
                            var IdentityInstance = samName.Replace(@"(", @"\28").Replace(@")", @"\29");
                            if (new Regex(@"^S-1-").Match(IdentityInstance).Success)
                            {
                                IdentityFilter += $@"(objectsid={IdentityInstance})";
                            }
                            else if (new Regex(@"^CN=").Match(IdentityInstance).Success)
                            {
                                IdentityFilter += $@"(distinguishedname={IdentityInstance})";
                                if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty())
                                {
                                    // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname
                                    // and rebuild the domain searcher
                                    var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @".");
                                    Logger.Write_Verbose($@"[Get-DomainGroup] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'");
                                    SearcherArguments.Domain = IdentityDomain;
                                    GroupSearcher            = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                                    if (GroupSearcher == null)
                                    {
                                        Logger.Write_Warning($@"[Get-DomainGroup] Unable to retrieve domain searcher for '{IdentityDomain}'");
                                    }
                                }
                            }
                            else if (new Regex(@"^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$").Match(IdentityInstance).Success)
                            {
                                var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2")));
                                IdentityFilter += $@"(objectguid={GuidByteString})";
                            }
                            else if (IdentityInstance.Contains(@"\"))
                            {
                                var ConvertedIdentityInstance = ConvertADName.Convert_ADName(new Args_Convert_ADName
                                {
                                    OutputType = ADSNameType.Canonical,
                                    Identity   = new string[] { IdentityInstance.Replace(@"\28", @"(").Replace(@"\29", @")") }
                                });
                                if (ConvertedIdentityInstance != null && ConvertedIdentityInstance.Any())
                                {
                                    var GroupDomain = ConvertedIdentityInstance.First().Substring(0, ConvertedIdentityInstance.First().IndexOf('/'));
                                    var GroupName   = IdentityInstance.Split(new char[] { '\\' })[1];
                                    IdentityFilter          += $@"(samAccountName={GroupName})";
                                    SearcherArguments.Domain = GroupDomain;
                                    Logger.Write_Verbose($@"[Get-DomainUser] Extracted domain '{GroupDomain}' from '{IdentityInstance}'");
                                    GroupSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                                }
                            }
                            else
                            {
                                IdentityFilter += $@"(|(samAccountName={IdentityInstance})(name={IdentityInstance}))";
                            }
                        }
                    }

                    if (IdentityFilter != null && IdentityFilter.Trim() != "")
                    {
                        Filter += $@"(|{IdentityFilter})";
                    }

                    if (args.AdminCount)
                    {
                        Logger.Write_Verbose(@"[Get-DomainGroup] Searching for adminCount=1");
                        Filter += "(admincount=1)";
                    }
                    if (args.GroupScope != null)
                    {
                        switch (args.GroupScope.Value)
                        {
                        case GroupScope.DomainLocal:
                            Filter = "(groupType:1.2.840.113556.1.4.803:=4)";
                            break;

                        case GroupScope.NotDomainLocal:
                            Filter = "(!(groupType:1.2.840.113556.1.4.803:=4))";
                            break;

                        case GroupScope.Global:
                            Filter = "(groupType:1.2.840.113556.1.4.803:=2)";
                            break;

                        case GroupScope.NotGlobal:
                            Filter = "(!(groupType:1.2.840.113556.1.4.803:=2))";
                            break;

                        case GroupScope.Universal:
                            Filter = "(groupType:1.2.840.113556.1.4.803:=8)";
                            break;

                        case GroupScope.NotUniversal:
                            Filter = "(!(groupType:1.2.840.113556.1.4.803:=8))";
                            break;

                        default:
                            break;
                        }
                        Logger.Write_Verbose($@"[Get-DomainGroup] Searching for group scope '{args.GroupScope.Value.ToString()}'");
                    }
                    if (args.GroupProperty != null)
                    {
                        switch (args.GroupProperty.Value)
                        {
                        case GroupProperty.Security:
                            Filter = "(groupType:1.2.840.113556.1.4.803:=2147483648)";
                            break;

                        case GroupProperty.Distribution:
                            Filter = "(!(groupType:1.2.840.113556.1.4.803:=2147483648))";
                            break;

                        case GroupProperty.CreatedBySystem:
                            Filter = "(groupType:1.2.840.113556.1.4.803:=1)";
                            break;

                        case GroupProperty.NotCreatedBySystem:
                            Filter = "(!(groupType:1.2.840.113556.1.4.803:=1))";
                            break;

                        default:
                            break;
                        }
                        Logger.Write_Verbose($@"[Get-DomainGroup] Searching for group property '{args.GroupProperty.Value.ToString()}'");
                    }
                    if (args.LDAPFilter.IsNotNullOrEmpty())
                    {
                        Logger.Write_Verbose($@"[Get-DomainGroup] Using additional LDAP filter: {args.LDAPFilter}");
                        Filter += $@"{args.LDAPFilter}";
                    }

                    GroupSearcher.Filter = $@"(&(objectCategory=group){Filter})";
                    Logger.Write_Verbose($@"[Get-DomainGroup] filter string: {GroupSearcher.Filter}");

                    if (args.FindOne)
                    {
                        var result = GroupSearcher.FindOne();
                        if (args.Raw)
                        {
                            // return raw result objects
                            Groups.Add(result);
                        }
                        else
                        {
                            Groups.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties));
                        }
                    }
                    else
                    {
                        var Results = GroupSearcher.FindAll();
                        foreach (SearchResult result in Results)
                        {
                            if (args.Raw)
                            {
                                // return raw result objects
                                Groups.Add(result);
                            }
                            else
                            {
                                Groups.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties));
                            }
                        }
                        if (Results != null)
                        {
                            try { Results.Dispose(); }
                            catch (Exception e)
                            {
                                Logger.Write_Verbose($@"[Get-DomainGroup] Error disposing of the Results object: {e}");
                            }
                        }
                    }
                    GroupSearcher.Dispose();
                }
            }
            return(Groups);
        }
예제 #3
0
        public static IEnumerable <object> Get_DomainObject(Args_Get_DomainObject args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainObject();
            }

            var SearcherArguments = new Args_Get_DomainSearcher
            {
                Domain          = args.Domain,
                Properties      = args.Properties,
                SearchBase      = args.SearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                SecurityMasks   = args.SecurityMasks,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            var ObjectSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
            var Objects        = new List <object>();

            if (ObjectSearcher != null)
            {
                var IdentityFilter = "";
                var Filter         = "";
                if (args.Identity != null)
                {
                    foreach (var samName in args.Identity)
                    {
                        var IdentityInstance = samName.Replace(@"(", @"\28").Replace(@")", @"\29");
                        if (new Regex(@"^S-1-").Match(IdentityInstance).Success)
                        {
                            IdentityFilter += $@"(objectsid={IdentityInstance})";
                        }
                        else if (new Regex(@"^(CN|OU|DC)=").Match(IdentityInstance).Success)
                        {
                            IdentityFilter += $@"(distinguishedname={IdentityInstance})";
                            if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty())
                            {
                                // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname
                                // and rebuild the domain searcher
                                var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @".");
                                Logger.Write_Verbose($@"[Get-DomainObject] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'");
                                SearcherArguments.Domain = IdentityDomain;
                                ObjectSearcher           = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                                if (ObjectSearcher == null)
                                {
                                    Logger.Write_Warning($@"[Get-DomainObject] Unable to retrieve domain searcher for '{IdentityDomain}'");
                                }
                            }
                        }
                        else if (new Regex(@"^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$").Match(IdentityInstance).Success)
                        {
                            var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2")));
                            IdentityFilter += $@"(objectguid={GuidByteString})";
                        }
                        else if (IdentityInstance.Contains(@"\"))
                        {
                            var ConvertedIdentityInstance = ConvertADName.Convert_ADName(new Args_Convert_ADName
                            {
                                OutputType = ADSNameType.Canonical,
                                Identity   = new string[] { IdentityInstance.Replace(@"\28", @"(").Replace(@"\29", @")") }
                            });
                            if (ConvertedIdentityInstance != null && ConvertedIdentityInstance.Any())
                            {
                                var ObjectDomain = ConvertedIdentityInstance.First().Substring(0, ConvertedIdentityInstance.First().IndexOf('/'));
                                var ObjectName   = IdentityInstance.Split(new char[] { '\\' })[1];
                                IdentityFilter          += $@"(samAccountName={ObjectName})";
                                SearcherArguments.Domain = ObjectDomain;
                                Logger.Write_Verbose($@"[Get-DomainObject] Extracted domain '{ObjectDomain}' from '{IdentityInstance}'");
                                ObjectSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                            }
                        }
                        else if (IdentityInstance.Contains(@"."))
                        {
                            IdentityFilter += $@"(|(samAccountName={IdentityInstance})(name={IdentityInstance})(dnshostname={IdentityInstance}))";
                        }
                        else
                        {
                            IdentityFilter += $@"(|(samAccountName={IdentityInstance})(name={IdentityInstance})(displayname={IdentityInstance}))";
                        }
                    }
                }
                if (IdentityFilter != null && IdentityFilter.Trim() != "")
                {
                    Filter += $@"(|{IdentityFilter})";
                }
                if (args.LDAPFilter.IsNotNullOrEmpty())
                {
                    Logger.Write_Verbose($@"[Get-DomainObject] Using additional LDAP filter: {args.LDAPFilter}");
                    Filter += $@"{args.LDAPFilter}";
                }
                // build the LDAP filter for the dynamic UAC filter value
                var uacs = args.UACFilter.ExtractValues();
                foreach (var uac in uacs)
                {
                    if (uac.IsNot())
                    {
                        Filter += $@"(!(userAccountControl:1.2.840.113556.1.4.803:={uac.GetValueAsInteger()}))";
                    }
                    else
                    {
                        Filter += $@"(userAccountControl:1.2.840.113556.1.4.803:={uac.GetValueAsInteger()})";
                    }
                }
                if (Filter != null && Filter != "")
                {
                    ObjectSearcher.Filter = $@"(&{Filter})";
                }
                Logger.Write_Verbose($@"[Get-DomainObject] Get-DomainComputer filter string: {ObjectSearcher.Filter}");

                if (args.FindOne)
                {
                    var result = ObjectSearcher.FindOne();
                    if (args.Raw)
                    {
                        // return raw result objects
                        Objects.Add(result);
                    }
                    else
                    {
                        Objects.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties));
                    }
                }
                else
                {
                    var Results = ObjectSearcher.FindAll();
                    foreach (SearchResult result in Results)
                    {
                        if (args.Raw)
                        {
                            // return raw result objects
                            Objects.Add(result);
                        }
                        else
                        {
                            Objects.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties));
                        }
                    }
                    if (Results != null)
                    {
                        try { Results.Dispose(); }
                        catch (Exception e)
                        {
                            Logger.Write_Verbose($@"[Get-DomainObject] Error disposing of the Results object: {e}");
                        }
                    }
                }
                ObjectSearcher.Dispose();
            }
            return(Objects);
        }
예제 #4
0
        public static IEnumerable <string> ConvertFrom_SID(Args_ConvertFrom_SID args = null)
        {
            if (args == null)
            {
                args = new Args_ConvertFrom_SID();
            }

            var ADNameArguments = new Args_Convert_ADName
            {
                Domain     = args.Domain,
                Server     = args.Server,
                Credential = args.Credential
            };

            var Results = new List <string>();

            foreach (var TargetSid in args.ObjectSID)
            {
                var trimedTargetSid = TargetSid.Trim('*');
                try
                {
                    // try to resolve any built-in SIDs first - https://support.microsoft.com/en-us/kb/243330

                    if (trimedTargetSid == @"S-1-0")
                    {
                        Results.Add(@"Null Authority");
                    }
                    else if (trimedTargetSid == @"S -1-0-0")
                    {
                        Results.Add(@"Nobody");
                    }
                    else if (trimedTargetSid == @"S-1-1")
                    {
                        Results.Add(@"World Authority");
                    }
                    else if (trimedTargetSid == @"S-1-1-0")
                    {
                        Results.Add(@"Everyone");
                    }
                    else if (trimedTargetSid == @"S-1-2")
                    {
                        Results.Add(@"Local Authority");
                    }
                    else if (trimedTargetSid == @"S-1-2-0")
                    {
                        Results.Add(@"Local");
                    }
                    else if (trimedTargetSid == @"S-1-2-1")
                    {
                        Results.Add(@"Console Logon ");
                    }
                    else if (trimedTargetSid == @"S-1-3")
                    {
                        Results.Add(@"Creator Authority");
                    }
                    else if (trimedTargetSid == @"S-1-3-0")
                    {
                        Results.Add(@"Creator Owner");
                    }
                    else if (trimedTargetSid == @"S-1-3-1")
                    {
                        Results.Add(@"Creator Group");
                    }
                    else if (trimedTargetSid == @"S-1-3-2")
                    {
                        Results.Add(@"Creator Owner Server");
                    }
                    else if (trimedTargetSid == @"S-1-3-3")
                    {
                        Results.Add(@"Creator Group Server");
                    }
                    else if (trimedTargetSid == @"S-1-3-4")
                    {
                        Results.Add(@"Owner Rights");
                    }
                    else if (trimedTargetSid == @"S-1-4")
                    {
                        Results.Add(@"Non-unique Authority");
                    }
                    else if (trimedTargetSid == @"S-1-5")
                    {
                        Results.Add(@"NT Authority");
                    }
                    else if (trimedTargetSid == @"S-1-5-1")
                    {
                        Results.Add(@"Dialup");
                    }
                    else if (trimedTargetSid == @"S-1-5-2")
                    {
                        Results.Add(@"Network");
                    }
                    else if (trimedTargetSid == @"S-1-5-3")
                    {
                        Results.Add(@"Batch");
                    }
                    else if (trimedTargetSid == @"S-1-5-4")
                    {
                        Results.Add(@"Interactive");
                    }
                    else if (trimedTargetSid == @"S-1-5-6")
                    {
                        Results.Add(@"Service");
                    }
                    else if (trimedTargetSid == @"S-1-5-7")
                    {
                        Results.Add(@"Anonymous");
                    }
                    else if (trimedTargetSid == @"S-1-5-8")
                    {
                        Results.Add(@"Proxy");
                    }
                    else if (trimedTargetSid == @"S-1-5-9")
                    {
                        Results.Add(@"Enterprise Domain Controllers");
                    }
                    else if (trimedTargetSid == @"S-1-5-10")
                    {
                        Results.Add(@"Principal Self");
                    }
                    else if (trimedTargetSid == @"S-1-5-11")
                    {
                        Results.Add(@"Authenticated Users");
                    }
                    else if (trimedTargetSid == @"S-1-5-12")
                    {
                        Results.Add(@"Restricted Code");
                    }
                    else if (trimedTargetSid == @"S-1-5-13")
                    {
                        Results.Add(@"Terminal Server Users");
                    }
                    else if (trimedTargetSid == @"S-1-5-14")
                    {
                        Results.Add(@"Remote Interactive Logon");
                    }
                    else if (trimedTargetSid == @"S-1-5-15")
                    {
                        Results.Add(@"This Organization ");
                    }
                    else if (trimedTargetSid == @"S-1-5-17")
                    {
                        Results.Add(@"This Organization ");
                    }
                    else if (trimedTargetSid == @"S-1-5-18")
                    {
                        Results.Add(@"Local System");
                    }
                    else if (trimedTargetSid == @"S-1-5-19")
                    {
                        Results.Add(@"NT Authority");
                    }
                    else if (trimedTargetSid == @"S-1-5-20")
                    {
                        Results.Add(@"NT Authority");
                    }
                    else if (trimedTargetSid == @"S-1-5-80-0")
                    {
                        Results.Add(@"All Services ");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-544")
                    {
                        Results.Add(@"BUILTIN\Administrators");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-545")
                    {
                        Results.Add(@"BUILTIN\Users");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-546")
                    {
                        Results.Add(@"BUILTIN\Guests");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-547")
                    {
                        Results.Add(@"BUILTIN\Power Users");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-548")
                    {
                        Results.Add(@"BUILTIN\Account Operators");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-549")
                    {
                        Results.Add(@"BUILTIN\Server Operators");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-550")
                    {
                        Results.Add(@"BUILTIN\Print Operators");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-551")
                    {
                        Results.Add(@"BUILTIN\Backup Operators");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-552")
                    {
                        Results.Add(@"BUILTIN\Replicators");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-554")
                    {
                        Results.Add(@"BUILTIN\Pre-Windows 2000 Compatible Access");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-555")
                    {
                        Results.Add(@"BUILTIN\Remote Desktop Users");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-556")
                    {
                        Results.Add(@"BUILTIN\Network Configuration Operators");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-557")
                    {
                        Results.Add(@"BUILTIN\Incoming Forest Trust Builders");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-558")
                    {
                        Results.Add(@"BUILTIN\Performance Monitor Users");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-559")
                    {
                        Results.Add(@"BUILTIN\Performance Log Users");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-560")
                    {
                        Results.Add(@"BUILTIN\Windows Authorization Access Group");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-561")
                    {
                        Results.Add(@"BUILTIN\Terminal Server License Servers");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-562")
                    {
                        Results.Add(@"BUILTIN\Distributed COM Users");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-569")
                    {
                        Results.Add(@"BUILTIN\Cryptographic Operators");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-573")
                    {
                        Results.Add(@"BUILTIN\Event Log Readers");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-574")
                    {
                        Results.Add(@"BUILTIN\Certificate Service DCOM Access");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-575")
                    {
                        Results.Add(@"BUILTIN\RDS Remote Access Servers");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-576")
                    {
                        Results.Add(@"BUILTIN\RDS Endpoint Servers");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-577")
                    {
                        Results.Add(@"BUILTIN\RDS Management Servers");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-578")
                    {
                        Results.Add(@"BUILTIN\Hyper-V Administrators");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-579")
                    {
                        Results.Add(@"BUILTIN\Access Control Assistance Operators");
                    }
                    else if (trimedTargetSid == @"S-1-5-32-580")
                    {
                        Results.Add(@"BUILTIN\Access Control Assistance Operators");
                    }
                    else
                    {
                        ADNameArguments.Identity = new string[] { TargetSid };
                        Results.AddRange(ConvertADName.Convert_ADName(ADNameArguments));
                    }
                }
                catch (Exception e)
                {
                    Logger.Write_Verbose($@"[ConvertFrom-SID] Error converting SID '{TargetSid}' : {e}");
                }
            }
            return(Results);
        }
예제 #5
0
        public static IEnumerable <ACL> Find_InterestingDomainAcl(Args_Find_InterestingDomainAcl args = null)
        {
            if (args == null)
            {
                args = new Args_Find_InterestingDomainAcl();
            }

            var ACLArguments = new Args_Get_DomainObjectAcl
            {
                ResolveGUIDs    = args.ResolveGUIDs,
                RightsFilter    = args.RightsFilter,
                LDAPFilter      = args.LDAPFilter,
                SearchBase      = args.SearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            var ObjectSearcherArguments = new Args_Get_DomainObject
            {
                Properties      = new[] { "samaccountname", "objectclass" },
                Raw             = true,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            var ADNameArguments = new Args_Convert_ADName
            {
                Server     = args.Server,
                Credential = args.Credential
            };

            // ongoing list of built-up SIDs
            var ResolvedSIDs = new Dictionary <string, ResolvedSID>();

            if (args.Domain != null)
            {
                ACLArguments.Domain    = args.Domain;
                ADNameArguments.Domain = args.Domain;
            }

            var InterestingACLs = new List <ACL>();
            var acls            = GetDomainObjectAcl.Get_DomainObjectAcl(ACLArguments);

            foreach (var acl in acls)
            {
                if ((acl.ActiveDirectoryRights.ToString().IsRegexMatch(@"GenericAll|Write|Create|Delete")) || ((acl.ActiveDirectoryRights == ActiveDirectoryRights.ExtendedRight) && (acl.Ace is QualifiedAce) && (acl.Ace as QualifiedAce).AceQualifier == AceQualifier.AccessAllowed))
                {
                    // only process SIDs > 1000
                    var ace = acl.Ace as QualifiedAce;
                    if (ace != null && ace.SecurityIdentifier.Value.IsRegexMatch(@"^S-1-5-.*-[1-9]\d{3,}$"))
                    {
                        if (ResolvedSIDs.ContainsKey(ace.SecurityIdentifier.Value) && ResolvedSIDs[ace.SecurityIdentifier.Value] != null)
                        {
                            var ResolvedSID    = ResolvedSIDs[(acl.Ace as KnownAce).SecurityIdentifier.Value];
                            var InterestingACL = new ACL
                            {
                                ObjectDN = acl.ObjectDN,
                                Ace      = ace,
                                ActiveDirectoryRights   = acl.ActiveDirectoryRights,
                                IdentityReferenceName   = ResolvedSID.IdentityReferenceName,
                                IdentityReferenceDomain = ResolvedSID.IdentityReferenceDomain,
                                IdentityReferenceDN     = ResolvedSID.IdentityReferenceDN,
                                IdentityReferenceClass  = ResolvedSID.IdentityReferenceClass
                            };
                            InterestingACLs.Add(InterestingACL);
                        }
                        else
                        {
                            ADNameArguments.Identity   = new string[] { ace.SecurityIdentifier.Value };
                            ADNameArguments.OutputType = ADSNameType.DN;
                            var IdentityReferenceDN = ConvertADName.Convert_ADName(ADNameArguments)?.FirstOrDefault();
                            // "IdentityReferenceDN: $IdentityReferenceDN"

                            if (IdentityReferenceDN != null)
                            {
                                var IdentityReferenceDomain = IdentityReferenceDN.Substring(IdentityReferenceDN.IndexOf("DC=")).Replace(@"DC=", "").Replace(",", ".");
                                // "IdentityReferenceDomain: $IdentityReferenceDomain"
                                ObjectSearcherArguments.Domain   = IdentityReferenceDomain;
                                ObjectSearcherArguments.Identity = new[] { IdentityReferenceDN };
                                // "IdentityReferenceDN: $IdentityReferenceDN"
                                var Object = GetDomainObject.Get_DomainObject(ObjectSearcherArguments)?.FirstOrDefault() as SearchResult;

                                if (Object != null)
                                {
                                    var    IdentityReferenceName = Object.Properties["samaccountname"][0].ToString();
                                    string IdentityReferenceClass;
                                    if (Object.Properties["objectclass"][0].ToString().IsRegexMatch(@"computer"))
                                    {
                                        IdentityReferenceClass = "computer";
                                    }
                                    else if (Object.Properties["objectclass"][0].ToString().IsRegexMatch(@"group"))
                                    {
                                        IdentityReferenceClass = "group";
                                    }
                                    else if (Object.Properties["objectclass"][0].ToString().IsRegexMatch(@"user"))
                                    {
                                        IdentityReferenceClass = "user";
                                    }
                                    else
                                    {
                                        IdentityReferenceClass = null;
                                    }

                                    // save so we don't look up more than once
                                    ResolvedSIDs[ace.SecurityIdentifier.Value] = new ResolvedSID
                                    {
                                        IdentityReferenceName   = IdentityReferenceName,
                                        IdentityReferenceDomain = IdentityReferenceDomain,
                                        IdentityReferenceDN     = IdentityReferenceDN,
                                        IdentityReferenceClass  = IdentityReferenceClass
                                    };

                                    var InterestingACL = new ACL
                                    {
                                        ObjectDN = acl.ObjectDN,
                                        Ace      = ace,
                                        ActiveDirectoryRights   = acl.ActiveDirectoryRights,
                                        IdentityReferenceName   = IdentityReferenceName,
                                        IdentityReferenceDomain = IdentityReferenceDomain,
                                        IdentityReferenceDN     = IdentityReferenceDN,
                                        IdentityReferenceClass  = IdentityReferenceClass
                                    };
                                    InterestingACLs.Add(InterestingACL);
                                }
                            }
                            else
                            {
                                Logger.Write_Warning($@"[Find-InterestingDomainAcl] Unable to convert SID '{ace.SecurityIdentifier.Value}' to a distinguishedname with Convert-ADName");
                            }
                        }
                    }
                }
            }

            return(InterestingACLs);
        }
예제 #6
0
        public static IEnumerable <object> Get_DomainUser(Args_Get_DomainUser args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainUser();
            }

            var SearcherArguments = new Args_Get_DomainSearcher
            {
                Domain          = args.Domain,
                Properties      = args.Properties,
                SearchBase      = args.SearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                SecurityMasks   = args.SecurityMasks,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            var UserSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
            var Users        = new List <object>();

            if (UserSearcher != null)
            {
                var IdentityFilter = "";
                var Filter         = "";
                if (args.Identity != null)
                {
                    foreach (var samName in args.Identity)
                    {
                        var IdentityInstance = samName.Replace(@"(", @"\28").Replace(@")", @"\29");
                        if (new Regex(@"^S-1-").Match(IdentityInstance).Success)
                        {
                            IdentityFilter += $@"(objectsid={IdentityInstance})";
                        }
                        else if (new Regex(@"^CN=").Match(IdentityInstance).Success)
                        {
                            IdentityFilter += $@"(distinguishedname={IdentityInstance})";
                            if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty())
                            {
                                // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname
                                // and rebuild the domain searcher
                                var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @".");
                                Logger.Write_Verbose($@"[Get-DomainUser] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'");
                                SearcherArguments.Domain = IdentityDomain;
                                UserSearcher             = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                                if (UserSearcher == null)
                                {
                                    Logger.Write_Warning($@"[Get-DomainUser] Unable to retrieve domain searcher for '{IdentityDomain}'");
                                }
                            }
                        }
                        else if (new Regex(@"^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$").Match(IdentityInstance).Success)
                        {
                            var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2")));
                            IdentityFilter += $@"(objectguid={GuidByteString})";
                        }
                        else if (IdentityInstance.Contains(@"\"))
                        {
                            var ConvertedIdentityInstance = ConvertADName.Convert_ADName(new Args_Convert_ADName
                            {
                                OutputType = ADSNameType.Canonical,
                                Identity   = new string[] { IdentityInstance.Replace(@"\28", @"(").Replace(@"\29", @")") }
                            });
                            if (ConvertedIdentityInstance != null && ConvertedIdentityInstance.Any())
                            {
                                var UserDomain = ConvertedIdentityInstance.First().Substring(0, ConvertedIdentityInstance.First().IndexOf('/'));
                                var UserName   = IdentityInstance.Split(new char[] { '\\' })[1];
                                IdentityFilter          += $@"(samAccountName={UserName})";
                                SearcherArguments.Domain = UserDomain;
                                Logger.Write_Verbose($@"[Get-DomainUser] Extracted domain '{UserDomain}' from '{IdentityInstance}'");
                                UserSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                            }
                        }
                        else
                        {
                            IdentityFilter += $@"(samAccountName={IdentityInstance})";
                        }
                    }
                }

                if (IdentityFilter != null && IdentityFilter.Trim() != "")
                {
                    Filter += $@"(|{IdentityFilter})";
                }

                if (args.SPN)
                {
                    Logger.Write_Verbose(@"[Get-DomainUser] Searching for non-null service principal names");
                    Filter += "(servicePrincipalName=*)";
                }
                if (args.AllowDelegation)
                {
                    Logger.Write_Verbose(@"[Get-DomainUser] Searching for users who can be delegated");
                    // negation of "Accounts that are sensitive and not trusted for delegation"
                    Filter += "(!(userAccountControl:1.2.840.113556.1.4.803:=1048574))";
                }
                if (args.DisallowDelegation)
                {
                    Logger.Write_Verbose(@"[Get-DomainUser] Searching for users who are sensitive and not trusted for delegation");
                    Filter += "(userAccountControl:1.2.840.113556.1.4.803:=1048574)";
                }
                if (args.AdminCount)
                {
                    Logger.Write_Verbose(@"[Get-DomainUser] Searching for adminCount=1");
                    Filter += "(admincount=1)";
                }
                if (args.TrustedToAuth)
                {
                    Logger.Write_Verbose("[Get-DomainUser] Searching for users that are trusted to authenticate for other principals");
                    Filter += "(msds-allowedtodelegateto=*)";
                }
                if (args.PreauthNotRequired)
                {
                    Logger.Write_Verbose("[Get-DomainUser] Searching for user accounts that do not require kerberos preauthenticate");
                    Filter += "(userAccountControl:1.2.840.113556.1.4.803:=4194304)";
                }
                if (args.LDAPFilter.IsNotNullOrEmpty())
                {
                    Logger.Write_Verbose($@"[Get-DomainUser] Using additional LDAP filter: {args.LDAPFilter}");
                    Filter += $@"{args.LDAPFilter}";
                }

                // build the LDAP filter for the dynamic UAC filter value
                var uacs = args.UACFilter.ExtractValues();
                foreach (var uac in uacs)
                {
                    if (uac.IsNot())
                    {
                        Filter += $@"(!(userAccountControl:1.2.840.113556.1.4.803:={uac.GetValueAsInteger()}))";
                    }
                    else
                    {
                        Filter += $@"(userAccountControl:1.2.840.113556.1.4.803:={uac.GetValueAsInteger()})";
                    }
                }

                UserSearcher.Filter = $@"(&(samAccountType=805306368){Filter})";
                Logger.Write_Verbose($@"[Get-DomainUser] filter string: {UserSearcher.Filter}");

                if (args.FindOne)
                {
                    var result = UserSearcher.FindOne();
                    if (args.Raw)
                    {
                        // return raw result objects
                        Users.Add(result);
                    }
                    else
                    {
                        Users.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties));
                    }
                }
                else
                {
                    var Results = UserSearcher.FindAll();
                    foreach (SearchResult result in Results)
                    {
                        if (args.Raw)
                        {
                            // return raw result objects
                            Users.Add(result);
                        }
                        else
                        {
                            Users.Add(ConvertLDAPProperty.Convert_LDAPProperty(result.Properties));
                        }
                    }
                    if (Results != null)
                    {
                        try { Results.Dispose(); }
                        catch (Exception e)
                        {
                            Logger.Write_Verbose($@"[Get-DomainUser] Error disposing of the Results object: {e}");
                        }
                    }
                }
                UserSearcher.Dispose();
            }
            return(Users);
        }
예제 #7
0
        public static IEnumerable <GroupMember> Get_DomainGroupMember(Args_Get_DomainGroupMember args = null)
        {
            if (args == null)
            {
                args = new Args_Get_DomainGroupMember();
            }

            var SearcherArguments = new Args_Get_DomainSearcher()
            {
                Properties      = new string[] { @"member", @"samaccountname", @"distinguishedname" },
                Domain          = args.Domain,
                LDAPFilter      = args.LDAPFilter,
                SearchBase      = args.SearchBase,
                Server          = args.Server,
                SearchScope     = args.SearchScope,
                ResultPageSize  = args.ResultPageSize,
                ServerTimeLimit = args.ServerTimeLimit,
                Tombstone       = args.Tombstone,
                Credential      = args.Credential
            };

            var ADNameArguments = new Args_Convert_ADName
            {
                Domain     = args.Domain,
                Server     = args.Server,
                Credential = args.Credential
            };

            var GroupMembers  = new List <GroupMember>();
            var GroupSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);

            if (GroupSearcher != null)
            {
                string        GroupFoundDomain = null;
                string        GroupFoundName   = null;
                string        GroupFoundDN     = null;
                List <string> Members          = null;
                if (args.RecurseUsingMatchingRule)
                {
                    var GroupArguments = new Args_Get_DomainGroup()
                    {
                        Properties      = SearcherArguments.Properties,
                        Domain          = SearcherArguments.Domain,
                        LDAPFilter      = SearcherArguments.LDAPFilter,
                        SearchBase      = SearcherArguments.SearchBase,
                        Server          = SearcherArguments.Server,
                        SearchScope     = SearcherArguments.SearchScope,
                        ResultPageSize  = SearcherArguments.ResultPageSize,
                        ServerTimeLimit = SearcherArguments.ServerTimeLimit,
                        Tombstone       = SearcherArguments.Tombstone,
                        Credential      = SearcherArguments.Credential,
                        Identity        = args.Identity,
                        Raw             = true
                    };
                    var Groups = GetDomainGroup.Get_DomainGroup(GroupArguments);

                    if (Groups == null)
                    {
                        Logger.Write_Warning($@"[Get-DomainGroupMember] Error searching for group with identity: {args.Identity}");
                    }
                    else
                    {
                        var Group = Groups.First() as SearchResult;
                        GroupFoundName = Group.Properties[@"samaccountname"][0] as string;
                        GroupFoundDN   = Group.Properties[@"distinguishedname"][0] as string;
                        if (args.Domain.IsNotNullOrEmpty())
                        {
                            GroupFoundDomain = args.Domain;
                        }
                        else
                        {
                            // if a domain isn't passed, try to extract it from the found group distinguished name
                            if (GroupFoundDN.IsNotNullOrEmpty())
                            {
                                GroupFoundDomain = GroupFoundDN.Substring(GroupFoundDN.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @".");
                            }
                        }
                        Logger.Write_Verbose($@"[Get-DomainGroupMember] Using LDAP matching rule to recurse on '{GroupFoundDN}', only user accounts will be returned.");
                        GroupSearcher.Filter = $@"(&(samAccountType=805306368)(memberof:1.2.840.113556.1.4.1941:={GroupFoundDN}))";
                        GroupSearcher.PropertiesToLoad.AddRange(new string[] { @"distinguishedName" });
                        var Results = GroupSearcher.FindAll();
                        if (Results != null)
                        {
                            Members = new List <string>();
                            foreach (SearchResult result in Results)
                            {
                                Members.Add(result.Properties[@"distinguishedname"][0] as string);
                            }
                        }
                    }
                }
                else
                {
                    var IdentityFilter = @"";
                    var Filter         = @"";
                    if (args.Identity != null)
                    {
                        foreach (var item in args.Identity)
                        {
                            var IdentityInstance = item.Replace(@"(", @"\28").Replace(@")", @"\29");
                            if (new Regex(@"^S-1-").Match(IdentityInstance).Success)
                            {
                                IdentityFilter += $@"(objectsid={IdentityInstance})";
                            }
                            else if (new Regex(@"^CN=").Match(IdentityInstance).Success)
                            {
                                IdentityFilter += $@"(distinguishedname={IdentityInstance})";
                                if (args.Domain.IsNullOrEmpty() && args.SearchBase.IsNullOrEmpty())
                                {
                                    // if a -Domain isn't explicitly set, extract the object domain out of the distinguishedname
                                    //   and rebuild the domain searcher
                                    var IdentityDomain = IdentityInstance.Substring(IdentityInstance.IndexOf(@"DC=")).Replace(@"DC=", @"".Replace(@",", @"."));
                                    Logger.Write_Verbose($@"[Get-DomainGroupMember] Extracted domain '{IdentityDomain}' from '{IdentityInstance}'");
                                    SearcherArguments.Domain = IdentityDomain;
                                    GroupSearcher            = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                                    if (GroupSearcher == null)
                                    {
                                        Logger.Write_Warning($@"[Get-DomainGroupMember] Unable to retrieve domain searcher for '{IdentityDomain}'");
                                    }
                                }
                            }
                            else if (new Regex(@"^[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}$").Match(IdentityInstance).Success)
                            {
                                var GuidByteString = string.Join(string.Empty, Guid.Parse(IdentityInstance).ToByteArray().Select(x => x.ToString(@"\X2")));
                                IdentityFilter += $@"(objectguid={GuidByteString})";
                            }
                            else if (IdentityInstance.Contains(@"\"))
                            {
                                var ConvertedIdentityInstance = ConvertADName.Convert_ADName(new Args_Convert_ADName
                                {
                                    OutputType = ADSNameType.Canonical,
                                    Identity   = new string[] { IdentityInstance.Replace(@"\28", @"(").Replace(@"\29", @")") }
                                });
                                if (ConvertedIdentityInstance != null && ConvertedIdentityInstance.Any())
                                {
                                    var GroupDomain = ConvertedIdentityInstance.First().Substring(0, ConvertedIdentityInstance.First().IndexOf('/'));
                                    var GroupName   = IdentityInstance.Split(new char[] { '\\' })[1];
                                    IdentityFilter          += $@"(samAccountName={GroupName})";
                                    SearcherArguments.Domain = GroupDomain;
                                    Logger.Write_Verbose($@"[Get-DomainGroupMember] Extracted domain '{GroupDomain}' from '{IdentityInstance}'");
                                    GroupSearcher = GetDomainSearcher.Get_DomainSearcher(SearcherArguments);
                                }
                            }
                            else
                            {
                                IdentityFilter += $@"(samAccountName={IdentityInstance})";
                            }
                        }
                    }

                    if (IdentityFilter != null && IdentityFilter.Trim() != @"")
                    {
                        Filter += $@"(|{IdentityFilter})";
                    }

                    if (args.LDAPFilter.IsNotNullOrEmpty())
                    {
                        Logger.Write_Verbose($@"[Get-DomainGroupMember] Using additional LDAP filter: {args.LDAPFilter}");
                        Filter += $@"{args.LDAPFilter}";
                    }

                    GroupSearcher.Filter = $@"(&(objectCategory=group){Filter})";
                    Logger.Write_Verbose($@"[Get-DomainGroupMember] Get-DomainGroupMember filter string: {GroupSearcher.Filter}");
                    SearchResult Result = null;
                    try
                    {
                        Result = GroupSearcher.FindOne();
                    }
                    catch (Exception e)
                    {
                        Logger.Write_Warning($@"[Get-DomainGroupMember] Error searching for group with identity '{args.Identity}': {e}");
                        Members = new List <string>();
                    }

                    GroupFoundName = @"";
                    GroupFoundDN   = @"";

                    if (Result != null)
                    {
                        var tmpProperty = Result.Properties[@"member"];
                        var tmpValues   = new string[tmpProperty.Count];
                        tmpProperty.CopyTo(tmpValues, 0);
                        Members = tmpValues.ToList();
                        string RangedProperty = "";

                        if (Members.Count == 0)
                        {
                            // ranged searching, thanks @meatballs__ !
                            var Finished = false;
                            var Bottom   = 0;
                            var Top      = 0;

                            while (!Finished)
                            {
                                Top = Bottom + 1499;
                                var MemberRange = $@"member;range={Bottom}-{Top}";
                                Bottom += 1500;
                                GroupSearcher.PropertiesToLoad.Clear();
                                GroupSearcher.PropertiesToLoad.Add($@"{MemberRange}");
                                GroupSearcher.PropertiesToLoad.Add(@"samaccountname");
                                GroupSearcher.PropertiesToLoad.Add(@"distinguishedname");

                                try
                                {
                                    Result         = GroupSearcher.FindOne();
                                    RangedProperty = Result.Properties.PropertyNames.GetFirstMatch(@"member;range=*");
                                    tmpProperty    = Result.Properties[RangedProperty];
                                    tmpValues      = new string[tmpProperty.Count];
                                    tmpProperty.CopyTo(tmpValues, 0);
                                    Members.AddRange(tmpValues.ToList());
                                    GroupFoundName = Result.Properties[@"samaccountname"][0] as string;
                                    GroupFoundDN   = Result.Properties[@"distinguishedname"][0] as string;

                                    if (Members.Count == 0)
                                    {
                                        Finished = true;
                                    }
                                }
                                catch
                                {
                                    Finished = true;
                                }
                            }
                        }
                        else
                        {
                            GroupFoundName = Result.Properties[@"samaccountname"][0] as string;
                            GroupFoundDN   = Result.Properties[@"distinguishedname"][0] as string;
                            tmpProperty    = Result.Properties[RangedProperty];
                            tmpValues      = new string[tmpProperty.Count];
                            tmpProperty.CopyTo(tmpValues, 0);
                            Members.AddRange(tmpValues.ToList());
                        }

                        if (args.Domain.IsNotNullOrEmpty())
                        {
                            GroupFoundDomain = args.Domain;
                        }
                        else
                        {
                            // if a domain isn't passed, try to extract it from the found group distinguished name
                            if (GroupFoundDN.IsNotNullOrEmpty())
                            {
                                GroupFoundDomain = GroupFoundDN.Substring(GroupFoundDN.IndexOf(@"DC=")).Replace(@"DC=", @"".Replace(@",", @"."));
                            }
                        }
                    }

                    var    UseMatchingRule = false;
                    string MemberDomain    = null;
                    foreach (var Member in Members)
                    {
                        ResultPropertyCollection Properties = null;
                        if (args.Recurse && UseMatchingRule)
                        {
                            //$Properties = $_.Properties
                        }
                        else
                        {
                            var ObjectSearcherArguments = new Args_Get_DomainObject
                            {
                                ADSPath          = SearcherArguments.ADSPath,
                                Credential       = SearcherArguments.Credential,
                                Domain           = SearcherArguments.Domain,
                                DomainController = SearcherArguments.DomainController,
                                Filter           = SearcherArguments.Filter,
                                LDAPFilter       = SearcherArguments.LDAPFilter,
                                Properties       = SearcherArguments.Properties,
                                ResultPageSize   = SearcherArguments.ResultPageSize,
                                SearchBase       = SearcherArguments.SearchBase,
                                SearchScope      = SearcherArguments.SearchScope,
                                SecurityMasks    = SearcherArguments.SecurityMasks,
                                Server           = SearcherArguments.Server,
                                ServerTimeLimit  = SearcherArguments.ServerTimeLimit,
                                Tombstone        = SearcherArguments.Tombstone
                            };
                            ObjectSearcherArguments.Identity   = new string[] { Member };
                            ObjectSearcherArguments.Raw        = true;
                            ObjectSearcherArguments.Properties = new string[] { @"distinguishedname", @"cn", @"samaccountname", @"objectsid", @"objectclass" };
                            var Object = GetDomainObject.Get_DomainObject(ObjectSearcherArguments)?.FirstOrDefault() as SearchResult;
                            Properties = Object.Properties;
                        }

                        if (Properties != null)
                        {
                            var GroupMember = new GroupMember
                            {
                                GroupDomain            = GroupFoundDomain,
                                GroupName              = GroupFoundName,
                                GroupDistinguishedName = GroupFoundDN
                            };

                            string MemberSID = null;
                            if (Properties["objectsid"] != null)
                            {
                                MemberSID = new System.Security.Principal.SecurityIdentifier(Properties["objectsid"][0] as byte[], 0).Value;
                            }
                            else
                            {
                                MemberSID = null;
                            }

                            string MemberDN = null;
                            try
                            {
                                MemberDN = Properties["distinguishedname"][0].ToString();
                                if (MemberDN.IsRegexMatch(@"ForeignSecurityPrincipals|S-1-5-21"))
                                {
                                    try
                                    {
                                        if (MemberSID.IsNullOrEmpty())
                                        {
                                            MemberSID = Properties["cn"][0].ToString();
                                        }
                                        ADNameArguments.Identity   = new string[] { MemberSID };
                                        ADNameArguments.OutputType = ADSNameType.DomainSimple;
                                        var MemberSimpleName = ConvertADName.Convert_ADName(ADNameArguments);

                                        if (MemberSimpleName != null && MemberSimpleName.Any())
                                        {
                                            MemberDomain = MemberSimpleName.First().Split('@')[1];
                                        }
                                        else
                                        {
                                            Logger.Write_Warning($@"[Get-DomainGroupMember] Error converting {MemberDN}");
                                            MemberDomain = null;
                                        }
                                    }
                                    catch
                                    {
                                        Logger.Write_Warning($@"[Get-DomainGroupMember] Error converting {MemberDN}");
                                        MemberDomain = null;
                                    }
                                }
                                else
                                {
                                    // extract the FQDN from the Distinguished Name
                                    MemberDomain = MemberDN.Substring(MemberDN.IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @".");
                                }
                            }
                            catch
                            {
                                MemberDN     = null;
                                MemberDomain = null;
                            }
                            string MemberName = null;
                            if (Properties["samaccountname"] != null)
                            {
                                // forest users have the samAccountName set
                                MemberName = Properties["samaccountname"][0].ToString();
                            }
                            else
                            {
                                // external trust users have a SID, so convert it
                                try
                                {
                                    MemberName = ConvertFromSID.ConvertFrom_SID(new Args_ConvertFrom_SID
                                    {
                                        ObjectSID  = new string[] { Properties["cn"][0].ToString() },
                                        Domain     = ADNameArguments.Domain,
                                        Server     = ADNameArguments.Server,
                                        Credential = ADNameArguments.Credential
                                    }).First();
                                }
                                catch
                                {
                                    // if there's a problem contacting the domain to resolve the SID
                                    MemberName = Properties["cn"][0].ToString();
                                }
                            }

                            string MemberObjectClass = null;
                            if (Properties["objectclass"].RegexContains(@"computer"))
                            {
                                MemberObjectClass = @"computer";
                            }
                            else if (Properties["objectclass"].RegexContains(@"group"))
                            {
                                MemberObjectClass = @"group";
                            }
                            else if (Properties["objectclass"].RegexContains(@"user"))
                            {
                                MemberObjectClass = @"user";
                            }
                            else
                            {
                                MemberObjectClass = null;
                            }
                            GroupMember.MemberDomain            = MemberDomain;
                            GroupMember.MemberName              = MemberName;
                            GroupMember.MemberDistinguishedName = MemberDN;
                            GroupMember.MemberObjectClass       = MemberObjectClass;
                            GroupMember.MemberSID = MemberSID;
                            GroupMembers.Add(GroupMember);

                            // if we're doing manual recursion
                            if (args.Recurse && MemberDN.IsNotNullOrEmpty() && MemberObjectClass.IsRegexMatch(@"group"))
                            {
                                Logger.Write_Verbose($@"[Get-DomainGroupMember] Manually recursing on group: {MemberDN}");
                                var GroupArguments = new Args_Get_DomainGroupMember()
                                {
                                    Domain          = SearcherArguments.Domain,
                                    LDAPFilter      = SearcherArguments.LDAPFilter,
                                    SearchBase      = SearcherArguments.SearchBase,
                                    Server          = SearcherArguments.Server,
                                    SearchScope     = SearcherArguments.SearchScope,
                                    ResultPageSize  = SearcherArguments.ResultPageSize,
                                    ServerTimeLimit = SearcherArguments.ServerTimeLimit,
                                    Tombstone       = SearcherArguments.Tombstone,
                                    Credential      = SearcherArguments.Credential,
                                    Identity        = new string[] { MemberDN }
                                };
                                GroupMembers.AddRange(Get_DomainGroupMember(GroupArguments));
                            }
                        }
                    }
                }
                GroupSearcher.Dispose();
            }
            return(GroupMembers);
        }
예제 #8
0
        public static IEnumerable <string> ConvertTo_SID(Args_ConvertTo_SID args = null)
        {
            if (args == null)
            {
                args = new Args_ConvertTo_SID();
            }

            var DomainSearcherArguments = new Args_Get_DomainObject
            {
                Domain     = args.Domain,
                Server     = args.Server,
                Credential = args.Credential
            };

            var SIDs = new List <string>();

            foreach (var item in args.ObjectName)
            {
                var name = item.Replace(@"/", @"\");

                if (args.Credential != null)
                {
                    var DN = ConvertADName.Convert_ADName(new Args_Convert_ADName
                    {
                        Identity   = new[] { name },
                        OutputType = ADSNameType.DN,
                        Domain     = DomainSearcherArguments.Domain,
                        Server     = DomainSearcherArguments.Server,
                        Credential = DomainSearcherArguments.Credential
                    });


                    if (DN != null)
                    {
                        var UserDomain = DN.First().Substring(DN.First().IndexOf(@"DC=")).Replace(@"DC=", @"").Replace(@",", @".");
                        var UserName   = DN.First().Split(',')[0].Split('=')[1];

                        DomainSearcherArguments.Identity   = new[] { UserName };
                        DomainSearcherArguments.Domain     = UserDomain;
                        DomainSearcherArguments.Properties = new[] { @"objectsid" };
                        var obj = GetDomainObject.Get_DomainObject(DomainSearcherArguments);
                        foreach (LDAPProperty ldapProperty in obj)
                        {
                            SIDs.AddRange(ldapProperty.objectsid);
                        }
                    }
                }
                else
                {
                    try
                    {
                        if (name.Contains(@"\"))
                        {
                            args.Domain = name.Split('\\')[0];
                            name        = name.Split('\\')[1];
                        }
                        else if (args.Domain.IsNullOrEmpty())
                        {
                            args.Domain = GetDomain.Get_Domain().Name;
                        }

                        var obj = new System.Security.Principal.NTAccount(args.Domain, name);
                        SIDs.Add(obj.Translate(typeof(System.Security.Principal.SecurityIdentifier)).Value);
                    }
                    catch (Exception e)
                    {
                        Logger.Write_Verbose($@"[ConvertTo-SID] Error converting {args.Domain}\{name} : {e}");
                    }
                }
            }
            return(SIDs);
        }