Search in sources :

Example 96 with Attributes

use of javax.naming.directory.Attributes in project vespa by vespa-engine.

the class DnsNameResolver method lookupName.

private Optional<String> lookupName(String name, Type type) throws NamingException {
    DirContext ctx = new InitialDirContext();
    Attributes attributes = ctx.getAttributes("dns:/" + name, new String[] { type.value });
    Optional<Attribute> attribute = Optional.ofNullable(attributes.get(type.value));
    if (attribute.isPresent()) {
        return Optional.ofNullable(attribute.get().get()).map(Object::toString);
    }
    return Optional.empty();
}
Also used : Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 97 with Attributes

use of javax.naming.directory.Attributes in project vespa by vespa-engine.

the class IPAddressVerifier method reverseLookUp.

String reverseLookUp(String ipAddress) throws NamingException {
    Hashtable<String, String> env = new Hashtable<>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    DirContext ctx = new InitialDirContext(env);
    Attributes attrs = ctx.getAttributes(ipAddress, new String[] { "PTR" });
    for (NamingEnumeration<? extends Attribute> ae = attrs.getAll(); ae.hasMoreElements(); ) {
        Attribute attr = ae.next();
        Enumeration<?> vals = attr.getAll();
        if (vals.hasMoreElements()) {
            String hostname = vals.nextElement().toString();
            ctx.close();
            return hostname.substring(0, hostname.length() - 1);
        }
    }
    ctx.close();
    return "";
}
Also used : Attribute(javax.naming.directory.Attribute) Hashtable(java.util.Hashtable) Attributes(javax.naming.directory.Attributes) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 98 with Attributes

use of javax.naming.directory.Attributes in project activemq-artemis by apache.

the class LegacyLDAPSecuritySettingPlugin method processSearchResult.

private void processSearchResult(Map<String, Set<Role>> securityRoles, SearchResult searchResult) throws NamingException {
    Attributes attrs = searchResult.getAttributes();
    if (attrs == null || attrs.size() == 0) {
        return;
    }
    LdapName searchResultLdapName = new LdapName(searchResult.getName());
    logger.debug("LDAP search result : " + searchResultLdapName);
    String permissionType = null;
    String destination = null;
    String destinationType = "unknown";
    for (Rdn rdn : searchResultLdapName.getRdns()) {
        if (rdn.getType().equals("cn")) {
            logger.debug("\tPermission type: " + rdn.getValue());
            permissionType = rdn.getValue().toString();
        }
        if (rdn.getType().equals("uid")) {
            logger.debug("\tDestination name: " + rdn.getValue());
            destination = rdn.getValue().toString();
        }
        if (rdn.getType().equals("ou")) {
            String rawDestinationType = rdn.getValue().toString();
            if (rawDestinationType.toLowerCase().contains("queue")) {
                destinationType = "queue";
            } else if (rawDestinationType.toLowerCase().contains("topic")) {
                destinationType = "topic";
            }
            logger.debug("\tDestination type: " + destinationType);
        }
    }
    logger.debug("\tAttributes: " + attrs);
    Attribute attr = attrs.get(roleAttribute);
    NamingEnumeration<?> e = attr.getAll();
    Set<Role> roles = securityRoles.get(destination);
    boolean exists = false;
    if (roles == null) {
        roles = new HashSet<>();
    } else {
        exists = true;
    }
    while (e.hasMore()) {
        String value = (String) e.next();
        LdapName ldapname = new LdapName(value);
        Rdn rdn = ldapname.getRdn(ldapname.size() - 1);
        String roleName = rdn.getValue().toString();
        logger.debug("\tRole name: " + roleName);
        Role role = new Role(roleName, // send
        permissionType.equalsIgnoreCase(writePermissionValue), // consume
        permissionType.equalsIgnoreCase(readPermissionValue), // createDurableQueue
        permissionType.equalsIgnoreCase(adminPermissionValue), // deleteDurableQueue
        permissionType.equalsIgnoreCase(adminPermissionValue), // createNonDurableQueue
        permissionType.equalsIgnoreCase(adminPermissionValue), // deleteNonDurableQueue
        permissionType.equalsIgnoreCase(adminPermissionValue), // manage - there is no permission from ActiveMQ 5.x that corresponds to this
        false, // browse
        permissionType.equalsIgnoreCase(readPermissionValue), // createAddress
        permissionType.equalsIgnoreCase(adminPermissionValue), // deleteAddress
        permissionType.equalsIgnoreCase(adminPermissionValue));
        roles.add(role);
    }
    if (!exists) {
        securityRoles.put(destination, roles);
    }
}
Also used : Role(org.apache.activemq.artemis.core.security.Role) Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) Rdn(javax.naming.ldap.Rdn) LdapName(javax.naming.ldap.LdapName)

Example 99 with Attributes

use of javax.naming.directory.Attributes in project tomcat70 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
 *
 * @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<String>();
    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");
        for (int i = 0; i < list.size(); i++) containerLog.trace("  Found user internal role " + list.get(i));
    }
    // 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<String, String>();
    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<String, String>(groupMap);
        while (!newGroups.isEmpty()) {
            // Stores the groups we find in this iteration
            Map<String, String> newThisRound = new HashMap<String, String>();
            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 100 with Attributes

use of javax.naming.directory.Attributes in project tomcat70 by apache.

the class JNDIRealm method getUserBySearch.

/**
 * Search the directory to return a User object containing
 * information about the user with the specified username, if
 * found in the directory; otherwise return <code>null</code>.
 *
 * @param context The directory context
 * @param username The username
 * @param attrIds String[]containing names of attributes to retrieve.
 *
 * @exception NamingException if a directory server error occurs
 */
protected User getUserBySearch(DirContext context, String username, String[] attrIds) throws NamingException {
    if (username == null || userSearchFormat == null)
        return null;
    // Form the search filter
    String filter = userSearchFormat.format(new String[] { username });
    // Set up the search controls
    SearchControls constraints = new SearchControls();
    if (userSubtree) {
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    } else {
        constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    }
    constraints.setCountLimit(sizeLimit);
    constraints.setTimeLimit(timeLimit);
    // Specify the attributes to be retrieved
    if (attrIds == null)
        attrIds = new String[0];
    constraints.setReturningAttributes(attrIds);
    NamingEnumeration<SearchResult> results = context.search(userBase, filter, constraints);
    try {
        // Fail if no entries found
        try {
            if (results == null || !results.hasMore()) {
                return null;
            }
        } catch (PartialResultException ex) {
            if (!adCompat)
                throw ex;
            else
                return null;
        }
        // Get result for the first entry found
        SearchResult result = results.next();
        // Check no further entries were found
        try {
            if (results.hasMore()) {
                if (containerLog.isInfoEnabled())
                    containerLog.info("username " + username + " has multiple entries");
                return null;
            }
        } catch (PartialResultException ex) {
            if (!adCompat)
                throw ex;
        }
        String dn = getDistinguishedName(context, userBase, result);
        if (containerLog.isTraceEnabled())
            containerLog.trace("  entry found for " + username + " with dn " + dn);
        // Get the entry's attributes
        Attributes attrs = result.getAttributes();
        if (attrs == null)
            return null;
        // Retrieve value of userPassword
        String password = null;
        if (userPassword != null)
            password = getAttributeValue(userPassword, attrs);
        String userRoleAttrValue = null;
        if (userRoleAttribute != null) {
            userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs);
        }
        // Retrieve values of userRoleName attribute
        ArrayList<String> roles = null;
        if (userRoleName != null)
            roles = addAttributeValues(userRoleName, attrs, roles);
        return new User(username, dn, password, roles, userRoleAttrValue);
    } finally {
        if (results != null) {
            results.close();
        }
    }
}
Also used : Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) PartialResultException(javax.naming.PartialResultException)

Aggregations

Attributes (javax.naming.directory.Attributes)252 Attribute (javax.naming.directory.Attribute)135 SearchResult (javax.naming.directory.SearchResult)87 NamingException (javax.naming.NamingException)84 BasicAttributes (javax.naming.directory.BasicAttributes)72 ArrayList (java.util.ArrayList)61 BasicAttribute (javax.naming.directory.BasicAttribute)56 SearchControls (javax.naming.directory.SearchControls)55 DirContext (javax.naming.directory.DirContext)49 NamingEnumeration (javax.naming.NamingEnumeration)44 Test (org.junit.Test)34 InitialDirContext (javax.naming.directory.InitialDirContext)32 LdapContext (javax.naming.ldap.LdapContext)29 HashMap (java.util.HashMap)25 InitialLdapContext (javax.naming.ldap.InitialLdapContext)24 Hashtable (java.util.Hashtable)20 HashSet (java.util.HashSet)18 Map (java.util.Map)17 IOException (java.io.IOException)16 Identity (org.olat.core.id.Identity)16