Search in sources :

Example 11 with Connection

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

the class LDAPGroups method getValidValues.

/**
     * Returns a list of possible values for the <code>LDAPGroups
     * </code> that satisfy the given <code>pattern</code>.
     *
     * @param token the <code>SSOToken</code> that will be used
     * to determine the possible values
     * @param pattern search pattern that will be used to narrow
     * the list of valid names.
     *
     * @return <code>ValidValues</code> object
     *
     * @exception SSOException if <code>SSOToken</code> is not valid
     * @exception PolicyException if unable to get the list of valid
     * names.
     */
public ValidValues getValidValues(SSOToken token, String pattern) throws SSOException, PolicyException {
    if (!initialized) {
        throw new PolicyException(ResBundleUtils.rbName, "ldapgroups_subject_not_yet_initialized", null, null);
    }
    Set<String> validGroupDNs = new HashSet<>();
    String searchFilter;
    if (pattern != null && !pattern.trim().isEmpty()) {
        searchFilter = "(&" + groupSearchFilter + "(" + groupRDNAttrName + "=" + pattern + "))";
    } else {
        searchFilter = groupSearchFilter;
    }
    debug.message("LDAPGroups.getValidValues(): group search filter is: {}", searchFilter);
    String[] attrs = { groupRDNAttrName };
    Connection ld = null;
    int status = ValidValues.SUCCESS;
    try (Connection conn = connPool.getConnection()) {
        SearchRequest searchRequest = LDAPRequests.newSearchRequest(baseDN, groupSearchScope, searchFilter, attrs);
        ConnectionEntryReader reader = conn.search(searchRequest);
        while (reader.hasNext()) {
            if (reader.isReference()) {
                //Ignore
                reader.readReference();
            } else {
                SearchResultEntry entry = reader.readEntry();
                if (entry != null) {
                    validGroupDNs.add(entry.getName().toString());
                    debug.message("LDAPGroups.getValidValues(): found group name={}", entry.getName().toString());
                }
            }
        }
    } catch (LdapException lde) {
        ResultCode resultCode = lde.getResult().getResultCode();
        if (ResultCode.SIZE_LIMIT_EXCEEDED.equals(resultCode)) {
            debug.warning("LDAPGroups.getValidValues(): exceeded the size limit");
            return new ValidValues(ValidValues.SIZE_LIMIT_EXCEEDED, validGroupDNs);
        } else if (ResultCode.TIME_LIMIT_EXCEEDED.equals(resultCode)) {
            debug.warning("LDAPGroups.getValidValues(): exceeded the time limit");
            return new ValidValues(ValidValues.TIME_LIMIT_EXCEEDED, validGroupDNs);
        } else if (ResultCode.INVALID_CREDENTIALS.equals(resultCode)) {
            throw new PolicyException(ResBundleUtils.rbName, "ldap_invalid_password", null, null);
        } else if (ResultCode.NO_SUCH_OBJECT.equals(resultCode)) {
            String[] objs = { baseDN };
            throw new PolicyException(ResBundleUtils.rbName, "no_such_ldap_base_dn", objs, null);
        }
        String errorMsg = lde.getMessage();
        String additionalMsg = lde.getResult().getDiagnosticMessage();
        if (additionalMsg != null) {
            throw new PolicyException(errorMsg + ": " + additionalMsg);
        } else {
            throw new PolicyException(errorMsg);
        }
    } catch (Exception e) {
        throw new PolicyException(e);
    }
    return new ValidValues(status, validGroupDNs);
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) ValidValues(com.sun.identity.policy.ValidValues) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) NameNotFoundException(com.sun.identity.policy.NameNotFoundException) PolicyException(com.sun.identity.policy.PolicyException) InvalidNameException(com.sun.identity.policy.InvalidNameException) SSOException(com.iplanet.sso.SSOException) LocalizedIllegalArgumentException(org.forgerock.i18n.LocalizedIllegalArgumentException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) PolicyException(com.sun.identity.policy.PolicyException) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) HashSet(java.util.HashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 12 with Connection

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

the class LDAPGroups method getUserDN.

/**
     * Get the full DN for the user using the RDN against the
     * LDAP server configured in the policy config service.
     */
private DN getUserDN(String userRDN) throws SSOException, PolicyException {
    DN userDN = null;
    if (userRDN != null) {
        Set<String> qualifiedUserDNs = new HashSet<>();
        String searchFilter = null;
        if ((userSearchFilter != null) && !(userSearchFilter.length() == 0)) {
            searchFilter = "(&" + userSearchFilter + userRDN + ")";
        } else {
            searchFilter = userRDN;
        }
        if (debug.messageEnabled()) {
            debug.message("LDAPGroups.getUserDN(): search filter is: " + searchFilter);
        }
        String[] attrs = { userRDNAttrName };
        try (Connection conn = connPool.getConnection()) {
            SearchRequest searchRequest = LDAPRequests.newSearchRequest(baseDN, userSearchScope, searchFilter, attrs);
            ConnectionEntryReader reader = conn.search(searchRequest);
            while (reader.hasNext()) {
                if (reader.isReference()) {
                    //Ignore
                    reader.readReference();
                } else {
                    SearchResultEntry entry = reader.readEntry();
                    if (entry != null) {
                        qualifiedUserDNs.add(entry.getName().toString());
                    }
                }
            }
        } catch (LdapException le) {
            ResultCode resultCode = le.getResult().getResultCode();
            if (ResultCode.SIZE_LIMIT_EXCEEDED.equals(resultCode)) {
                String[] objs = { orgName };
                debug.warning("LDAPGroups.isMember(): exceeded the size limit");
                throw new PolicyException(ResBundleUtils.rbName, "ldap_search_exceed_size_limit", objs, null);
            } else if (ResultCode.TIME_LIMIT_EXCEEDED.equals(resultCode)) {
                String[] objs = { orgName };
                debug.warning("LDAPGroups.isMember(): exceeded the time limit");
                throw new PolicyException(ResBundleUtils.rbName, "ldap_search_exceed_time_limit", objs, null);
            } else if (ResultCode.INVALID_CREDENTIALS.equals(resultCode)) {
                throw new PolicyException(ResBundleUtils.rbName, "ldap_invalid_password", null, null);
            } else if (ResultCode.NO_SUCH_OBJECT.equals(resultCode)) {
                String[] objs = { baseDN };
                throw new PolicyException(ResBundleUtils.rbName, "no_such_ldap_base_dn", objs, null);
            }
            String errorMsg = le.getMessage();
            String additionalMsg = le.getResult().getDiagnosticMessage();
            if (additionalMsg != null) {
                throw new PolicyException(errorMsg + ": " + additionalMsg);
            } else {
                throw new PolicyException(errorMsg);
            }
        } catch (Exception e) {
            throw new PolicyException(e);
        }
        // check if the user belongs to any of the selected groups
        if (qualifiedUserDNs.size() > 0) {
            debug.message("LDAPGroups.getUserDN(): qualified users={}", qualifiedUserDNs);
            Iterator<String> iter = qualifiedUserDNs.iterator();
            // we only take the first qualified DN if the DN
            userDN = DN.valueOf(iter.next());
        }
    }
    return userDN;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) Connection(org.forgerock.opendj.ldap.Connection) DN(org.forgerock.opendj.ldap.DN) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) NameNotFoundException(com.sun.identity.policy.NameNotFoundException) PolicyException(com.sun.identity.policy.PolicyException) InvalidNameException(com.sun.identity.policy.InvalidNameException) SSOException(com.iplanet.sso.SSOException) LocalizedIllegalArgumentException(org.forgerock.i18n.LocalizedIllegalArgumentException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) PolicyException(com.sun.identity.policy.PolicyException) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) HashSet(java.util.HashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 13 with Connection

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

the class RemoveReferralsStep method deleteExistingReferrals.

private void deleteExistingReferrals() throws UpgradeException {
    try (Connection connection = getConnection()) {
        for (DN referral : referralsToBeRemoved) {
            UpgradeProgress.reportStart(AUDIT_REMOVING_REFERRAL_START, referral);
            DeleteRequest request = LDAPRequests.newDeleteRequest(referral);
            connection.delete(request);
            UpgradeProgress.reportEnd(AUDIT_UPGRADE_SUCCESS);
        }
    } catch (DataLayerException | LdapException e) {
        UpgradeProgress.reportEnd(AUDIT_UPGRADE_FAIL);
        throw new UpgradeException("Failed to delete referrals", e);
    }
}
Also used : UpgradeException(org.forgerock.openam.upgrade.UpgradeException) DataLayerException(org.forgerock.openam.sm.datalayer.api.DataLayerException) Connection(org.forgerock.opendj.ldap.Connection) DN(org.forgerock.opendj.ldap.DN) DeleteRequest(org.forgerock.opendj.ldap.requests.DeleteRequest) LdapException(org.forgerock.opendj.ldap.LdapException)

Example 14 with Connection

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

the class LDAPAuthUtils method authenticate.

/**
     * Connect to LDAP server using parameters specified in
     * constructor and/or by setting properties attempt to authenticate.
     * checks for the password controls and  sets to the appropriate states
     */
private void authenticate() throws LDAPUtilException {
    Connection conn = null;
    List<Control> controls = null;
    try {
        try {
            BindRequest bindRequest = LDAPRequests.newSimpleBindRequest(userDN, userPassword.toCharArray());
            if (beheraEnabled) {
                bindRequest.addControl(PasswordPolicyRequestControl.newControl(false));
            }
            conn = getConnection();
            BindResult bindResult = conn.bind(bindRequest);
            controls = processControls(bindResult);
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        // Were there any password policy controls returned?
        PasswordPolicyResult result = checkControls(controls);
        if (result == null) {
            if (debug.messageEnabled()) {
                debug.message("No controls returned");
            }
            setState(ModuleState.SUCCESS);
        } else {
            processPasswordPolicyControls(result);
        }
    } catch (LdapException ere) {
        if (ere.getResult().getResultCode().equals(ResultCode.INVALID_CREDENTIALS)) {
            if (!isAd) {
                controls = processControls(ere.getResult());
                PasswordPolicyResult result = checkControls(controls);
                if (result != null && result.getPasswordPolicyErrorType() != null && result.getPasswordPolicyErrorType().equals(PasswordPolicyErrorType.PASSWORD_EXPIRED)) {
                    if (result.getPasswordPolicyWarningType() != null) {
                        //this case the credential was actually wrong
                        throw new LDAPUtilException("CredInvalid", ResultCode.INVALID_CREDENTIALS, null);
                    } else {
                        if (debug.messageEnabled()) {
                            debug.message("Password expired and must be reset");
                        }
                        setState(ModuleState.PASSWORD_EXPIRED_STATE);
                    }
                } else if (result != null && result.getPasswordPolicyErrorType() != null && result.getPasswordPolicyErrorType().equals(PasswordPolicyErrorType.ACCOUNT_LOCKED)) {
                    if (debug.messageEnabled()) {
                        debug.message("Account Locked");
                    }
                    processPasswordPolicyControls(result);
                } else {
                    if (debug.messageEnabled()) {
                        debug.message("Failed auth due to invalid credentials");
                    }
                    throw new LDAPUtilException("CredInvalid", ResultCode.INVALID_CREDENTIALS, null);
                }
            } else {
                PasswordPolicyResult result = checkADResult(ere.getResult().getDiagnosticMessage());
                if (result != null) {
                    processPasswordPolicyControls(result);
                } else {
                    if (debug.messageEnabled()) {
                        debug.message("Failed auth due to invalid credentials");
                    }
                    throw new LDAPUtilException("CredInvalid", ResultCode.INVALID_CREDENTIALS, null);
                }
            }
        } else if (ere.getResult().getResultCode().equals(ResultCode.NO_SUCH_OBJECT)) {
            if (debug.messageEnabled()) {
                debug.message("user does not exist");
            }
            throw new LDAPUtilException("UsrNotExist", ResultCode.NO_SUCH_OBJECT, null);
        } else if (ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_CONNECT_ERROR) || ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_SERVER_DOWN) || ere.getResult().getResultCode().equals(ResultCode.UNAVAILABLE) || ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_TIMEOUT)) {
            if (debug.messageEnabled()) {
                debug.message("Cannot connect to " + servers, ere);
            }
            setState(ModuleState.SERVER_DOWN);
        } else if (ere.getResult().getResultCode().equals(ResultCode.UNWILLING_TO_PERFORM)) {
            if (debug.messageEnabled()) {
                debug.message(servers + " unwilling to perform auth request");
            }
            // cases for err=53
            // - disconnect in progress
            // - backend unavailable (read-only, etc)
            // - server locked down
            // - reject unauthenticated requests
            // - low disk space (updates only)
            // - bind with no password (binds only)
            String[] args = { ere.getMessage() };
            throw new LDAPUtilException("FConnect", ResultCode.UNWILLING_TO_PERFORM, args);
        } else if (ere.getResult().getResultCode().equals(ResultCode.INAPPROPRIATE_AUTHENTICATION)) {
            if (debug.messageEnabled()) {
                debug.message("Failed auth due to inappropriate authentication");
            }
            throw new LDAPUtilException("amAuth", "InappAuth", ResultCode.INAPPROPRIATE_AUTHENTICATION, null);
        } else if (ere.getResult().getResultCode().equals(ResultCode.CONSTRAINT_VIOLATION)) {
            if (debug.messageEnabled()) {
                debug.message("Exceed password retry limit.");
            }
            throw new LDAPUtilException(ISAuthConstants.EXCEED_RETRY_LIMIT, ResultCode.CONSTRAINT_VIOLATION, null);
        } else {
            if (debug.messageEnabled()) {
                debug.message("Cannot authenticate to " + servers, ere);
            }
            throw new LDAPUtilException("amAuth", "FAuth", null, null);
        }
    }
}
Also used : PasswordExpiringResponseControl(org.forgerock.opendj.ldap.controls.PasswordExpiringResponseControl) PasswordExpiredResponseControl(org.forgerock.opendj.ldap.controls.PasswordExpiredResponseControl) PasswordPolicyRequestControl(org.forgerock.opendj.ldap.controls.PasswordPolicyRequestControl) Control(org.forgerock.opendj.ldap.controls.Control) PasswordPolicyResponseControl(org.forgerock.opendj.ldap.controls.PasswordPolicyResponseControl) Connection(org.forgerock.opendj.ldap.Connection) BindRequest(org.forgerock.opendj.ldap.requests.BindRequest) BindResult(org.forgerock.opendj.ldap.responses.BindResult) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException)

Example 15 with Connection

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

the class LDAPAuthUtils method changePassword.

/**
     * Updates to new password by using the parameters passed by the user.
     *
     * @param oldPwd Current password entered.
     * @param password New password entered.
     * @param confirmPassword Confirm password.
     * @throws LDAPUtilException
     */
public void changePassword(String oldPwd, String password, String confirmPassword) throws LDAPUtilException {
    if (password.equals(oldPwd)) {
        setState(ModuleState.WRONG_PASSWORD_ENTERED);
        return;
    }
    if (!(password.equals(confirmPassword))) {
        setState(ModuleState.PASSWORD_MISMATCH);
        return;
    }
    if (password.equals(userId)) {
        setState(ModuleState.USER_PASSWORD_SAME);
        return;
    }
    Connection modConn = null;
    List<Control> controls;
    try {
        ModifyRequest mods = LDAPRequests.newModifyRequest(userDN);
        if (beheraEnabled) {
            mods.addControl(PasswordPolicyRequestControl.newControl(false));
        }
        if (!isAd) {
            mods.addModification(ModificationType.DELETE, LDAP_PASSWD_ATTR, oldPwd);
            mods.addModification(ModificationType.ADD, LDAP_PASSWD_ATTR, password);
            modConn = getConnection();
            modConn.bind(LDAPRequests.newSimpleBindRequest(userDN, oldPwd.toCharArray()));
        } else {
            mods.addModification(ModificationType.DELETE, AD_PASSWD_ATTR, updateADPassword(oldPwd));
            mods.addModification(ModificationType.ADD, AD_PASSWD_ATTR, updateADPassword(password));
            modConn = getAdminConnection();
        }
        Result modResult = modConn.modify(mods);
        controls = processControls(modResult);
        // Were there any password policy controls returned?
        PasswordPolicyResult result = checkControls(controls);
        if (result == null) {
            if (debug.messageEnabled()) {
                debug.message("No controls returned");
            }
            setState(ModuleState.PASSWORD_UPDATED_SUCCESSFULLY);
        } else {
            processPasswordPolicyControls(result);
        }
    } catch (LdapException ere) {
        if (ere.getResult().getResultCode().equals(ResultCode.CONSTRAINT_VIOLATION)) {
            PasswordPolicyResult result = checkControls(processControls(ere.getResult()));
            if (result != null) {
                processPasswordPolicyControls(result);
            } else {
                if (isAd) {
                    setState(ModuleState.PASSWORD_NOT_UPDATE);
                } else {
                    setState(ModuleState.INSUFFICIENT_PASSWORD_QUALITY);
                }
            }
        } else if (ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_CONNECT_ERROR) || ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_SERVER_DOWN) || ere.getResult().getResultCode().equals(ResultCode.UNAVAILABLE) || ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_TIMEOUT)) {
            if (debug.messageEnabled()) {
                debug.message("changepassword:Cannot connect to " + servers + ": ", ere);
            }
            setState(ModuleState.SERVER_DOWN);
            return;
        } else if (ere.getResult().getResultCode().equals(ResultCode.UNWILLING_TO_PERFORM)) {
            // Were there any password policy controls returned?
            PasswordPolicyResult result = checkControls(processControls(ere.getResult()));
            if (result != null) {
                processPasswordPolicyControls(result);
            } else {
                setState(ModuleState.INSUFFICIENT_PASSWORD_QUALITY);
            }
        } else if (ere.getResult().getResultCode().equals(ResultCode.INVALID_CREDENTIALS)) {
            Result r = ere.getResult();
            if (r != null) {
                // Were there any password policy controls returned?
                PasswordPolicyResult result = checkControls(processControls(r));
                if (result != null) {
                    processPasswordPolicyControls(result);
                }
            }
            setState(ModuleState.PASSWORD_NOT_UPDATE);
        } else {
            setState(ModuleState.PASSWORD_NOT_UPDATE);
        }
        if (debug.warningEnabled()) {
            debug.warning("Cannot update : ", ere);
        }
    } finally {
        if (modConn != null) {
            modConn.close();
        }
    }
}
Also used : PasswordExpiringResponseControl(org.forgerock.opendj.ldap.controls.PasswordExpiringResponseControl) PasswordExpiredResponseControl(org.forgerock.opendj.ldap.controls.PasswordExpiredResponseControl) PasswordPolicyRequestControl(org.forgerock.opendj.ldap.controls.PasswordPolicyRequestControl) Control(org.forgerock.opendj.ldap.controls.Control) PasswordPolicyResponseControl(org.forgerock.opendj.ldap.controls.PasswordPolicyResponseControl) Connection(org.forgerock.opendj.ldap.Connection) ModifyRequest(org.forgerock.opendj.ldap.requests.ModifyRequest) LdapException(org.forgerock.opendj.ldap.LdapException) BindResult(org.forgerock.opendj.ldap.responses.BindResult) Result(org.forgerock.opendj.ldap.responses.Result)

Aggregations

Connection (org.forgerock.opendj.ldap.Connection)94 LdapException (org.forgerock.opendj.ldap.LdapException)72 ByteString (org.forgerock.opendj.ldap.ByteString)47 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)46 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)39 ResultCode (org.forgerock.opendj.ldap.ResultCode)29 Attribute (org.forgerock.opendj.ldap.Attribute)27 HashSet (java.util.HashSet)26 SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)20 SearchResultReferenceIOException (org.forgerock.opendj.ldap.SearchResultReferenceIOException)19 IOException (java.io.IOException)18 SSOException (com.iplanet.sso.SSOException)15 PolicyException (com.sun.identity.policy.PolicyException)14 SMSException (com.sun.identity.sm.SMSException)13 LinkedAttribute (org.forgerock.opendj.ldap.LinkedAttribute)13 ModifyRequest (org.forgerock.opendj.ldap.requests.ModifyRequest)12 BindResult (org.forgerock.opendj.ldap.responses.BindResult)12 DN (org.forgerock.opendj.ldap.DN)11 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)10 InvalidNameException (com.sun.identity.policy.InvalidNameException)10