Search in sources :

Example 21 with Attribute

use of org.forgerock.opendj.ldap.Attribute in project OpenAM by OpenRock.

the class DJLDAPv3Repo method search.

/**
     * Performs a search in the directory based on the provided parameters.
     * Using the pattern and avPairs parameters an example search filter would look something like:
     * <code>(&(|(attr1=value1)(attr2=value2))(searchAttr=pattern)(objectclassfilter))</code>.
     *
     * @param token Not used.
     * @param type The type of the identity.
     * @param crestQuery Either a string, coming from something like the CREST endpoint _queryId or a fully
     *                        fledged query filter, coming from a CREST endpoint's _queryFilter
     * @param maxTime The time limit for this search (in seconds). When maxTime &lt; 1, the default time limit will
     * be used.
     * @param maxResults The number of maximum results we should receive for this search. When maxResults &lt; 1 the
     * default sizelimit will be used.
     * @param returnAttrs The attributes that should be returned from the "search hits".
     * @param returnAllAttrs <code>true</code> if all user attribute should be returned.
     * @param filterOp When avPairs is provided, this logical operation will be used between them. Use
     * {@link IdRepo#AND_MOD} or {@link IdRepo#OR_MOD}.
     * @param avPairs Attribute-value pairs based on the search should be performed.
     * @param recursive Deprecated setting, not used.
     * @return The search results based on the provided parameters.
     * @throws IdRepoException Shouldn't be thrown as the returned RepoSearchResults will contain the error code.
     */
@Override
public RepoSearchResults search(SSOToken token, IdType type, CrestQuery crestQuery, int maxTime, int maxResults, Set<String> returnAttrs, boolean returnAllAttrs, int filterOp, Map<String, Set<String>> avPairs, boolean recursive) throws IdRepoException {
    if (DEBUG.messageEnabled()) {
        DEBUG.message("search invoked with type: " + type + " crestQuery: " + crestQuery + " avPairs: " + avPairs + " maxTime: " + maxTime + " maxResults: " + maxResults + " returnAttrs: " + returnAttrs + " returnAllAttrs: " + returnAllAttrs + " filterOp: " + filterOp + " recursive: " + recursive);
    }
    DN baseDN = getBaseDN(type);
    // Recursive is a deprecated setting on IdSearchControl, hence we should use the searchscope defined in the
    // datastore configuration.
    SearchScope scope = defaultScope;
    String searchAttr = getSearchAttribute(type);
    String[] attrs;
    Filter first;
    if (crestQuery.hasQueryId()) {
        first = Filter.valueOf(searchAttr + "=" + crestQuery.getQueryId());
    } else {
        first = crestQuery.getQueryFilter().accept(new LdapFromJsonQueryFilterVisitor(), null);
    }
    Filter filter = Filter.and(first, getObjectClassFilter(type));
    Filter tempFilter = constructFilter(filterOp, avPairs);
    if (tempFilter != null) {
        filter = Filter.and(tempFilter, filter);
    }
    if (returnAllAttrs || (returnAttrs != null && returnAttrs.contains("*"))) {
        Set<String> predefinedAttrs = getDefinedAttributes(type);
        attrs = predefinedAttrs.toArray(new String[predefinedAttrs.size()]);
        returnAllAttrs = true;
    } else if (returnAttrs != null && !returnAttrs.isEmpty()) {
        returnAttrs.add(searchAttr);
        attrs = returnAttrs.toArray(new String[returnAttrs.size()]);
    } else {
        attrs = new String[] { searchAttr };
    }
    SearchRequest searchRequest = LDAPRequests.newSearchRequest(baseDN, scope, filter, attrs);
    searchRequest.setSizeLimit(maxResults < 1 ? defaultSizeLimit : maxResults);
    searchRequest.setTimeLimit(maxTime < 1 ? defaultTimeLimit : maxTime);
    Connection conn = null;
    Set<String> names = new HashSet<String>();
    Map<String, Map<String, Set<String>>> entries = new HashMap<String, Map<String, Set<String>>>();
    int errorCode = RepoSearchResults.SUCCESS;
    try {
        conn = connectionFactory.getConnection();
        ConnectionEntryReader reader = conn.search(searchRequest);
        while (reader.hasNext()) {
            Map<String, Set<String>> attributes = new HashMap<String, Set<String>>();
            if (reader.isEntry()) {
                SearchResultEntry entry = reader.readEntry();
                String name = entry.parseAttribute(searchAttr).asString();
                names.add(name);
                if (returnAllAttrs) {
                    for (Attribute attribute : entry.getAllAttributes()) {
                        LDAPUtils.addAttributeToMapAsString(attribute, attributes);
                    }
                    entries.put(name, attributes);
                } else if (returnAttrs != null && !returnAttrs.isEmpty()) {
                    for (String attr : returnAttrs) {
                        Attribute attribute = entry.getAttribute(attr);
                        if (attribute != null) {
                            LDAPUtils.addAttributeToMapAsString(attribute, attributes);
                        }
                    }
                    entries.put(name, attributes);
                } else {
                //there is no attribute to return, don't populate the entries map
                }
            } else {
                //ignore search result references
                reader.readReference();
            }
        }
    } catch (LdapException ere) {
        ResultCode resultCode = ere.getResult().getResultCode();
        if (resultCode.equals(ResultCode.NO_SUCH_OBJECT)) {
            return new RepoSearchResults(new HashSet<String>(0), RepoSearchResults.SUCCESS, Collections.EMPTY_MAP, type);
        } else if (resultCode.equals(ResultCode.TIME_LIMIT_EXCEEDED) || resultCode.equals(ResultCode.CLIENT_SIDE_TIMEOUT)) {
            errorCode = RepoSearchResults.TIME_LIMIT_EXCEEDED;
        } else if (resultCode.equals(ResultCode.SIZE_LIMIT_EXCEEDED)) {
            errorCode = RepoSearchResults.SIZE_LIMIT_EXCEEDED;
        } else {
            DEBUG.error("Unexpected error occurred during search", ere);
            errorCode = resultCode.intValue();
        }
    } catch (SearchResultReferenceIOException srrioe) {
        //should never ever happen...
        DEBUG.error("Got reference instead of entry", srrioe);
        throw newIdRepoException(IdRepoErrorCode.SEARCH_FAILED, CLASS_NAME);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    return new RepoSearchResults(names, errorCode, entries, type);
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) Set(java.util.Set) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) CollectionUtils.asSet(org.forgerock.openam.utils.CollectionUtils.asSet) LdapFromJsonQueryFilterVisitor(org.forgerock.openam.ldap.LdapFromJsonQueryFilterVisitor) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) Connection(org.forgerock.opendj.ldap.Connection) DN(org.forgerock.opendj.ldap.DN) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Filter(org.forgerock.opendj.ldap.Filter) SearchScope(org.forgerock.opendj.ldap.SearchScope) RepoSearchResults(com.sun.identity.idm.RepoSearchResults) Map(java.util.Map) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 22 with Attribute

use of org.forgerock.opendj.ldap.Attribute in project OpenAM by OpenRock.

the class DJLDAPv3Repo method setAttributes.

/**
     * Sets the provided attributes (string or binary) for the given identity. The following steps will be performed
     * prior to modification:
     * <ul>
     *  <li>The password will be encoded in case we are dealing with AD.</li>
     *  <li>Anything related to undefined attributes will be ignored.</li>
     *  <li>If the attribute map contains the default status attribute, then it will be converted to the status value
     *      specified in the configuration.</li>
     *  <li>In case changeOCs is set to <code>true</code>, the method will traverse through all the defined
     *      objectclasses to see if there is any attribute in the attributes map that is defined by that objectclass.
     *      These objectclasses will be collected and will be part of the modificationset with the other changes.</li>
     * </ul>
     * The attributes will be translated to modifications based on the followings:
     * <ul>
     *  <li>If the attribute has no values in the map, it will be considered as an attribute DELETE.</li>
     *  <li>In any other case based on the value of isAdd parameter, it will be either ADD, or REPLACE.</li>
     * </ul>
     *
     * @param token Not used.
     * @param type The type of the identity.
     * @param name The name of the identity.
     * @param attributes The attributes that needs to be set for the entry.
     * @param isAdd <code>true</code> if the attributes should be ADDed, <code>false</code> if the attributes should be
     * REPLACEd instead.
     * @param isString Whether the provided attributes are in string or binary format.
     * @param changeOCs Whether the module should adjust the objectclasses for the entry or not.
     * @throws IdRepoException Can be thrown in the following cases:
     * <ul>
     *  <li>the identity cannot be found,</li>
     *  <li>there was a problem while retrieving the current user status from the directory (AD),</li>
     *  <li>there are no modifications to actually perform,</li>
     *  <li>there was an error while retrieving the objectClass attribute,</li>
     *  <li>there was an error while trying to read the directory schema,</li>
     *  <li>there was an error while trying to perform the modifications.</li>
     * </ul>
     */
private void setAttributes(SSOToken token, IdType type, String name, Map attributes, boolean isAdd, boolean isString, boolean changeOCs) throws IdRepoException {
    ModifyRequest modifyRequest = LDAPRequests.newModifyRequest(getDN(type, name));
    attributes = removeUndefinedAttributes(type, attributes);
    if (type.equals(IdType.USER)) {
        Object status = attributes.get(DEFAULT_USER_STATUS_ATTR);
        if (status != null && !attributes.containsKey(userStatusAttr)) {
            String value = null;
            if (status instanceof Set) {
                value = ((Set<String>) status).iterator().next();
            } else if (status instanceof byte[][]) {
                value = new String(((byte[][]) status)[0], Charset.forName("UTF-8"));
            }
            value = helper.getStatus(this, name, !STATUS_INACTIVE.equals(value), userStatusAttr, activeValue, inactiveValue);
            attributes.remove(DEFAULT_USER_STATUS_ATTR);
            if (isString) {
                attributes.put(userStatusAttr, asSet(value));
            } else {
                byte[][] binValue = new byte[1][];
                binValue[0] = value.getBytes(Charset.forName("UTF-8"));
                attributes.put(userStatusAttr, binValue);
            }
        }
    }
    for (Map.Entry<String, Object> entry : (Set<Map.Entry<String, Object>>) attributes.entrySet()) {
        Object values = entry.getValue();
        String attrName = entry.getKey();
        Attribute attr = new LinkedAttribute(attrName);
        if (AD_UNICODE_PWD_ATTR.equalsIgnoreCase(attrName)) {
            if (values instanceof byte[][]) {
                attr.add(ByteString.valueOfBytes(helper.encodePassword(IdType.USER, (byte[][]) values)));
            } else {
                attr.add(ByteString.valueOfBytes(helper.encodePassword(IdType.USER, (Set) values)));
            }
        } else if (values instanceof byte[][]) {
            for (byte[] bytes : (byte[][]) values) {
                attr.add(ByteString.valueOfBytes(bytes));
            }
        } else if (values instanceof Set) {
            for (String value : (Set<String>) values) {
                attr.add(value);
            }
        }
        if (attr.isEmpty()) {
            modifyRequest.addModification(new Modification(ModificationType.REPLACE, attr));
        } else {
            modifyRequest.addModification(new Modification(isAdd ? ModificationType.ADD : ModificationType.REPLACE, attr));
        }
    }
    if (modifyRequest.getModifications().isEmpty()) {
        if (DEBUG.messageEnabled()) {
            DEBUG.message("setAttributes: there are no modifications to perform");
        }
        throw newIdRepoException(IdRepoErrorCode.ILLEGAL_ARGUMENTS);
    }
    if (type.equals(IdType.USER) && changeOCs) {
        Set<String> missingOCs = new CaseInsensitiveHashSet();
        Map<String, Set<String>> attrs = getAttributes(token, type, name, asSet(OBJECT_CLASS_ATTR));
        Set<String> ocs = attrs.get(OBJECT_CLASS_ATTR);
        //to missingOCs
        if (ocs != null) {
            missingOCs.addAll(getObjectClasses(type));
            missingOCs.removeAll(ocs);
        }
        //if the missingOCs is not empty (i.e. there are objectclasses that are not present in the entry yet)
        if (!missingOCs.isEmpty()) {
            Object obj = attributes.get(OBJECT_CLASS_ATTR);
            //if the API user has also added some of his objectclasses, then let's remove those from missingOCs
            if (obj != null && obj instanceof Set) {
                missingOCs.removeAll((Set<String>) obj);
            }
            //for every single objectclass that needs to be added, let's check if they contain an attribute that we
            //wanted to add to the entry.
            Set<String> newOCs = new HashSet<String>(2);
            Schema dirSchema = getSchema();
            for (String objectClass : missingOCs) {
                try {
                    ObjectClass oc = dirSchema.getObjectClass(objectClass);
                    //we should never add new structural objectclasses, see RFC 4512
                    if (!oc.getObjectClassType().equals(ObjectClassType.STRUCTURAL)) {
                        for (String attrName : (Set<String>) attributes.keySet()) {
                            //before we start to add too many objectclasses here...
                            if (!attrName.equalsIgnoreCase(OBJECT_CLASS_ATTR) && oc.isRequiredOrOptional(dirSchema.getAttributeType(attrName))) {
                                newOCs.add(objectClass);
                                break;
                            }
                        }
                    }
                } catch (UnknownSchemaElementException usee) {
                    if (DEBUG.warningEnabled()) {
                        DEBUG.warning("Unable to find a schema element: " + usee.getMessage());
                    }
                }
            }
            missingOCs = newOCs;
            //it is possible that none of the missing objectclasses are actually covering any new attributes
            if (!missingOCs.isEmpty()) {
                //based on these let's add the extra objectclasses to the modificationset
                modifyRequest.addModification(new Modification(ModificationType.ADD, new LinkedAttribute(OBJECT_CLASS_ATTR, missingOCs)));
            }
        }
    }
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        conn.modify(modifyRequest);
    } catch (LdapException ere) {
        DEBUG.error("An error occured while setting attributes for identity: " + name, ere);
        handleErrorResult(ere);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
}
Also used : Modification(org.forgerock.opendj.ldap.Modification) Set(java.util.Set) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) CollectionUtils.asSet(org.forgerock.openam.utils.CollectionUtils.asSet) ObjectClass(org.forgerock.opendj.ldap.schema.ObjectClass) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) UnknownSchemaElementException(org.forgerock.opendj.ldap.schema.UnknownSchemaElementException) Schema(org.forgerock.opendj.ldap.schema.Schema) Connection(org.forgerock.opendj.ldap.Connection) ModifyRequest(org.forgerock.opendj.ldap.requests.ModifyRequest) ByteString(org.forgerock.opendj.ldap.ByteString) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) Map(java.util.Map) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) LdapException(org.forgerock.opendj.ldap.LdapException) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 23 with Attribute

use of org.forgerock.opendj.ldap.Attribute in project OpenAM by OpenRock.

the class DJLDAPv3Repo method getGroupMemberships.

/**
     * Returns the group membership informations for this given user. In case the memberOf attribute is configured,
     * this will try to query the user entry and return the group DNs found in the memberOf attribute. Otherwise a
     * search request will be issued using the uniqueMember attribute looking for matches with the user DN.
     *
     * @param dn The DN of the user identity.
     * @return The DNs of the groups that the provided user is member of.
     * @throws IdRepoException If there was an error while retrieving the group membership information.
     */
private Set<String> getGroupMemberships(String dn) throws IdRepoException {
    Set<String> results = new HashSet<String>();
    if (memberOfAttr == null) {
        Filter filter = Filter.and(groupSearchFilter, Filter.equality(uniqueMemberAttr, dn));
        SearchRequest searchRequest = LDAPRequests.newSearchRequest(getBaseDN(IdType.GROUP), defaultScope, filter, DN_ATTR);
        searchRequest.setTimeLimit(defaultTimeLimit);
        searchRequest.setSizeLimit(defaultSizeLimit);
        Connection conn = null;
        try {
            conn = connectionFactory.getConnection();
            ConnectionEntryReader reader = conn.search(searchRequest);
            while (reader.hasNext()) {
                if (reader.isEntry()) {
                    results.add(reader.readEntry().getName().toString());
                } else {
                    //ignore search result references
                    reader.readReference();
                }
            }
        } catch (LdapException ere) {
            DEBUG.error("An error occurred while trying to retrieve group memberships for " + dn + " using " + uniqueMemberAttr, ere);
            handleErrorResult(ere);
        } catch (SearchResultReferenceIOException srrioe) {
            //should never ever happen...
            DEBUG.error("Got reference instead of entry", srrioe);
            throw newIdRepoException(IdRepoErrorCode.SEARCH_FAILED, CLASS_NAME);
        } finally {
            IOUtils.closeIfNotNull(conn);
        }
    } else {
        Connection conn = null;
        try {
            conn = connectionFactory.getConnection();
            SearchResultEntry entry = conn.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(dn, memberOfAttr));
            Attribute attr = entry.getAttribute(memberOfAttr);
            if (attr != null) {
                results.addAll(LDAPUtils.getAttributeValuesAsStringSet(attr));
            }
        } catch (LdapException ere) {
            DEBUG.error("An error occurred while trying to retrieve group memberships for " + dn + " using " + memberOfAttr + " attribute", ere);
            handleErrorResult(ere);
        } finally {
            IOUtils.closeIfNotNull(conn);
        }
    }
    return results;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Filter(org.forgerock.opendj.ldap.Filter) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 24 with Attribute

use of org.forgerock.opendj.ldap.Attribute in project ddf by codice.

the class SslLdapLoginModule method doLogin.

protected boolean doLogin() throws LoginException {
    //--------- EXTRACT USERNAME AND PASSWORD FOR LDAP LOOKUP -------------
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    try {
        callbackHandler.handle(callbacks);
    } catch (IOException ioException) {
        throw new LoginException(ioException.getMessage());
    } catch (UnsupportedCallbackException unsupportedCallbackException) {
        boolean result;
        throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
    }
    user = ((NameCallback) callbacks[0]).getName();
    if (user == null) {
        return false;
    }
    user = user.trim();
    validateUsername(user);
    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
    // this method.
    if ("none".equalsIgnoreCase(getBindMethod()) && (tmpPassword != null)) {
        LOGGER.debug("Changing from authentication = none to simple since user or password was specified.");
        // default to simple so that the provided user/password will get checked
        setBindMethod(DEFAULT_AUTHENTICATION);
    }
    if (tmpPassword == null) {
        tmpPassword = new char[0];
    }
    //---------------------------------------------------------------------
    // RESET OBJECT STATE AND DECLARE LOCAL VARS
    principals = new HashSet<>();
    Connection connection;
    String userDn;
    //------------- CREATE CONNECTION #1 ----------------------------------
    try {
        connection = ldapConnectionFactory.getConnection();
    } catch (LdapException e) {
        LOGGER.info("Unable to get LDAP Connection from factory.", e);
        return false;
    }
    if (connection != null) {
        try {
            //------------- BIND #1 (CONNECTION USERNAME & PASSWORD) --------------
            try {
                BindRequest request;
                switch(getBindMethod()) {
                    case "Simple":
                        request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
                        break;
                    case "SASL":
                        request = Requests.newPlainSASLBindRequest(connectionUsername, connectionPassword);
                        break;
                    case "GSSAPI SASL":
                        request = Requests.newGSSAPISASLBindRequest(connectionUsername, connectionPassword);
                        ((GSSAPISASLBindRequest) request).setRealm(realm);
                        ((GSSAPISASLBindRequest) request).setKDCAddress(kdcAddress);
                        break;
                    case "Digest MD5 SASL":
                        request = Requests.newDigestMD5SASLBindRequest(connectionUsername, connectionPassword);
                        ((DigestMD5SASLBindRequest) request).setCipher(DigestMD5SASLBindRequest.CIPHER_HIGH);
                        ((DigestMD5SASLBindRequest) request).getQOPs().clear();
                        ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_CONF);
                        ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_INT);
                        ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH);
                        if (StringUtils.isNotEmpty(realm)) {
                            ((DigestMD5SASLBindRequest) request).setRealm(realm);
                        }
                        break;
                    default:
                        request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
                        break;
                }
                BindResult bindResult = connection.bind(request);
                if (!bindResult.isSuccess()) {
                    LOGGER.debug("Bind failed");
                    return false;
                }
            } catch (LdapException e) {
                LOGGER.debug("Unable to bind to LDAP server.", e);
                return false;
            }
            //--------- SEARCH #1, FIND USER DISTINGUISHED NAME -----------
            SearchScope scope;
            if (userSearchSubtree) {
                scope = SearchScope.WHOLE_SUBTREE;
            } else {
                scope = SearchScope.SINGLE_LEVEL;
            }
            userFilter = userFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
            userFilter = userFilter.replace("\\", "\\\\");
            ConnectionEntryReader entryReader = connection.search(userBaseDN, scope, userFilter);
            try {
                if (!entryReader.hasNext()) {
                    LOGGER.info("User {} not found in LDAP.", user);
                    return false;
                }
                SearchResultEntry searchResultEntry = entryReader.readEntry();
                userDn = searchResultEntry.getName().toString();
            } catch (LdapException | SearchResultReferenceIOException e) {
                LOGGER.info("Unable to read contents of LDAP user search.", e);
                return false;
            }
        } finally {
            //------------ CLOSE CONNECTION -------------------------------
            connection.close();
        }
    } else {
        return false;
    }
    //------------- CREATE CONNECTION #2 ----------------------------------
    try {
        connection = ldapConnectionFactory.getConnection();
    } catch (LdapException e) {
        LOGGER.info("Unable to get LDAP Connection from factory.", e);
        return false;
    }
    if (connection != null) {
        // Validate user's credentials.
        try {
            BindResult bindResult = connection.bind(userDn, tmpPassword);
            if (!bindResult.isSuccess()) {
                LOGGER.info("Bind failed");
                return false;
            }
        } catch (Exception e) {
            LOGGER.info("Unable to bind user to LDAP server.", e);
            return false;
        } finally {
            //------------ CLOSE CONNECTION -------------------------------
            connection.close();
        }
        //---------- ADD USER AS PRINCIPAL --------------------------------
        principals.add(new UserPrincipal(user));
    } else {
        return false;
    }
    //-------------- CREATE CONNECTION #3 ---------------------------------
    try {
        connection = ldapConnectionFactory.getConnection();
    } catch (LdapException e) {
        LOGGER.info("Unable to get LDAP Connection from factory.", e);
        return false;
    }
    if (connection != null) {
        try {
            //----- BIND #3 (CONNECTION USERNAME & PASSWORD) --------------
            try {
                BindResult bindResult = connection.bind(connectionUsername, connectionPassword);
                if (!bindResult.isSuccess()) {
                    LOGGER.info("Bind failed");
                    return false;
                }
            } catch (LdapException e) {
                LOGGER.info("Unable to bind to LDAP server.", e);
                return false;
            }
            //--------- SEARCH #3, GET ROLES ------------------------------
            SearchScope scope;
            if (roleSearchSubtree) {
                scope = SearchScope.WHOLE_SUBTREE;
            } else {
                scope = SearchScope.SINGLE_LEVEL;
            }
            roleFilter = roleFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
            roleFilter = roleFilter.replaceAll(Pattern.quote("%dn"), Matcher.quoteReplacement(userBaseDN));
            roleFilter = roleFilter.replaceAll(Pattern.quote("%fqdn"), Matcher.quoteReplacement(userDn));
            roleFilter = roleFilter.replace("\\", "\\\\");
            ConnectionEntryReader entryReader = connection.search(roleBaseDN, scope, roleFilter, roleNameAttribute);
            SearchResultEntry entry;
            //------------- ADD ROLES AS NEW PRINCIPALS -------------------
            try {
                while (entryReader.hasNext()) {
                    entry = entryReader.readEntry();
                    Attribute attr = entry.getAttribute(roleNameAttribute);
                    for (ByteString role : attr) {
                        principals.add(new RolePrincipal(role.toString()));
                    }
                }
            } catch (Exception e) {
                boolean result;
                throw new LoginException("Can't get user " + user + " roles: " + e.getMessage());
            }
        } finally {
            //------------ CLOSE CONNECTION -------------------------------
            connection.close();
        }
    } else {
        return false;
    }
    return true;
}
Also used : Attribute(org.forgerock.opendj.ldap.Attribute) ByteString(org.forgerock.opendj.ldap.ByteString) DigestMD5SASLBindRequest(org.forgerock.opendj.ldap.requests.DigestMD5SASLBindRequest) GSSAPISASLBindRequest(org.forgerock.opendj.ldap.requests.GSSAPISASLBindRequest) BindRequest(org.forgerock.opendj.ldap.requests.BindRequest) ByteString(org.forgerock.opendj.ldap.ByteString) GSSAPISASLBindRequest(org.forgerock.opendj.ldap.requests.GSSAPISASLBindRequest) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) LdapException(org.forgerock.opendj.ldap.LdapException) Connection(org.forgerock.opendj.ldap.Connection) IOException(java.io.IOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) LdapException(org.forgerock.opendj.ldap.LdapException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) DigestMD5SASLBindRequest(org.forgerock.opendj.ldap.requests.DigestMD5SASLBindRequest) SearchScope(org.forgerock.opendj.ldap.SearchScope) LoginException(javax.security.auth.login.LoginException) BindResult(org.forgerock.opendj.ldap.responses.BindResult) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 25 with Attribute

use of org.forgerock.opendj.ldap.Attribute in project OpenAM by OpenRock.

the class AMCRLStore method getCRLByLdapURI.

/**
     * It gets the new CRL from ldap server.
     * If it is ldap URI, the URI has to be a dn that can be accessed
     * with ldap anonymous bind.
     * (example : ldap://server:port/uid=ca,o=company.com)
     * This dn entry has to have CRL in attribute certificaterevocationlist
     * or certificaterevocationlist;binary.
     *
     * @param uri
     */
private byte[] getCRLByLdapURI(String uri) {
    if (debug.messageEnabled()) {
        debug.message("AMCRLStore.getCRLByLdapURI: uri = " + uri);
    }
    LDAPUrl url;
    LDAPConnectionFactory factory;
    byte[] crl = null;
    try {
        url = LDAPUrl.valueOf(uri);
    } catch (LocalizedIllegalArgumentException e) {
        debug.error("AMCRLStore.getCRLByLdapURI(): Could not parse uri: {}", uri, e);
        return null;
    }
    debug.message("AMCRLStore.getCRLByLdapURI: url.dn = {}", url.getName());
    // Check ldap over SSL
    if (url.isSecure()) {
        try {
            factory = new LDAPConnectionFactory(url.getHost(), url.getPort(), Options.defaultOptions().set(LDAPConnectionFactory.SSL_CONTEXT, new SSLContextBuilder().getSSLContext()));
        } catch (GeneralSecurityException e) {
            debug.error("AMCRLStore.getCRLByLdapURI: Error getting SSL Context", e);
            return null;
        }
    } else {
        // non-ssl
        factory = new LDAPConnectionFactory(url.getHost(), url.getPort());
    }
    try (Connection ldc = factory.getConnection()) {
        ConnectionEntryReader results = ldc.search(url.asSearchRequest().addControl(TransactionIdControl.newControl(AuditRequestContext.createSubTransactionIdValue())));
        if (!results.hasNext()) {
            debug.error("verifyCertificate - No CRL distribution Point configured");
            return null;
        }
        if (results.isReference()) {
            debug.warning("Getting CRL but got LDAP reference: {}", results.readReference());
            return null;
        }
        SearchResultEntry entry = results.readEntry();
        /* 
            * Retrieve the certificate revocation list if available.
            */
        Attribute crlAttribute = entry.getAttribute(CERTIFICATE_REVOCATION_LIST);
        if (crlAttribute == null) {
            crlAttribute = entry.getAttribute(CERTIFICATE_REVOCATION_LIST_BINARY);
            if (crlAttribute == null) {
                debug.error("verifyCertificate - No CRL distribution Point configured");
                return null;
            }
        }
        crl = crlAttribute.firstValue().toByteArray();
    } catch (Exception e) {
        debug.error("getCRLByLdapURI : Error in getting CRL", e);
    }
    return crl;
}
Also used : ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) LDAPUrl(org.forgerock.opendj.ldap.LDAPUrl) Attribute(org.forgerock.opendj.ldap.Attribute) GeneralSecurityException(java.security.GeneralSecurityException) HttpURLConnection(java.net.HttpURLConnection) Connection(org.forgerock.opendj.ldap.Connection) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) LocalizedIllegalArgumentException(org.forgerock.i18n.LocalizedIllegalArgumentException) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder) LdapException(org.forgerock.opendj.ldap.LdapException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) LocalizedIllegalArgumentException(org.forgerock.i18n.LocalizedIllegalArgumentException) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Aggregations

Attribute (org.forgerock.opendj.ldap.Attribute)48 ByteString (org.forgerock.opendj.ldap.ByteString)35 LdapException (org.forgerock.opendj.ldap.LdapException)30 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)28 Connection (org.forgerock.opendj.ldap.Connection)25 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)16 HashSet (java.util.HashSet)14 IOException (java.io.IOException)13 LinkedAttribute (org.forgerock.opendj.ldap.LinkedAttribute)11 SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)10 SearchResultReferenceIOException (org.forgerock.opendj.ldap.SearchResultReferenceIOException)9 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)8 FileNotFoundException (java.io.FileNotFoundException)6 ArrayList (java.util.ArrayList)6 LinkedHashSet (java.util.LinkedHashSet)6 Set (java.util.Set)6 Modification (org.forgerock.opendj.ldap.Modification)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 HashMap (java.util.HashMap)5 ModifyRequest (org.forgerock.opendj.ldap.requests.ModifyRequest)5