Search in sources :

Example 31 with LdapName

use of javax.naming.ldap.LdapName in project midpoint by Evolveum.

the class BasicExpressionFunctions method composeDnWithSuffix.

/**
 * Creates a valid LDAP distinguished name from the wide range of components assuming that
 * the last component is a suffix. The method can be invoked in many ways, e.g.:
 * <p>
 * composeDn("cn","foo","o=bar")
 * composeDn(new Rdn("cn","foo"),"ou=baz,o=bar")
 * composeDn(new Rdn("cn","foo"),new LdapName("ou=baz,o=bar"))
 * composeDn("cn","foo",new LdapName("ou=baz,o=bar"))
 * <p>
 * The last element is a complete suffix represented either as String or LdapName.
 * <p>
 * Note: the DN is not normalized. The case of the attribute names and white spaces are
 * preserved.
 */
public static String composeDnWithSuffix(Object... components) throws InvalidNameException {
    if (components == null) {
        return null;
    }
    if (components.length == 0) {
        return null;
    }
    if (components.length == 1) {
        if (components[0] == null) {
            return null;
        }
        if ((components[0] instanceof String)) {
            if (StringUtils.isBlank((String) (components[0]))) {
                return null;
            } else {
                return (new LdapName((String) (components[0]))).toString();
            }
        } else if ((components[0] instanceof LdapName)) {
            return ((LdapName) (components[0])).toString();
        } else {
            throw new InvalidNameException("Invalid input to composeDn() function: expected suffix (last element) to be String or LdapName, but it was " + components[0].getClass());
        }
    }
    Object suffix = components[components.length - 1];
    if (suffix instanceof String) {
        suffix = new LdapName((String) suffix);
    }
    if (!(suffix instanceof LdapName)) {
        throw new InvalidNameException("Invalid input to composeDn() function: expected suffix (last element) to be String or LdapName, but it was " + suffix.getClass());
    }
    components[components.length - 1] = suffix;
    return composeDn(components);
}
Also used : InvalidNameException(javax.naming.InvalidNameException) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) LdapName(javax.naming.ldap.LdapName)

Example 32 with LdapName

use of javax.naming.ldap.LdapName in project zeppelin by apache.

the class LdapRealm method addRoleIfMember.

private void addRoleIfMember(final String userDn, final SearchResult group, final Set<String> roleNames, final Set<String> groupNames, final LdapContextFactory ldapContextFactory) throws NamingException {
    NamingEnumeration<? extends Attribute> attributeEnum = null;
    NamingEnumeration<?> ne = null;
    try {
        LdapName userLdapDn = new LdapName(userDn);
        Attribute attribute = group.getAttributes().get(getGroupIdAttribute());
        String groupName = attribute.get().toString();
        attributeEnum = group.getAttributes().getAll();
        while (attributeEnum.hasMore()) {
            final Attribute attr = attributeEnum.next();
            if (!memberAttribute.equalsIgnoreCase(attr.getID())) {
                continue;
            }
            ne = attr.getAll();
            while (ne.hasMore()) {
                String attrValue = ne.next().toString();
                if (memberAttribute.equalsIgnoreCase(MEMBER_URL)) {
                    boolean dynamicGroupMember = isUserMemberOfDynamicGroup(userLdapDn, attrValue, ldapContextFactory);
                    if (dynamicGroupMember) {
                        groupNames.add(groupName);
                        String roleName = roleNameFor(groupName);
                        if (roleName != null) {
                            roleNames.add(roleName);
                        } else {
                            roleNames.add(groupName);
                        }
                    }
                } else {
                    // posix groups' members don' include the entire dn
                    if (groupObjectClass.equalsIgnoreCase(POSIX_GROUP)) {
                        attrValue = memberDn(attrValue);
                    }
                    if (userLdapDn.equals(new LdapName(attrValue))) {
                        groupNames.add(groupName);
                        String roleName = roleNameFor(groupName);
                        if (roleName != null) {
                            roleNames.add(roleName);
                        } else {
                            roleNames.add(groupName);
                        }
                        break;
                    }
                }
            }
        }
    } finally {
        try {
            if (attributeEnum != null) {
                attributeEnum.close();
            }
        } finally {
            if (ne != null) {
                ne.close();
            }
        }
    }
}
Also used : Attribute(javax.naming.directory.Attribute) LdapName(javax.naming.ldap.LdapName)

Example 33 with LdapName

use of javax.naming.ldap.LdapName in project zeppelin by apache.

the class LdapRealm method isUserMemberOfDynamicGroup.

boolean isUserMemberOfDynamicGroup(LdapName userLdapDn, String memberUrl, final LdapContextFactory ldapContextFactory) throws NamingException {
    // ldap://host:port/dn?attributes?scope?filter?extensions
    if (memberUrl == null) {
        return false;
    }
    String[] tokens = memberUrl.split("\\?");
    if (tokens.length < 4) {
        return false;
    }
    String searchBaseString = tokens[0].substring(tokens[0].lastIndexOf('/') + 1);
    String searchScope = tokens[2];
    String searchFilter = tokens[3];
    LdapName searchBaseDn = new LdapName(searchBaseString);
    // do scope test
    if ("base".equalsIgnoreCase(searchScope)) {
        LOGGER.debug("DynamicGroup SearchScope base");
        return false;
    }
    if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) {
        return false;
    }
    if ("one".equalsIgnoreCase(searchScope) && (userLdapDn.size() != searchBaseDn.size() - 1)) {
        LOGGER.debug("DynamicGroup SearchScope one");
        return false;
    }
    // search for the filter, substituting base with userDn
    // search for base_dn=userDn, scope=base, filter=filter
    LdapContext systemLdapCtx;
    systemLdapCtx = ldapContextFactory.getSystemLdapContext();
    NamingEnumeration<SearchResult> searchResultEnum = null;
    try {
        searchResultEnum = systemLdapCtx.search(userLdapDn, searchFilter, "sub".equalsIgnoreCase(searchScope) ? SUBTREE_SCOPE : ONELEVEL_SCOPE);
        if (searchResultEnum.hasMore()) {
            return true;
        }
    } finally {
        try {
            if (searchResultEnum != null) {
                searchResultEnum.close();
            }
        } finally {
            LdapUtils.closeContext(systemLdapCtx);
        }
    }
    return false;
}
Also used : SearchResult(javax.naming.directory.SearchResult) LdapContext(javax.naming.ldap.LdapContext) LdapName(javax.naming.ldap.LdapName)

Example 34 with LdapName

use of javax.naming.ldap.LdapName in project Openfire by igniterealtime.

the class LdapGroupProvider method getGroupByDN.

/**
 * Reads the group with the given DN
 *
 * @param groupDN         the absolute DN of the group
 * @param membersToIgnore A mutable set of DNs and/or UIDs (for Posix mode) to ignore. This set will be
 *                        filled with visited DNs. If flatten of hierarchies of groups is active
 *                        ({@link LdapManager#isFlattenNestedGroups()}, this will prevent endless loops
 *                        for cyclic hierarchies.
 * @return A group (never null)
 * @throws NamingException When a group can't be read from LDAP.
 */
private Group getGroupByDN(LdapName groupDN, Set<String> membersToIgnore) throws NamingException {
    LdapContext ctx = null;
    try {
        LdapName baseDN;
        Name relativeDN;
        if (manager.getAlternateBaseDN() != null && groupDN.startsWith(manager.getAlternateBaseDN())) {
            baseDN = manager.getAlternateBaseDN();
        } else if (groupDN.startsWith(manager.getBaseDN())) {
            baseDN = manager.getBaseDN();
        } else {
            throw new IllegalArgumentException("GroupDN does not match any baseDN");
        }
        relativeDN = groupDN.getSuffix(baseDN.size());
        membersToIgnore.add(groupDN.toString());
        // Load record.
        ctx = manager.getContext(baseDN);
        Attributes attrs = ctx.getAttributes(relativeDN, standardAttributes);
        return processGroup(ctx, attrs, membersToIgnore);
    } finally {
        try {
            if (ctx != null) {
                ctx.setRequestControls(null);
                ctx.close();
            }
        } catch (Exception ex) {
            Log.debug("An exception was ignored while trying to close the Ldap context after trying to get a group.", ex);
        }
    }
}
Also used : Attributes(javax.naming.directory.Attributes) LdapContext(javax.naming.ldap.LdapContext) NamingException(javax.naming.NamingException) GroupNotFoundException(org.jivesoftware.openfire.group.GroupNotFoundException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) LdapName(javax.naming.ldap.LdapName) LdapName(javax.naming.ldap.LdapName) Name(javax.naming.Name)

Example 35 with LdapName

use of javax.naming.ldap.LdapName in project Openfire by igniterealtime.

the class LdapGroupProvider method getGroupNames.

@Override
public Collection<String> getGroupNames(JID user) {
    // Get DN of specified user
    XMPPServer server = XMPPServer.getInstance();
    String username;
    if (!manager.isPosixMode()) {
        // Check if the user exists (only if user is a local user)
        if (!server.isLocal(user)) {
            return Collections.emptyList();
        }
        username = JID.unescapeNode(user.getNode());
        try {
            final String relativePart = Arrays.stream(manager.findUserRDN(username)).map(Rdn::toString).collect(Collectors.joining(","));
            username = relativePart + "," + manager.getUsersBaseDN(username);
        } catch (Exception e) {
            Log.error("Could not find user in LDAP " + username);
            return Collections.emptyList();
        }
    } else {
        username = server.isLocal(user) ? JID.unescapeNode(user.getNode()) : user.toString();
    }
    // Do nothing if the user is empty or null
    if (username == null || "".equals(username)) {
        return Collections.emptyList();
    }
    Set<String> groupNames = new LinkedHashSet<>(search(manager.getGroupMemberField(), username));
    if (manager.isFlattenNestedGroups()) {
        // search groups that contain the given groups
        Set<String> checkedGroups = new HashSet<>();
        Deque<String> todo = new ArrayDeque<>(groupNames);
        String group;
        while (null != (group = todo.pollFirst())) {
            if (checkedGroups.contains(group)) {
                continue;
            }
            checkedGroups.add(group);
            try {
                // get the DN of the group
                LdapName groupDN = manager.findGroupAbsoluteDN(group);
                if (manager.isPosixMode()) {
                    // in posix mode we need to search for the "uid" of the group.
                    List<String> uids = manager.retrieveAttributeOf(manager.getUsernameField(), groupDN);
                    if (uids.isEmpty()) {
                        // group not there or has not the "uid" attribute
                        continue;
                    }
                    group = uids.get(0);
                } else {
                    group = groupDN.toString();
                }
                // search for groups that have the given group (DN normal, UID posix) as member
                Collection<String> containingGroupNames = search(manager.getGroupMemberField(), group);
                // add the found groups to the result and to the groups to be checked transitively
                todo.addAll(containingGroupNames);
                groupNames.addAll(containingGroupNames);
            } catch (Exception e) {
                Log.warn("Error looking up group: {}", group);
            }
        }
    }
    return groupNames;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) XMPPServer(org.jivesoftware.openfire.XMPPServer) NamingException(javax.naming.NamingException) GroupNotFoundException(org.jivesoftware.openfire.group.GroupNotFoundException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) ArrayDeque(java.util.ArrayDeque) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) LdapName(javax.naming.ldap.LdapName)

Aggregations

LdapName (javax.naming.ldap.LdapName)86 Rdn (javax.naming.ldap.Rdn)43 InvalidNameException (javax.naming.InvalidNameException)27 Attribute (javax.naming.directory.Attribute)18 NamingException (javax.naming.NamingException)16 Attributes (javax.naming.directory.Attributes)12 SearchResult (javax.naming.directory.SearchResult)10 Test (org.junit.Test)10 IOException (java.io.IOException)6 X509Certificate (java.security.cert.X509Certificate)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)5 Test (org.junit.jupiter.api.Test)5 HashSet (java.util.HashSet)4 List (java.util.List)4 NoSuchElementException (java.util.NoSuchElementException)4 TreeSet (java.util.TreeSet)4 SearchControls (javax.naming.directory.SearchControls)4 SSLException (javax.net.ssl.SSLException)4