Search in sources :

Example 1 with SearchControls

use of javax.naming.directory.SearchControls in project tomcat by apache.

the class JNDIRealm method getRoles.

/**
     * Return a List of roles associated with the given User.  Any
     * roles present in the user's directory entry are supplemented by
     * a directory search. If no roles are associated with this user,
     * a zero-length List is returned.
     *
     * @param context The directory context we are searching
     * @param user The User to be checked
     * @return the list of role names
     * @exception NamingException if a directory server error occurs
     */
protected List<String> getRoles(DirContext context, User user) throws NamingException {
    if (user == null)
        return null;
    String dn = user.getDN();
    String username = user.getUserName();
    String userRoleId = user.getUserRoleId();
    if (dn == null || username == null)
        return null;
    if (containerLog.isTraceEnabled())
        containerLog.trace("  getRoles(" + dn + ")");
    // Start with roles retrieved from the user entry
    List<String> list = new ArrayList<>();
    List<String> userRoles = user.getRoles();
    if (userRoles != null) {
        list.addAll(userRoles);
    }
    if (commonRole != null)
        list.add(commonRole);
    if (containerLog.isTraceEnabled()) {
        containerLog.trace("  Found " + list.size() + " user internal roles");
        containerLog.trace("  Found user internal roles " + list.toString());
    }
    // Are we configured to do role searches?
    if ((roleFormat == null) || (roleName == null))
        return list;
    // Set up parameters for an appropriate search
    String filter = roleFormat.format(new String[] { doRFC2254Encoding(dn), username, userRoleId });
    SearchControls controls = new SearchControls();
    if (roleSubtree)
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    else
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    controls.setReturningAttributes(new String[] { roleName });
    String base = null;
    if (roleBaseFormat != null) {
        NameParser np = context.getNameParser("");
        Name name = np.parse(dn);
        String[] nameParts = new String[name.size()];
        for (int i = 0; i < name.size(); i++) {
            nameParts[i] = name.get(i);
        }
        base = roleBaseFormat.format(nameParts);
    } else {
        base = "";
    }
    // Perform the configured search and process the results
    NamingEnumeration<SearchResult> results = searchAsUser(context, user, base, filter, controls, isRoleSearchAsUser());
    if (results == null)
        // Should never happen, but just in case ...
        return list;
    HashMap<String, String> groupMap = new HashMap<>();
    try {
        while (results.hasMore()) {
            SearchResult result = results.next();
            Attributes attrs = result.getAttributes();
            if (attrs == null)
                continue;
            String dname = getDistinguishedName(context, roleBase, result);
            String name = getAttributeValue(roleName, attrs);
            if (name != null && dname != null) {
                groupMap.put(dname, name);
            }
        }
    } catch (PartialResultException ex) {
        if (!adCompat)
            throw ex;
    } finally {
        results.close();
    }
    if (containerLog.isTraceEnabled()) {
        Set<Entry<String, String>> entries = groupMap.entrySet();
        containerLog.trace("  Found " + entries.size() + " direct roles");
        for (Entry<String, String> entry : entries) {
            containerLog.trace("  Found direct role " + entry.getKey() + " -> " + entry.getValue());
        }
    }
    // if nested group search is enabled, perform searches for nested groups until no new group is found
    if (getRoleNested()) {
        // The following efficient algorithm is known as memberOf Algorithm, as described in "Practices in
        // Directory Groups". It avoids group slurping and handles cyclic group memberships as well.
        // See http://middleware.internet2.edu/dir/ for details
        Map<String, String> newGroups = new HashMap<>(groupMap);
        while (!newGroups.isEmpty()) {
            // Stores the groups we find in this iteration
            Map<String, String> newThisRound = new HashMap<>();
            for (Entry<String, String> group : newGroups.entrySet()) {
                filter = roleFormat.format(new String[] { group.getKey(), group.getValue(), group.getValue() });
                if (containerLog.isTraceEnabled()) {
                    containerLog.trace("Perform a nested group search with base " + roleBase + " and filter " + filter);
                }
                results = searchAsUser(context, user, roleBase, filter, controls, isRoleSearchAsUser());
                try {
                    while (results.hasMore()) {
                        SearchResult result = results.next();
                        Attributes attrs = result.getAttributes();
                        if (attrs == null)
                            continue;
                        String dname = getDistinguishedName(context, roleBase, result);
                        String name = getAttributeValue(roleName, attrs);
                        if (name != null && dname != null && !groupMap.keySet().contains(dname)) {
                            groupMap.put(dname, name);
                            newThisRound.put(dname, name);
                            if (containerLog.isTraceEnabled()) {
                                containerLog.trace("  Found nested role " + dname + " -> " + name);
                            }
                        }
                    }
                } catch (PartialResultException ex) {
                    if (!adCompat)
                        throw ex;
                } finally {
                    results.close();
                }
            }
            newGroups = newThisRound;
        }
    }
    list.addAll(groupMap.values());
    return list;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) PartialResultException(javax.naming.PartialResultException) CompositeName(javax.naming.CompositeName) Name(javax.naming.Name) Entry(java.util.Map.Entry) SearchControls(javax.naming.directory.SearchControls) NameParser(javax.naming.NameParser)

Example 2 with SearchControls

use of javax.naming.directory.SearchControls in project zeppelin by apache.

the class LdapRealm method rolesFor.

private Set<String> rolesFor(PrincipalCollection principals, String userNameIn, final LdapContext ldapCtx, final LdapContextFactory ldapContextFactory) throws NamingException {
    final Set<String> roleNames = new HashSet<>();
    final Set<String> groupNames = new HashSet<>();
    final String userName;
    if (getUserLowerCase()) {
        log.debug("userLowerCase true");
        userName = userNameIn.toLowerCase();
    } else {
        userName = userNameIn;
    }
    String userDn;
    if (userSearchAttributeName == null || userSearchAttributeName.isEmpty()) {
        // memberAttributeValuePrefix and memberAttributeValueSuffix 
        // were computed from memberAttributeValueTemplate
        userDn = memberAttributeValuePrefix + userName + memberAttributeValueSuffix;
    } else {
        userDn = getUserDn(userName);
    }
    // Activate paged results
    int pageSize = getPagingSize();
    if (log.isDebugEnabled()) {
        log.debug("Ldap PagingSize: " + pageSize);
    }
    int numResults = 0;
    byte[] cookie = null;
    try {
        ldapCtx.addToEnvironment(Context.REFERRAL, "ignore");
        ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        do {
            // ldapsearch -h localhost -p 33389 -D
            // uid=guest,ou=people,dc=hadoop,dc=apache,dc=org -w guest-password
            // -b dc=hadoop,dc=apache,dc=org -s sub '(objectclass=*)'
            NamingEnumeration<SearchResult> searchResultEnum = null;
            SearchControls searchControls = getGroupSearchControls();
            try {
                if (groupSearchEnableMatchingRuleInChain) {
                    searchResultEnum = ldapCtx.search(getGroupSearchBase(), String.format(MATCHING_RULE_IN_CHAIN_FORMAT, groupObjectClass, memberAttribute, userDn), searchControls);
                    while (searchResultEnum != null && searchResultEnum.hasMore()) {
                        // searchResults contains all the groups in search scope
                        numResults++;
                        final SearchResult group = searchResultEnum.next();
                        Attribute attribute = group.getAttributes().get(getGroupIdAttribute());
                        String groupName = attribute.get().toString();
                        String roleName = roleNameFor(groupName);
                        if (roleName != null) {
                            roleNames.add(roleName);
                        } else {
                            roleNames.add(groupName);
                        }
                    }
                } else {
                    searchResultEnum = ldapCtx.search(getGroupSearchBase(), "objectClass=" + groupObjectClass, searchControls);
                    while (searchResultEnum != null && searchResultEnum.hasMore()) {
                        // searchResults contains all the groups in search scope
                        numResults++;
                        final SearchResult group = searchResultEnum.next();
                        addRoleIfMember(userDn, group, roleNames, groupNames, ldapContextFactory);
                    }
                }
            } catch (PartialResultException e) {
                log.debug("Ignoring PartitalResultException");
            } finally {
                if (searchResultEnum != null) {
                    searchResultEnum.close();
                }
            }
            // Re-activate paged results
            ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
        } while (cookie != null);
    } catch (SizeLimitExceededException e) {
        log.info("Only retrieved first " + numResults + " groups due to SizeLimitExceededException.");
    } catch (IOException e) {
        log.error("Unabled to setup paged results");
    }
    // save role names and group names in session so that they can be
    // easily looked up outside of this object
    SecurityUtils.getSubject().getSession().setAttribute(SUBJECT_USER_ROLES, roleNames);
    SecurityUtils.getSubject().getSession().setAttribute(SUBJECT_USER_GROUPS, groupNames);
    if (!groupNames.isEmpty() && (principals instanceof MutablePrincipalCollection)) {
        ((MutablePrincipalCollection) principals).addAll(groupNames, getName());
    }
    if (log.isDebugEnabled()) {
        log.debug("User RoleNames: " + userName + "::" + roleNames);
    }
    return roleNames;
}
Also used : Attribute(javax.naming.directory.Attribute) SearchResult(javax.naming.directory.SearchResult) PartialResultException(javax.naming.PartialResultException) IOException(java.io.IOException) MutablePrincipalCollection(org.apache.shiro.subject.MutablePrincipalCollection) SizeLimitExceededException(javax.naming.SizeLimitExceededException) SearchControls(javax.naming.directory.SearchControls) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) PagedResultsControl(javax.naming.ldap.PagedResultsControl)

Example 3 with SearchControls

use of javax.naming.directory.SearchControls in project zeppelin by apache.

the class LdapGroupRealm method getRoleNamesForUser.

public Set<String> getRoleNamesForUser(String username, LdapContext ldapContext, String userDnTemplate) throws NamingException {
    try {
        Set<String> roleNames = new LinkedHashSet<>();
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchFilter = "(&(objectClass=groupOfNames)(member=" + userDnTemplate + "))";
        Object[] searchArguments = new Object[] { username };
        NamingEnumeration<?> answer = ldapContext.search(String.valueOf(ldapContext.getEnvironment().get("ldap.searchBase")), searchFilter, searchArguments, searchCtls);
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            if (attrs != null) {
                NamingEnumeration<?> ae = attrs.getAll();
                while (ae.hasMore()) {
                    Attribute attr = (Attribute) ae.next();
                    if (attr.getID().equals("cn")) {
                        roleNames.add((String) attr.get());
                    }
                }
            }
        }
        return roleNames;
    } catch (Exception e) {
        LOG.error("Error", e);
    }
    return new HashSet<>();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 4 with SearchControls

use of javax.naming.directory.SearchControls in project zeppelin by apache.

the class GetUserList method getUserList.

/**
   * function to extract users from LDAP
   */
public List<String> getUserList(JndiLdapRealm r, String searchText) {
    List<String> userList = new ArrayList<>();
    String userDnTemplate = r.getUserDnTemplate();
    String[] userDn = userDnTemplate.split(",", 2);
    String userDnPrefix = userDn[0].split("=")[0];
    String userDnSuffix = userDn[1];
    JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
    try {
        LdapContext ctx = CF.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userDnPrefix };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)", constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userDnPrefix) != null) {
                String currentUser = attrs.get(userDnPrefix).toString();
                userList.add(currentUser.split(":")[1].trim());
            }
        }
    } catch (Exception e) {
        LOG.error("Error retrieving User list from Ldap Realm", e);
    }
    LOG.info("UserList: " + userList);
    return userList;
}
Also used : ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) LdapContext(javax.naming.ldap.LdapContext) JndiLdapContextFactory(org.apache.shiro.realm.ldap.JndiLdapContextFactory)

Example 5 with SearchControls

use of javax.naming.directory.SearchControls in project cas by apereo.

the class CasPersonDirectoryConfiguration method ldapAttributeRepositories.

@ConditionalOnMissingBean(name = "ldapAttributeRepositories")
@Bean
@RefreshScope
public List<IPersonAttributeDao> ldapAttributeRepositories() {
    final List<IPersonAttributeDao> list = new ArrayList<>();
    final PrincipalAttributesProperties attrs = casProperties.getAuthn().getAttributeRepository();
    attrs.getLdap().forEach(ldap -> {
        if (StringUtils.isNotBlank(ldap.getBaseDn()) && StringUtils.isNotBlank(ldap.getLdapUrl())) {
            final LdaptivePersonAttributeDao ldapDao = new LdaptivePersonAttributeDao();
            LOGGER.debug("Configured LDAP attribute source for [{}] and baseDn [{}]", ldap.getLdapUrl(), ldap.getBaseDn());
            ldapDao.setConnectionFactory(Beans.newLdaptivePooledConnectionFactory(ldap));
            ldapDao.setBaseDN(ldap.getBaseDn());
            LOGGER.debug("LDAP attributes are fetched from [{}] via filter [{}]", ldap.getLdapUrl(), ldap.getUserFilter());
            ldapDao.setSearchFilter(ldap.getUserFilter());
            final SearchControls constraints = new SearchControls();
            if (ldap.getAttributes() != null && !ldap.getAttributes().isEmpty()) {
                LOGGER.debug("Configured result attribute mapping for [{}] to be [{}]", ldap.getLdapUrl(), ldap.getAttributes());
                ldapDao.setResultAttributeMapping(ldap.getAttributes());
                final String[] attributes = ldap.getAttributes().keySet().toArray(new String[ldap.getAttributes().keySet().size()]);
                constraints.setReturningAttributes(attributes);
            } else {
                LOGGER.debug("Retrieving all attributes as no explicit attribute mappings are defined for [{}]", ldap.getLdapUrl());
                constraints.setReturningAttributes(null);
            }
            if (ldap.isSubtreeSearch()) {
                LOGGER.debug("Configured subtree searching for [{}]", ldap.getLdapUrl());
                constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
            }
            constraints.setDerefLinkFlag(true);
            ldapDao.setSearchControls(constraints);
            ldapDao.setOrder(ldap.getOrder());
            LOGGER.debug("Initializing LDAP attribute source for [{}]", ldap.getLdapUrl());
            ldapDao.initialize();
            list.add(ldapDao);
        }
    });
    return list;
}
Also used : IPersonAttributeDao(org.apereo.services.persondir.IPersonAttributeDao) ArrayList(java.util.ArrayList) LdaptivePersonAttributeDao(org.apereo.services.persondir.support.ldap.LdaptivePersonAttributeDao) PrincipalAttributesProperties(org.apereo.cas.configuration.model.core.authentication.PrincipalAttributesProperties) SearchControls(javax.naming.directory.SearchControls) RefreshScope(org.springframework.cloud.context.config.annotation.RefreshScope) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Bean(org.springframework.context.annotation.Bean)

Aggregations

SearchControls (javax.naming.directory.SearchControls)59 SearchResult (javax.naming.directory.SearchResult)46 NamingException (javax.naming.NamingException)27 ArrayList (java.util.ArrayList)23 Attributes (javax.naming.directory.Attributes)20 NamingEnumeration (javax.naming.NamingEnumeration)16 Attribute (javax.naming.directory.Attribute)15 DirContext (javax.naming.directory.DirContext)13 InitialDirContext (javax.naming.directory.InitialDirContext)8 LdapContext (javax.naming.ldap.LdapContext)8 HashMap (java.util.HashMap)5 GroupNotFoundException (org.jivesoftware.openfire.group.GroupNotFoundException)5 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)5 IOException (java.io.IOException)4 HashSet (java.util.HashSet)4 LinkedHashSet (java.util.LinkedHashSet)4 Map (java.util.Map)4 PartialResultException (javax.naming.PartialResultException)4 Control (javax.naming.ldap.Control)4 PagedResultsControl (javax.naming.ldap.PagedResultsControl)4