Ejemplo n.º 1
0
        public static HashSet <GroupId> ExtractGroups(this SearchResult result)
        {
            var groups = new HashSet <GroupId>();

            if (result == null || !result.Properties.Contains("memberof"))
            {
                return(groups);
            }

            foreach (object memberOfProperty in result.Properties["memberof"])
            {
                var memberOf = memberOfProperty.ToString();

                //memberof is CN=groupName,OU=something,OH=else
                foreach (string cat in LdapSplitRegex.Split(memberOf))
                {
                    var cats = cat.Split('=');
                    if (string.Equals(cats[0], "CN", StringComparison.OrdinalIgnoreCase))
                    {
                        var groupName = Unescape(cats[1]);
                        groups.Add(new GroupId(groupName, LDAP.GetDomainPath(memberOf)));
                    }
                }
            }

            return(groups);
        }
Ejemplo n.º 2
0
        private SearchResult TryGetPrincipal(PrincipalSearchType searchType, string principalName)
        {
            if (string.IsNullOrEmpty(principalName))
            {
                return(null);
            }

            this.LogDebug($"Trying to a {searchType} search for principal \"{principalName}\"...");

            PrincipalId principalId  = null;
            var         searchString = new StringBuilder();

            if (searchType == PrincipalSearchType.Users)
            {
                principalId = UserId.Parse(principalName);
                searchString.Append($"(sAMAccountName={LDAP.Escape(principalId?.Principal ?? principalName)})");
            }
            else if (searchType.HasFlag(PrincipalSearchType.Groups))
            {
                principalId = GroupId.Parse(principalName);
                searchString.Append("(|");
                searchString.Append($"(sAMAccountName={LDAP.Escape(principalId?.Principal ?? principalName)})");
                searchString.Append($"(name={LDAP.Escape(principalId?.Principal ?? principalName)})");
                searchString.Append(")");
            }
            else if (searchType == PrincipalSearchType.UsersAndGroups)
            {
                throw new ArgumentOutOfRangeException(nameof(searchType));
            }

            HashSet <CredentialedDomain> domains;

            if (principalId == null)
            {
                this.LogDebug($"No domain specified, searching through aliases.");
                domains = this.domainsToSearch.Value;
            }
            else
            {
                this.LogDebug($"Domain alias \"{principalId.DomainAlias}\" will be used.");
                domains = new HashSet <CredentialedDomain>();
                domains.Add(new CredentialedDomain(principalId.DomainAlias));
            }
            foreach (var domain in domains)
            {
                this.LogDebug($"Searching domain {domain}...");
                using (var entry = new DirectoryEntry("LDAP://DC=" + domain.Name.Replace(".", ",DC="), domain.UserName, domain.Password))
                    using (var searcher = new DirectorySearcher(entry))
                    {
                        searcher.Filter = searchString.ToString();
                        var result = searcher.FindOne();
                        if (result != null)
                        {
                            return(result);
                        }
                    }
            }
            this.LogDebug($"Principal not found.");
            return(null);
        }
Ejemplo n.º 3
0
            public bool IsMemberOfGroup(string groupName)
            {
                if (groupName == null)
                {
                    throw new ArgumentNullException(nameof(groupName));
                }

                var userSearchResult = this.directory.TryGetPrincipal(PrincipalSearchType.Users, this.userId.ToFullyQualifiedName());

                if (userSearchResult == null)
                {
                    return(false);
                }

                var groupSet    = LDAP.ExtractGroupNames(userSearchResult);
                var compareName = GroupId.Parse(groupName)?.Principal ?? groupName;

                if (groupSet.Contains(compareName))
                {
                    return(true);
                }

                if (this.directory.SearchGroupsRecursively)
                {
                    var groupsToSearch = new Queue <string>(groupSet);
                    var groupsSearched = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                    while (groupsToSearch.Count > 0)
                    {
                        var nextGroup = groupsToSearch.Dequeue();
                        if (groupsSearched.Add(nextGroup))
                        {
                            var groupSearchResult = this.directory.TryGetPrincipal(PrincipalSearchType.Groups, nextGroup);
                            if (groupSearchResult != null)
                            {
                                var groupGroups = LDAP.ExtractGroupNames(groupSearchResult);
                                foreach (var g in groupGroups)
                                {
                                    groupsToSearch.Enqueue(g);
                                }
                            }
                        }
                    }

                    return(groupsSearched.Contains(compareName));
                }

                return(false);
            }
Ejemplo n.º 4
0
        public override IUserDirectoryUser TryParseLogonUser(string logonUser)
        {
            if (string.IsNullOrEmpty(logonUser))
            {
                throw new ArgumentNullException(nameof(logonUser));
            }

            var parts = logonUser.Split(new[] { '\\' }, 2, StringSplitOptions.RemoveEmptyEntries);

            if (parts.Length != 2)
            {
                return(null);
            }

            var domain = LDAP.GetDomainNameFromNetbiosName(parts[0], this.netBiosNameMaps.Value);

            return(this.TryGetUser($"{parts[1]}@{domain}"));
        }
Ejemplo n.º 5
0
            public bool IsMemberOfGroup(string groupName)
            {
                if (groupName == null)
                {
                    throw new ArgumentNullException(nameof(groupName));
                }

                var userSearchResult = directory.TryGetPrincipal(PrincipalSearchType.Users, this.userId.ToFullyQualifiedName());

                if (userSearchResult == null)
                {
                    return(false);
                }

                var groupSet = LDAP.ExtractGroupNames(userSearchResult);

                return(groupSet.Contains(GroupId.Parse(groupName)?.Principal ?? groupName));
            }
Ejemplo n.º 6
0
        private IEnumerable <IUserDirectoryPrincipal> FindPrincipals(PrincipalSearchType searchType, string searchTerm)
        {
            if (string.IsNullOrEmpty(searchTerm))
            {
                yield break;
            }

            var categoryFilter = AH.Switch <PrincipalSearchType, string>(searchType)
                                 .Case(PrincipalSearchType.UsersAndGroups, "(|(objectCategory=user)(objectCategory=group))")
                                 .Case(PrincipalSearchType.Groups, "(objectCategory=group)")
                                 .Case(PrincipalSearchType.Users, "(objectCategory=user)")
                                 .End();

            var st     = LDAP.Escape(searchTerm);
            var filter = $"(&{categoryFilter}(|(userPrincipalName={st}*)(sAMAccountName={st}*)(name={st}*)(displayName={st}*)))";

            this.LogDebug("Search term: " + searchTerm);
            this.LogDebug("Filter string: " + filter);

            foreach (var domain in this.domainsToSearch.Value)
            {
                this.LogDebug("Searching domain: " + domain);

                using (var entry = new DirectoryEntry(this.GetLdapRoot() + "DC=" + domain.Name.Replace(".", ",DC="), domain.UserName, domain.Password))
                    using (var searcher = new DirectorySearcher(entry))
                    {
                        searcher.Filter = filter;

                        using (var results = searcher.FindAll())
                        {
                            foreach (SearchResult result in results)
                            {
                                var principal = this.CreatePrincipal(result);
                                if (principal == null)
                                {
                                    continue;
                                }

                                yield return(principal);
                            }
                        }
                    }
            }
        }
Ejemplo n.º 7
0
        private void GetParentGroups(PrincipalId principalId, HashSet <GroupId> groupList, bool recurse)
        {
            var escapedUserPrincipalName = LDAP.Escape(principalId.ToString());

            var filter = string.Format(
                "(&(|(objectCategory=user)(objectCategory=group))(|(userPrincipalName={0})(sAMAccountName={1})(name={1})))",
                LDAP.Escape(principalId.ToString()),
                LDAP.Escape(principalId.Principal)
                );

            try
            {
                using (var entry = new DirectoryEntry($"LDAP://" + principalId.GetDomainSearchPath()))
                    using (var searcher = new DirectorySearcher(entry))
                    {
                        searcher.Filter = filter;
                        var result = searcher.FindOne();
                        if (result == null)
                        {
                            return;
                        }

                        foreach (var group in result.ExtractGroups())
                        {
                            if (groupList.Add(group) && recurse)
                            {
                                this.GetParentGroups(group, groupList, true);
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                this.LogWarning("Failed to get active directory groups: " + ex.Message);
            }
        }