public static string GetDomainFromDn(this LdapObject ldapObject)
        {
            if (ldapObject == null || string.IsNullOrEmpty(ldapObject.DistinguishedName))
            {
                return(null);
            }

            return(LdapUtils.DistinguishedNameToDomain(ldapObject.DistinguishedName));
        }
        private string LoadLDAPDomain()
        {
            try
            {
                if (!Settings.EnableLdapAuthentication)
                {
                    return(null);
                }

                if (!LdapHelper.IsConnected)
                {
                    LdapHelper.Connect();
                }

                string ldapDomain;

                if (AllDomainUsers.Any())
                {
                    ldapDomain = AllDomainUsers.First().GetDomainFromDn();

                    if (!string.IsNullOrEmpty(ldapDomain))
                    {
                        return(ldapDomain);
                    }
                }

                ldapDomain = LdapHelper.SearchDomain();

                if (!string.IsNullOrEmpty(ldapDomain))
                {
                    return(ldapDomain);
                }

                ldapDomain = LdapUtils.DistinguishedNameToDomain(Settings.UserDN);

                if (!string.IsNullOrEmpty(ldapDomain))
                {
                    return(ldapDomain);
                }

                ldapDomain = LdapUtils.DistinguishedNameToDomain(Settings.GroupDN);

                if (!string.IsNullOrEmpty(ldapDomain))
                {
                    return(ldapDomain);
                }
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("LoadLDAPDomain(): Error: {0}", ex);
            }

            return(null);
        }
 public void UserEmptyTest()
 {
     Assert.Equals(LdapUtils.IsLoginAccepted(LdapLogin, null, LDAP_DOMAIN), false);
     Assert.Equals(LdapUtils.IsLoginAccepted(LdapLogin, Constants.LostUser, LDAP_DOMAIN), false);
     Assert.Equals(LdapUtils.IsLoginAccepted(LdapLogin, new UserInfo
     {
         ID    = Guid.NewGuid(),
         Email = "*****@*****.**",
     }, LDAP_DOMAIN), false);
     Assert.Equals(LdapUtils.IsLoginAccepted(LdapLogin, new UserInfo
     {
         ID       = Guid.NewGuid(),
         UserName = "******",
     }, LDAP_DOMAIN), false);
 }
 public void CheckEmptyUserTest()
 {
     Assert.AreEqual(false, LdapUtils.IsLoginAccepted(BaseLdapLogin, null, BASE_LDAP_DOMAIN));
     Assert.AreEqual(false, LdapUtils.IsLoginAccepted(BaseLdapLogin, Constants.LostUser, BASE_LDAP_DOMAIN));
     Assert.AreEqual(false, LdapUtils.IsLoginAccepted(BaseLdapLogin, new UserInfo
     {
         ID    = Guid.NewGuid(),
         Email = BASE_EMAIL,
     }, BASE_LDAP_DOMAIN));
     Assert.AreEqual(false, LdapUtils.IsLoginAccepted(BaseLdapLogin, new UserInfo
     {
         ID       = Guid.NewGuid(),
         UserName = BASE_USERNAME,
     }, BASE_LDAP_DOMAIN));
 }
Exemplo n.º 5
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected org.apache.shiro.authc.AuthenticationInfo queryForAuthenticationInfoUsingStartTls(org.apache.shiro.authc.AuthenticationToken token, org.apache.shiro.realm.ldap.LdapContextFactory ldapContextFactory) throws javax.naming.NamingException
        protected internal virtual AuthenticationInfo QueryForAuthenticationInfoUsingStartTls(AuthenticationToken token, LdapContextFactory ldapContextFactory)
        {
            object principal   = getLdapPrincipal(token);
            object credentials = token.Credentials;

            LdapContext ctx = null;

            try
            {
                ctx = GetLdapContextUsingStartTls(ldapContextFactory, principal, credentials);
                return(CreateAuthenticationInfo(token, principal, credentials, ctx));
            }
            finally
            {
                LdapUtils.closeContext(ctx);
            }
        }
Exemplo n.º 6
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected org.apache.shiro.authz.AuthorizationInfo queryForAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection principals, org.apache.shiro.realm.ldap.LdapContextFactory ldapContextFactory) throws javax.naming.NamingException
        protected internal override AuthorizationInfo QueryForAuthorizationInfo(PrincipalCollection principals, LdapContextFactory ldapContextFactory)
        {
            if (_authorizationEnabled.Value)
            {
                string username = GetUsername(principals);
                if (string.ReferenceEquals(username, null))
                {
                    return(null);
                }

                if (_useSystemAccountForAuthorization.Value)
                {
                    // Perform context search using the system context
                    LdapContext ldapContext = _useStartTls ? GetSystemLdapContextUsingStartTls(ldapContextFactory) : ldapContextFactory.SystemLdapContext;

                    ISet <string> roleNames;
                    try
                    {
                        roleNames = FindRoleNamesForUser(username, ldapContext);
                    }
                    finally
                    {
                        LdapUtils.closeContext(ldapContext);
                    }

                    return(new SimpleAuthorizationInfo(roleNames));
                }
                else
                {
                    // Authorization info is cached during authentication
                    Cache <object, AuthorizationInfo> authorizationCache = AuthorizationCache;
                    AuthorizationInfo authorizationInfo = authorizationCache.get(username);
                    if (authorizationInfo == null)
                    {
                        // The cached authorization info has expired.
                        // Since we do not have the subject's credentials we cannot perform a new LDAP search
                        // for authorization info. Instead we need to fail with a special status,
                        // so that the client can react by re-authenticating.
                        throw new AuthorizationExpiredException("LDAP authorization info expired.");
                    }
                    return(authorizationInfo);
                }
            }
            return(null);
        }
Exemplo n.º 7
0
        public DomainArray getDomains()
        {
            DomainArray result = new DomainArray();

            try
            {
                using (new Impersonator(mySession.MdwsConfiguration.LdapConfiguration.RunasUser))
                {
                    SortedList <string, Domain> domains = LdapUtils.getCurrentDomains();
                    result = new DomainArray(domains);
                }
            }
            catch (Exception exc)
            {
                result.fault = new FaultTO(exc);
            }

            return(result);
        }
Exemplo n.º 8
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private org.apache.shiro.authc.AuthenticationInfo queryForAuthenticationInfoSAM(org.apache.shiro.authc.AuthenticationToken token, org.apache.shiro.realm.ldap.LdapContextFactory ldapContextFactory) throws javax.naming.NamingException
        private AuthenticationInfo QueryForAuthenticationInfoSAM(AuthenticationToken token, LdapContextFactory ldapContextFactory)
        {
            object principal   = token.Principal;
            object credentials = token.Credentials;

            LdapContext ctx = null;

            try
            {
                ctx = _useStartTls ? GetSystemLdapContextUsingStartTls(ldapContextFactory) : ldapContextFactory.SystemLdapContext;
                string[]       attrs                    = new string[] { "cn" };
                SearchControls searchCtls               = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, attrs, false, false);
                object[]       searchArguments          = new object[] { principal };
                string         filter                   = "sAMAccountName={0}";
                NamingEnumeration <SearchResult> search = ctx.search(_userSearchBase, filter, searchArguments, searchCtls);
                if (search.hasMore())
                {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final javax.naming.directory.SearchResult next = search.next();
                    SearchResult next      = search.next();
                    string       loginUser = next.NameInNamespace;
                    if (search.hasMore())
                    {
                        _securityLog.error("More than one user matching: " + principal);
                        throw new AuthenticationException("More than one user matching: " + principal);
                    }
                    else
                    {
                        LdapContext ctx2 = ldapContextFactory.getLdapContext(loginUser, credentials);
                        LdapUtils.closeContext(ctx2);
                    }
                }
                else
                {
                    throw new AuthenticationException("No user matching: " + principal);
                }
                return(CreateAuthenticationInfo(token, principal, credentials, ctx));
            }
            finally
            {
                LdapUtils.closeContext(ctx);
            }
        }
Exemplo n.º 9
0
        private bool ServerCertValidationHandler(object sender, X509Certificate certificate,
                                                 X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            lock (RootSync)
            {
                var certHash = certificate.GetCertHashString();

                if (LdapUtils.IsCertInstalled(certificate, _log))
                {
                    AcceptCertificate     = true;
                    AcceptCertificateHash = certHash;
                    return(true);
                }

                if (AcceptCertificate)
                {
                    if (AcceptCertificateHash == null || AcceptCertificateHash.Equals(certHash))
                    {
                        if (LdapUtils.TryInstallCert(certificate, _log))
                        {
                            AcceptCertificateHash = certHash;
                        }

                        return(true);
                    }

                    AcceptCertificate     = false;
                    AcceptCertificateHash = null;
                }

                _log.WarnFormat("ServerCertValidationHandler: sslPolicyErrors = {0}", sslPolicyErrors);

                _certificateConfirmRequest = LdapCertificateConfirmRequest.FromCert(certificate, chain, sslPolicyErrors, false, true, _log);
            }

            return(false);
        }
Exemplo n.º 10
0
        // TODO: Extract to an LdapAuthorizationStrategy ? This ("group by attribute") is one of multiple possible strategies
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: java.util.Set<String> findRoleNamesForUser(String username, javax.naming.ldap.LdapContext ldapContext) throws javax.naming.NamingException
        internal virtual ISet <string> FindRoleNamesForUser(string username, LdapContext ldapContext)
        {
            ISet <string> roleNames = new LinkedHashSet <string>();

            SearchControls searchCtls = new SearchControls();

            searchCtls.SearchScope         = SearchControls.SUBTREE_SCOPE;
            searchCtls.ReturningAttributes = _membershipAttributeNames.ToArray();

            // Use search argument to prevent potential code injection
            object[] searchArguments = new object[] { username };

            NamingEnumeration result = ldapContext.search(_userSearchBase, _userSearchFilter, searchArguments, searchCtls);

            if (result.hasMoreElements())
            {
                SearchResult searchResult = ( SearchResult )result.next();

                if (result.hasMoreElements())
                {
                    _securityLog.warn(_securityLog.DebugEnabled ? WithRealm("LDAP user search for user principal '%s' is ambiguous. The first match that will " + "be checked for group membership is '%s' but the search also matches '%s'. " + "Please check your LDAP realm configuration.", username, searchResult.ToString(), result.next().ToString()) : WithRealm("LDAP user search for user principal '%s' is ambiguous. The search matches more " + "than one entry. Please check your LDAP realm configuration.", username));
                }

                Attributes attributes = searchResult.Attributes;
                if (attributes != null)
                {
                    NamingEnumeration attributeEnumeration = attributes.All;
                    while (attributeEnumeration.hasMore())
                    {
                        Attribute attribute   = ( Attribute )attributeEnumeration.next();
                        string    attributeId = attribute.ID;
                        if (_membershipAttributeNames.Any(attributeId.equalsIgnoreCase))
                        {
                            ICollection <string> groupNames     = LdapUtils.getAllAttributeValues(attribute);
                            ICollection <string> rolesForGroups = GetRoleNamesForGroups(groupNames);
                            roleNames.addAll(rolesForGroups);
                        }
                    }
                }
            }
            return(roleNames);
        }
        public static LdapCertificateConfirmRequest FromCert(X509Certificate certificate, X509Chain chain,
                                                             SslPolicyErrors sslPolicyErrors, bool approved = false, bool requested = false, ILog log = null)
        {
            var certificateErrors = GetLdapCertProblems(certificate, chain, sslPolicyErrors, log);

            try
            {
                string   serialNumber = "", issuerName = "", subjectName = "", hash = "";
                DateTime validFrom = DateTime.UtcNow, validUntil = DateTime.UtcNow;

                LdapUtils.SkipErrors(() => serialNumber = certificate.GetSerialNumberString(), log);
                LdapUtils.SkipErrors(() => issuerName   = certificate.Issuer, log);
                LdapUtils.SkipErrors(() => subjectName  = certificate.Subject, log);
                LdapUtils.SkipErrors(() => validFrom    = DateTime.Parse(certificate.GetEffectiveDateString()), log);
                LdapUtils.SkipErrors(() => validUntil   = DateTime.Parse(certificate.GetExpirationDateString()), log);
                LdapUtils.SkipErrors(() => hash         = certificate.GetCertHashString(), log);

                var certificateConfirmRequest = new LdapCertificateConfirmRequest
                {
                    SerialNumber      = serialNumber,
                    IssuerName        = issuerName,
                    SubjectName       = subjectName,
                    ValidFrom         = validFrom,
                    ValidUntil        = validUntil,
                    Hash              = hash,
                    CertificateErrors = certificateErrors,
                    Approved          = approved,
                    Requested         = requested
                };

                return(certificateConfirmRequest);
            }
            catch (Exception ex)
            {
                if (log != null)
                {
                    log.ErrorFormat("LdapCertificateConfirmRequest.FromCert() failed. Error: {0}", ex);
                }
                return(null);
            }
        }
Exemplo n.º 12
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private javax.naming.ldap.LdapContext getLdapContextUsingStartTls(org.apache.shiro.realm.ldap.LdapContextFactory ldapContextFactory, Object principal, Object credentials) throws javax.naming.NamingException
        private LdapContext GetLdapContextUsingStartTls(LdapContextFactory ldapContextFactory, object principal, object credentials)
        {
            JndiLdapContextFactory      jndiLdapContextFactory = ( JndiLdapContextFactory )ldapContextFactory;
            Dictionary <string, object> env = new Dictionary <string, object>();

            env[Context.INITIAL_CONTEXT_FACTORY] = jndiLdapContextFactory.ContextFactoryClassName;
            env[Context.PROVIDER_URL]            = jndiLdapContextFactory.Url;

            LdapContext ctx = null;

            try
            {
                ctx = new InitialLdapContext(env, null);

                StartTlsRequest  startTlsRequest = new StartTlsRequest();
                StartTlsResponse tls             = ( StartTlsResponse )ctx.extendedOperation(startTlsRequest);

                tls.negotiate();

                ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, jndiLdapContextFactory.AuthenticationMechanism);
                ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal);
                ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);

                // do a lookup of the user to trigger authentication
                ctx.lookup(principal.ToString());

                return(ctx);
            }
            catch (IOException e)
            {
                LdapUtils.closeContext(ctx);
                _securityLog.error(WithRealm("Failed to negotiate TLS connection with '%s': ", Server(jndiLdapContextFactory), e));
                throw new CommunicationException(e.Message);
            }
            catch (Exception t)
            {
                LdapUtils.closeContext(ctx);
                _securityLog.error(WithRealm("Unexpected failure to negotiate TLS connection with '%s': ", Server(jndiLdapContextFactory), t));
                throw t;
            }
        }
Exemplo n.º 13
0
        /// <summary>
        ///     Fetches the DACL of the object which is evaluated by
        ///     {@linkplain net.tirasa.adsddl.ntsd.dacl.DACLAssertor#doAssert}
        ///     @throws CommunicationException
        ///     @throws NameNotFoundException
        ///     @throws NamingException
        /// </summary>
        private void GetDacl()
        {
            SearchRequest directoryRequest = new SearchRequest(LdapUtils.GetDnFromHostname(),
                                                               "",
                                                               Native.Native.LdapSearchScope.LDAP_SCOPE_SUBTREE)
            {
                Attributes = { LdapAttributes.NtSecurityDescriptor }
            };

            directoryRequest.Controls.Add(new SecurityDescriptorFlagControl(SecurityMasks.Owner | SecurityMasks.Group | SecurityMasks.Dacl | SecurityMasks.Sacl));
            SearchResponse response = (SearchResponse)this.ldapContext.SendRequest(directoryRequest);
            DirectoryEntry entry    = response.Entries.FirstOrDefault();

            if (entry == null)
            {
                throw new LdapException("Couldn't find ldap");
            }

            byte[] descbytes = entry.GetBytes(LdapAttributes.NtSecurityDescriptor);
            Sddl   sddl      = new Sddl(descbytes);

            this.dacl = sddl.GetDacl();
        }
        public List <Tuple <UserInfo, LdapObject> > FindLdapUsers(string login)
        {
            var listResults = new List <Tuple <UserInfo, LdapObject> >();

            var ldapLogin = LdapLogin.ParseLogin(login);

            if (ldapLogin == null)
            {
                return(listResults);
            }

            if (!LdapHelper.IsConnected)
            {
                LdapHelper.Connect();
            }

            var exps = new List <Expression> {
                Expression.Equal(Settings.LoginAttribute, ldapLogin.Username)
            };

            if (!ldapLogin.Username.Equals(login) && ldapLogin.ToString().Equals(login))
            {
                exps.Add(Expression.Equal(Settings.LoginAttribute, login));
            }

            string email = null;

            if (!string.IsNullOrEmpty(Settings.MailAttribute) && !string.IsNullOrEmpty(ldapLogin.Domain) && login.Contains("@"))
            {
                email = ldapLogin.ToString();
                exps.Add(Expression.Equal(Settings.MailAttribute, email));
            }

            var searchTerm = exps.Count > 1 ? Criteria.Any(exps.ToArray()).ToString() : exps.First().ToString();

            var users = LdapHelper.GetUsers(searchTerm, !string.IsNullOrEmpty(email) ? -1 : 1)
                        .Where(user => user != null)
                        .ToLookup(lu =>
            {
                var ui = Constants.LostUser;

                try
                {
                    if (string.IsNullOrEmpty(_ldapDomain))
                    {
                        _ldapDomain = LdapUtils.DistinguishedNameToDomain(lu.DistinguishedName);
                    }

                    ui = lu.ToUserInfo(this, _log);
                }
                catch (Exception ex)
                {
                    _log.ErrorFormat("FindLdapUser->ToUserInfo() failed. Error: {0}", ex.ToString());
                }

                return(Tuple.Create(ui, lu));
            });

            if (!users.Any())
            {
                return(listResults);
            }

            foreach (var user in users)
            {
                var ui = user.Key.Item1;

                if (ui.Equals(Constants.LostUser))
                {
                    continue;
                }

                var ul = user.Key.Item2;

                var ldapLoginAttribute = ul.GetValue(Settings.LoginAttribute) as string;

                if (string.IsNullOrEmpty(ldapLoginAttribute))
                {
                    _log.WarnFormat("LDAP: DN: '{0}' Login Attribute '{1}' is empty", ul.DistinguishedName, Settings.LoginAttribute);
                    continue;
                }

                if (ldapLoginAttribute.Equals(login))
                {
                    listResults.Add(user.Key);
                    continue;
                }

                if (!string.IsNullOrEmpty(email))
                {
                    if (ui.Email.Equals(email, StringComparison.InvariantCultureIgnoreCase))
                    {
                        listResults.Add(user.Key);
                        continue;
                    }
                }

                if (LdapUtils.IsLoginAccepted(ldapLogin, ui, LDAPDomain))
                {
                    listResults.Add(user.Key);
                }
            }

            return(listResults);
        }
        public void CheckIncorrectLdapLoginByEmailWithBaseDomainTest()
        {
            var ldapLogin = new LdapLogin("Ivan.Ivanov", BASE_LDAP_DOMAIN);

            Assert.AreEqual(false, LdapUtils.IsLoginAccepted(ldapLogin, BaseUserInfo, BASE_LDAP_DOMAIN));
        }
 public void CheckAllBaseTest()
 {
     Assert.AreEqual(true, LdapUtils.IsLoginAccepted(BaseLdapLogin, BaseUserInfo, BASE_LDAP_DOMAIN));
 }
Exemplo n.º 17
0
 public static IList <LdapEntry> SearchByCn(this ILdapConnection connection, string cn)
 {
     return(connection.SearchByCn(LdapUtils.GetDnFromHostname(), cn));
 }
Exemplo n.º 18
0
        public override string SearchDomain()
        {
            try
            {
                var capabilities = GetCapabilities();

                if (capabilities.Any())
                {
                    if (capabilities.ContainsKey("defaultNamingContext"))
                    {
                        var dnList = capabilities["defaultNamingContext"];

                        var dn = dnList.FirstOrDefault(dc =>
                                                       !string.IsNullOrEmpty(dc) &&
                                                       dc.IndexOf("dc=", StringComparison.InvariantCultureIgnoreCase) != -1);

                        var domain = LdapUtils.DistinguishedNameToDomain(dn);

                        if (!string.IsNullOrEmpty(domain))
                        {
                            return(domain);
                        }
                    }

                    if (capabilities.ContainsKey("rootDomainNamingContext"))
                    {
                        var dnList = capabilities["rootDomainNamingContext"];

                        var dn = dnList.FirstOrDefault(dc =>
                                                       !string.IsNullOrEmpty(dc) &&
                                                       dc.IndexOf("dc=", StringComparison.InvariantCultureIgnoreCase) != -1);

                        var domain = LdapUtils.DistinguishedNameToDomain(dn);

                        if (!string.IsNullOrEmpty(domain))
                        {
                            return(domain);
                        }
                    }

                    if (capabilities.ContainsKey("namingContexts"))
                    {
                        var dnList = capabilities["namingContexts"];

                        var dn = dnList.FirstOrDefault(dc =>
                                                       !string.IsNullOrEmpty(dc) &&
                                                       dc.IndexOf("dc=", StringComparison.InvariantCultureIgnoreCase) != -1);

                        var domain = LdapUtils.DistinguishedNameToDomain(dn);

                        if (!string.IsNullOrEmpty(domain))
                        {
                            return(domain);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.WarnFormat("NovellLdapHelper->SearchDomain() failed. Error: {0}", e);
            }

            try
            {
                var searchResult =
                    LDAPSearcher.Search(Settings.UserDN, NovellLdapSearcher.LdapScope.Sub, Settings.UserFilter, limit: 1)
                    .FirstOrDefault();

                return(searchResult != null?searchResult.GetDomainFromDn() : null);
            }
            catch (Exception e)
            {
                Log.WarnFormat("NovellLdapHelper->SearchDomain() failed. Error: {0}", e);
            }

            return(null);
        }
Exemplo n.º 19
0
        private IEnumerable <LdapObject> GetLdapUserGroups(LdapObject ldapUser)
        {
            var ldapUserGroups = new List <LdapObject>();

            try
            {
                if (!Settings.GroupMembership)
                {
                    return(ldapUserGroups);
                }

                if (ldapUser == null ||
                    string.IsNullOrEmpty(ldapUser.Sid))
                {
                    return(ldapUserGroups);
                }

                if (!LdapHelper.IsConnected)
                {
                    LdapHelper.Connect();
                }

                var userGroups = ldapUser.GetAttributes(LdapConstants.ADSchemaAttributes.MEMBER_OF, _log)
                                 .Select(s => LdapUtils.UnescapeLdapString(s))
                                 .ToList();

                if (!userGroups.Any())
                {
                    userGroups = ldapUser.GetAttributes(GROUP_MEMBERSHIP, _log);
                }

                var searchExpressions = new List <Expression>();

                var primaryGroupId = ldapUser.GetValue(LdapConstants.ADSchemaAttributes.PRIMARY_GROUP_ID) as string;

                if (!string.IsNullOrEmpty(primaryGroupId))
                {
                    var userSid = ldapUser.Sid;
                    var index   = userSid.LastIndexOf("-", StringComparison.InvariantCultureIgnoreCase);

                    if (index > -1)
                    {
                        var primaryGroupSid = userSid.Substring(0, index + 1) + primaryGroupId;
                        searchExpressions.Add(Expression.Equal(ldapUser.SidAttribute, primaryGroupSid));
                    }
                }

                if (userGroups.Any())
                {
                    var cnRegex = new Regex(",[A-z]{2}=");
                    searchExpressions.AddRange(userGroups
                                               .Select(g => g.Substring(0, cnRegex.Match(g).Index))
                                               .Where(s => !string.IsNullOrEmpty(s))
                                               .Select(Expression.Parse)
                                               .Where(e => e != null));

                    var criteria = Criteria.Any(searchExpressions.ToArray());

                    var foundList = LdapHelper.GetGroups(criteria);

                    if (foundList.Any())
                    {
                        ldapUserGroups.AddRange(foundList);
                    }
                }
                else
                {
                    var ldapGroups = LdapHelper.GetGroups();

                    ldapUserGroups.AddRange(
                        ldapGroups.Where(
                            ldapGroup =>
                            LdapHelper.UserExistsInGroup(ldapGroup, ldapUser, Settings)));
                }
            }
            catch (Exception ex)
            {
                if (ldapUser != null)
                {
                    _log.ErrorFormat("IsUserExistInGroups(login: '******' sid: '{1}') error {2}",
                                     ldapUser.DistinguishedName, ldapUser.Sid, ex);
                }
            }

            return(ldapUserGroups);
        }
Exemplo n.º 20
0
        public void LdapUtils_GetDnFromHostname_Return_Base_Dn()
        {
            var actual = LdapUtils.GetDnFromHostname("uvda01.v04.example.com");

            Assert.AreEqual("dc=v04,dc=example,dc=com", actual);
        }
Exemplo n.º 21
0
        public void LdapUtils_GetDnFromHostname_Return_Hostname_When_Machine_Not_Joined_To_Domain()
        {
            var actual = LdapUtils.GetDnFromHostname("uvda01");

            Assert.AreEqual("dc=uvda01", actual);
        }
        public void CheckLdapLoginByBaseUsernameTest()
        {
            var ldapLogin = LdapLogin.ParseLogin(BASE_USERNAME);

            Assert.AreEqual(true, LdapUtils.IsLoginAccepted(ldapLogin, BaseUserInfo, BASE_LDAP_DOMAIN));
        }
        public void CheckIncorrectLdapLoginByEmailTest()
        {
            var ldapLogin = LdapLogin.ParseLogin("*****@*****.**");

            Assert.AreEqual(false, LdapUtils.IsLoginAccepted(ldapLogin, BaseUserInfo, BASE_LDAP_DOMAIN));
        }
        public void CheckLdapLoginByBaseUsernameAndBaseDominTest()
        {
            var ldapLogin = new LdapLogin(BASE_USERNAME, BASE_LDAP_DOMAIN);

            Assert.AreEqual(true, LdapUtils.IsLoginAccepted(ldapLogin, BaseUserInfo, BASE_LDAP_DOMAIN));
        }
        public void CheckLdapLoginByBaseForm4Test()
        {
            var ldapLogin = LdapLogin.ParseLogin(BASE_LDAP_LOGIN_FORM4);

            Assert.AreEqual(true, LdapUtils.IsLoginAccepted(ldapLogin, BaseUserInfo, BASE_LDAP_DOMAIN));
        }
Exemplo n.º 26
0
 public void LoginEmptyTest()
 {
     Assert.Equals(LdapUtils.IsLoginAccepted(null, BaseUserInfo, LDAP_DOMAIN), false);
 }
 public void CheckEmptyLdapLoginTest()
 {
     Assert.AreEqual(false, LdapUtils.IsLoginAccepted(null, BaseUserInfo, BASE_LDAP_DOMAIN));
     Assert.AreEqual(false, LdapUtils.IsLoginAccepted(new LdapLogin("", ""), BaseUserInfo, BASE_LDAP_DOMAIN));
     Assert.AreEqual(false, LdapUtils.IsLoginAccepted(new LdapLogin(null, null), BaseUserInfo, BASE_LDAP_DOMAIN));
 }
 public void CheckEmptyDomainTest()
 {
     Assert.AreEqual(false, LdapUtils.IsLoginAccepted(BaseLdapLogin, BaseUserInfo, null));
     Assert.AreEqual(false, LdapUtils.IsLoginAccepted(BaseLdapLogin, Constants.LostUser, ""));
 }
Exemplo n.º 29
0
 public static IList <LdapEntry> SearchBySid(this ILdapConnection connection, string sid)
 {
     return(connection.SearchBySid(LdapUtils.GetDnFromHostname(), sid));
 }
Exemplo n.º 30
0
 public static async Task <IList <LdapEntry> > SearchBySidAsync(this ILdapConnection connection, string sid)
 {
     return(await connection.SearchBySidAsync(LdapUtils.GetDnFromHostname(), sid));
 }