Search in sources :

Example 1 with InvalidPasswordException

use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.

the class DJLDAPv3Repo method authenticate.

/**
     * Tries to bind as the user with the credentials passed in via callbacks. This authentication mechanism does not
     * handle password policies, nor password expiration.
     *
     * @param credentials The username/password combination.
     * @return <code>true</code> if the bind operation was successful.
     * @throws IdRepoException If the passed in username/password was null, or if the specified user cannot be found.
     * @throws AuthLoginException If an LDAP error occurs during authentication.
     * @throws InvalidPasswordException If the provided password is not valid, so Account Lockout can be triggered.
     */
@Override
public boolean authenticate(Callback[] credentials) throws IdRepoException, AuthLoginException {
    if (DEBUG.messageEnabled()) {
        DEBUG.message("authenticate invoked");
    }
    String userName = null;
    char[] password = null;
    for (Callback callback : credentials) {
        if (callback instanceof NameCallback) {
            userName = ((NameCallback) callback).getName();
        } else if (callback instanceof PasswordCallback) {
            password = ((PasswordCallback) callback).getPassword();
        }
    }
    if (userName == null || password == null) {
        throw newIdRepoException(IdRepoErrorCode.UNABLE_TO_AUTHENTICATE, CLASS_NAME);
    }
    String dn = findDNForAuth(IdType.USER, userName);
    Connection conn = null;
    try {
        BindRequest bindRequest = LDAPRequests.newSimpleBindRequest(dn, password);
        conn = bindConnectionFactory.getConnection();
        BindResult bindResult = conn.bind(bindRequest);
        return bindResult.isSuccess();
    } catch (LdapException ere) {
        ResultCode resultCode = ere.getResult().getResultCode();
        if (DEBUG.messageEnabled()) {
            DEBUG.message("An error occurred while trying to authenticate a user: " + ere.toString());
        }
        if (resultCode.equals(ResultCode.INVALID_CREDENTIALS)) {
            throw new InvalidPasswordException(AM_AUTH, "InvalidUP", null, userName, null);
        } else if (resultCode.equals(ResultCode.UNWILLING_TO_PERFORM) || resultCode.equals(ResultCode.CONSTRAINT_VIOLATION)) {
            throw new AuthLoginException(AM_AUTH, "FAuth", null);
        } else if (resultCode.equals(ResultCode.INAPPROPRIATE_AUTHENTICATION)) {
            throw new AuthLoginException(AM_AUTH, "InappAuth", null);
        } else {
            throw new AuthLoginException(AM_AUTH, "LDAPex", null);
        }
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
}
Also used : PasswordCallback(javax.security.auth.callback.PasswordCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) NameCallback(javax.security.auth.callback.NameCallback) Connection(org.forgerock.opendj.ldap.Connection) BindRequest(org.forgerock.opendj.ldap.requests.BindRequest) PasswordCallback(javax.security.auth.callback.PasswordCallback) BindResult(org.forgerock.opendj.ldap.responses.BindResult) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode)

Example 2 with InvalidPasswordException

use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.

the class AgentsRepo method authenticate.

public boolean authenticate(Callback[] credentials) throws IdRepoException, AuthLoginException {
    if (debug.messageEnabled()) {
        debug.message("AgentsRepo.authenticate() called");
    }
    // Obtain user name and password from credentials and compare
    // with the ones from the agent profile to authorize the agent.
    String username = null;
    String unhashedPassword = null;
    String password = null;
    for (int i = 0; i < credentials.length; i++) {
        if (credentials[i] instanceof NameCallback) {
            username = ((NameCallback) credentials[i]).getName();
            if (debug.messageEnabled()) {
                debug.message("AgentsRepo.authenticate() username: " + username);
            }
        } else if (credentials[i] instanceof PasswordCallback) {
            char[] passwd = ((PasswordCallback) credentials[i]).getPassword();
            if (passwd != null) {
                unhashedPassword = new String(passwd);
                password = hashAlgStr + Hash.hash(unhashedPassword);
                if (debug.messageEnabled()) {
                    debug.message("AgentsRepo.authenticate() passwd " + "present");
                }
            }
        }
    }
    if (username == null || (username.length() == 0) || password == null || unhashedPassword == null) {
        Object[] args = { NAME };
        throw new IdRepoException(IdRepoBundle.BUNDLE_NAME, IdRepoErrorCode.UNABLE_TO_AUTHENTICATE, args);
    }
    SSOToken adminToken = (SSOToken) AccessController.doPrivileged(AdminTokenAction.getInstance());
    boolean answer = false;
    String userid = username;
    try {
        /* Only agents with IdType.AGENTONLY is used for authentication,
             * not the agents with IdType.AGENTGROUP.
             * AGENTGROUP is for storing common properties.
             */
        if (LDAPUtils.isDN(username)) {
            userid = LDAPUtils.rdnValueFromDn(username);
        }
        Set pSet = new HashSet(2);
        pSet.add("userpassword");
        pSet.add(oauth2Attribute);
        Map ansMap = new HashMap();
        String userPwd = null;
        ansMap = getAttributes(adminToken, IdType.AGENT, userid, pSet);
        Set userPwdSet = (Set) ansMap.get("userpassword");
        if ((userPwdSet != null) && (!userPwdSet.isEmpty())) {
            userPwd = (String) userPwdSet.iterator().next();
            if (!(answer = password.equals(userPwd)) && !(answer = oauth2PasswordMatch(ansMap, unhashedPassword, userPwd))) {
                throw (new InvalidPasswordException("invalid password", userid));
            }
        }
        if (debug.messageEnabled()) {
            debug.message("AgentsRepo.authenticate() result: " + answer);
        }
    } catch (SSOException ssoe) {
        if (debug.warningEnabled()) {
            debug.warning("AgentsRepo.authenticate(): " + "Unable to authenticate SSOException: " + ssoe.getMessage());
        }
    }
    return (answer);
}
Also used : SSOToken(com.iplanet.sso.SSOToken) NotificationSet(com.iplanet.services.comm.share.NotificationSet) Set(java.util.Set) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) Map(java.util.Map) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet)

Example 3 with InvalidPasswordException

use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.

the class RADIUS method process.

/**
     * Takes an array of submitted <code>Callback</code>, process them and decide the order of next state to go. Return
     * STATE_SUCCEED if the login is successful, return STATE_FAILED if the LoginModule should be ignored.
     *
     * @param callbacks
     *            an array of <code>Callback</code> for this Login state
     * @param state
     *            order of state. State order starts with 1.
     * @return int order of next state. Return STATE_SUCCEED if authentication is successful, return STATE_FAILED if the
     *         LoginModule should be ignored.
     * @throws AuthLoginException if the user fails authentication or some anomalous condition occurs
     */
@Override
public int process(Callback[] callbacks, int state) throws AuthLoginException {
    String tmpPasswd = null;
    String sState;
    switch(state) {
        case ISAuthConstants.LOGIN_START:
            try {
                radiusConn = new RadiusConn(primaryServers, secondaryServers, sharedSecret, iTimeOut, healthCheckInterval);
            } catch (SocketException se) {
                debug.error("RADIUS login failure; Socket Exception se == ", se);
                shutdown();
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusNoServer", null);
            } catch (Exception e) {
                debug.error("RADIUS login failure; Can't connect to RADIUS server", e);
                shutdown();
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusNoServer", null);
            }
            if (callbacks != null && callbacks.length == 0) {
                username = (String) sharedState.get(getUserKey());
                tmpPasswd = (String) sharedState.get(getPwdKey());
                if (username == null || tmpPasswd == null) {
                    return ISAuthConstants.LOGIN_START;
                }
                getCredentialsFromSharedState = true;
            } else {
                username = ((NameCallback) callbacks[0]).getName();
                tmpPasswd = charToString(((PasswordCallback) callbacks[1]).getPassword(), callbacks[1]);
                if (debug.messageEnabled()) {
                    debug.message("username: " + username);
                }
            }
            storeUsernamePasswd(username, tmpPasswd);
            try {
                succeeded = false;
                radiusConn.authenticate(username, tmpPasswd);
            } catch (RejectException re) {
                if (getCredentialsFromSharedState && !isUseFirstPassEnabled()) {
                    getCredentialsFromSharedState = false;
                    return ISAuthConstants.LOGIN_START;
                }
                if (debug.messageEnabled()) {
                    debug.message("Radius login request rejected", re);
                }
                shutdown();
                setFailureID(username);
                throw new InvalidPasswordException(AM_AUTH_RADIUS, "RadiusLoginFailed", null, username, re);
            } catch (IOException ioe) {
                if (getCredentialsFromSharedState && !isUseFirstPassEnabled()) {
                    getCredentialsFromSharedState = false;
                    return ISAuthConstants.LOGIN_START;
                }
                debug.error("Radius request IOException", ioe);
                shutdown();
                setFailureID(username);
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
            } catch (java.security.NoSuchAlgorithmException ne) {
                if (getCredentialsFromSharedState && !isUseFirstPassEnabled()) {
                    getCredentialsFromSharedState = false;
                    return ISAuthConstants.LOGIN_START;
                }
                debug.error("Radius No Such Algorithm Exception", ne);
                shutdown();
                setFailureID(username);
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
            } catch (ChallengeException ce) {
                if (getCredentialsFromSharedState && !isUseFirstPassEnabled()) {
                    getCredentialsFromSharedState = false;
                    return ISAuthConstants.LOGIN_START;
                }
                cException = ce;
                sState = ce.getState();
                if (sState == null) {
                    debug.error("Radius failure - no state returned in challenge");
                    shutdown();
                    setFailureID(username);
                    throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusAuth", null);
                }
                challengeID = ce.getReplyMessage();
                if (debug.messageEnabled()) {
                    debug.message("Server challenge with " + "challengeID: " + challengeID);
                }
                setDynamicText(2);
                return ISAuthConstants.LOGIN_CHALLENGE;
            } catch (Exception e) {
                if (getCredentialsFromSharedState && !isUseFirstPassEnabled()) {
                    getCredentialsFromSharedState = false;
                    return ISAuthConstants.LOGIN_START;
                }
                shutdown();
                setFailureID(username);
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null, e);
            }
            succeeded = true;
            break;
        case ISAuthConstants.LOGIN_CHALLENGE:
            String passwd = getChallengePassword(callbacks);
            if (debug.messageEnabled()) {
                debug.message("reply to challenge--username: " + username);
            }
            try {
                succeeded = false;
                radiusConn.replyChallenge(username, passwd, cException);
            } catch (ChallengeException ce) {
                sState = ce.getState();
                if (sState == null) {
                    debug.error("handle Challenge failure - no state returned");
                    shutdown();
                    setFailureID(username);
                    throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
                }
                resetCallback(2, 0);
                challengeID = ce.getReplyMessage();
                if (debug.messageEnabled()) {
                    debug.message("Server challenge again with challengeID: " + challengeID);
                }
                // save it for next replyChallenge
                cException = ce;
                setDynamicText(2);
                return ISAuthConstants.LOGIN_CHALLENGE;
            } catch (RejectException ex) {
                debug.error("Radius challenge response rejected", ex);
                shutdown();
                setFailureID(username);
                throw new InvalidPasswordException(AM_AUTH_RADIUS, "RadiusLoginFailed", null, username, ex);
            } catch (IOException ioe) {
                debug.error("Radius challenge IOException", ioe);
                shutdown();
                setFailureID(username);
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
            } catch (java.security.NoSuchAlgorithmException ex) {
                debug.error("Radius No Such Algorithm Exception", ex);
                shutdown();
                setFailureID(username);
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
            } catch (Exception e) {
                debug.error("RADIUS challenge Authentication Failed ", e);
                shutdown();
                setFailureID(username);
                throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
            }
            succeeded = true;
            break;
        default:
            debug.error("RADIUS Authentication Failed - invalid state" + state);
            shutdown();
            succeeded = false;
            setFailureID(username);
            throw new AuthLoginException(AM_AUTH_RADIUS, "RadiusLoginFailed", null);
    }
    if (succeeded) {
        if (debug.messageEnabled()) {
            debug.message("RADIUS authentication successful");
        }
        if (username != null) {
            StringTokenizer usernameToken = new StringTokenizer(username, ",");
            userTokenId = usernameToken.nextToken();
        }
        if (debug.messageEnabled()) {
            debug.message("userTokenID: " + userTokenId);
        }
        shutdown();
        return ISAuthConstants.LOGIN_SUCCEED;
    } else {
        if (debug.messageEnabled()) {
            debug.message("RADIUS authentication to be ignored");
        }
        return ISAuthConstants.LOGIN_IGNORE;
    }
}
Also used : SocketException(java.net.SocketException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) RejectException(com.sun.identity.authentication.modules.radius.client.RejectException) IOException(java.io.IOException) RadiusConn(com.sun.identity.authentication.modules.radius.client.RadiusConn) IOException(java.io.IOException) ChallengeException(com.sun.identity.authentication.modules.radius.client.ChallengeException) SocketException(java.net.SocketException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) RejectException(com.sun.identity.authentication.modules.radius.client.RejectException) ChallengeException(com.sun.identity.authentication.modules.radius.client.ChallengeException) StringTokenizer(java.util.StringTokenizer) PasswordCallback(javax.security.auth.callback.PasswordCallback) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException)

Example 4 with InvalidPasswordException

use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.

the class OATH method process.

/**
     * Processes the OTP input by the user. Checks the OTP for validity, and
     * resynchronizes the server as needed.
     *
     * @param callbacks
     * @param state
     * @return -1 for success; 0 for failure
     * @throws AuthLoginException upon any errors
     */
@Override
public int process(Callback[] callbacks, int state) throws AuthLoginException {
    try {
        //check for session and get username and UUID
        if (userName == null || userName.length() == 0) {
            // session upgrade case. Need to find the user ID from the old
            // session
            SSOTokenManager mgr = SSOTokenManager.getInstance();
            InternalSession isess = getLoginState("OATH").getOldSession();
            if (isess == null) {
                throw new AuthLoginException("amAuth", "noInternalSession", null);
            }
            SSOToken token = mgr.createSSOToken(isess.getID().toString());
            UUID = token.getPrincipal().getName();
            userName = token.getProperty("UserToken");
            if (debug.messageEnabled()) {
                debug.message("OATH.process(): Username from SSOToken : " + userName);
            }
            if (userName == null || userName.length() == 0) {
                throw new AuthLoginException("amAuth", "noUserName", null);
            }
        }
        switch(state) {
            case ISAuthConstants.LOGIN_START:
                // callback[1] = Confirmation CallBack (Submit OTP)
                if (callbacks == null || callbacks.length != 2) {
                    throw new AuthLoginException(amAuthOATH, "authFailed", null);
                }
                // check password length MUST be 6 or higher according to RFC
                if (passLen < MIN_PASSWORD_LENGTH) {
                    debug.error("OATH.process(): Password length is less than " + MIN_PASSWORD_LENGTH);
                    throw new AuthLoginException(amAuthOATH, "authFailed", null);
                }
                // get OTP
                String OTP = String.valueOf(((PasswordCallback) callbacks[0]).getPassword());
                if (StringUtils.isEmpty(OTP)) {
                    debug.error("OATH.process(): invalid OTP code");
                    setFailureID(userName);
                    throw new InvalidPasswordException("amAuth", "invalidPasswd", null);
                }
                if (minSecretKeyLength <= 0) {
                    debug.error("OATH.process(): Min Secret Key Length is not a valid value");
                    throw new AuthLoginException(amAuthOATH, "authFailed", null);
                }
                if (StringUtils.isEmpty(secretKeyAttrName)) {
                    debug.error("OATH.process():  secret key attribute name is empty");
                    throw new AuthLoginException(amAuthOATH, "authFailed", null);
                }
                // get Arrival time of the OTP
                timeInSeconds = System.currentTimeMillis() / 1000L;
                if (checkOTP(OTP)) {
                    return ISAuthConstants.LOGIN_SUCCEED;
                } else {
                    // the OTP is out of the window or incorrect
                    setFailureID(userName);
                    throw new InvalidPasswordException("amAuth", "invalidPasswd", null);
                }
        }
    } catch (SSOException e) {
        debug.error("OATH.process(): SSOException", e);
        throw new AuthLoginException(amAuthOATH, "authFailed", null);
    }
    return ISAuthConstants.LOGIN_IGNORE;
}
Also used : SSOTokenManager(com.iplanet.sso.SSOTokenManager) SSOToken(com.iplanet.sso.SSOToken) InternalSession(com.iplanet.dpro.session.service.InternalSession) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) SSOException(com.iplanet.sso.SSOException)

Example 5 with InvalidPasswordException

use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.

the class AuthenticatorOATH method doLoginSavedDevice.

private int doLoginSavedDevice(final Callback[] callbacks, final int state, final OathDeviceSettings settings) throws AuthLoginException, IOException, IdRepoException, SSOException {
    OathDeviceSettings deviceToAuthAgainst = settings;
    if (null == deviceToAuthAgainst && null != newDevice) {
        deviceToAuthAgainst = newDevice;
    }
    //get OTP
    String OTP = ((NameCallback) callbacks[0]).getName();
    if (OTP.length() == 0) {
        debug.error("OATH.process() : invalid OTP code");
        if (++attempt >= TOTAL_ATTEMPTS) {
            setFailureID(userName);
            throw new InvalidPasswordException("amAuth", "invalidPasswd", null);
        }
        replaceHeader(state, MODULE_NAME + "Attempt " + (attempt + 1) + " of " + TOTAL_ATTEMPTS);
        return state;
    }
    //get Arrival time of the OTP
    time = System.currentTimeMillis() / 1000L;
    if (isRecoveryCode(OTP, deviceToAuthAgainst, id)) {
        return RECOVERY_USED;
    } else if (checkOTP(OTP, id, deviceToAuthAgainst)) {
        if (isOptional) {
            //if it's optional and you log in, config not skippable
            realmOathService.setUserSkipOath(id, AuthenticatorOathService.NOT_SKIPPABLE);
        }
        if (null == settings) {
            // this is the first time we have authorised against this device - we can now save it.
            deviceFactory.saveDeviceProfile(id.getName(), id.getRealm(), deviceToAuthAgainst);
        }
        return ISAuthConstants.LOGIN_SUCCEED;
    } else {
        //the OTP is out of the window or incorrect
        if (++attempt >= TOTAL_ATTEMPTS) {
            setFailureID(userName);
            throw new InvalidPasswordException("amAuth", "invalidPasswd", null);
        }
        replaceHeader(state, MODULE_NAME + "Attempt " + (attempt + 1) + " of " + TOTAL_ATTEMPTS);
        return state;
    }
}
Also used : NameCallback(javax.security.auth.callback.NameCallback) OathDeviceSettings(org.forgerock.openam.core.rest.devices.OathDeviceSettings) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException)

Aggregations

InvalidPasswordException (com.sun.identity.authentication.spi.InvalidPasswordException)18 AuthLoginException (com.sun.identity.authentication.spi.AuthLoginException)15 PasswordCallback (javax.security.auth.callback.PasswordCallback)8 SSOException (com.iplanet.sso.SSOException)6 IdRepoException (com.sun.identity.idm.IdRepoException)6 NameCallback (javax.security.auth.callback.NameCallback)6 IOException (java.io.IOException)4 HashSet (java.util.HashSet)4 Set (java.util.Set)4 Callback (javax.security.auth.callback.Callback)4 HashMap (java.util.HashMap)3 LoginException (javax.security.auth.login.LoginException)3 LDAPUtilException (org.forgerock.openam.ldap.LDAPUtilException)3 SSOToken (com.iplanet.sso.SSOToken)2 AuthErrorCodeException (com.sun.identity.authentication.spi.AuthErrorCodeException)2 UserNamePasswordValidationException (com.sun.identity.authentication.spi.UserNamePasswordValidationException)2 AMIdentityRepository (com.sun.identity.idm.AMIdentityRepository)2 Map (java.util.Map)2 InternalSession (com.iplanet.dpro.session.service.InternalSession)1 NotificationSet (com.iplanet.services.comm.share.NotificationSet)1