use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.
the class SMSAuthModule method login.
public boolean login() throws LoginException {
// Check if the user is already present
String username = (String) sharedState.get(ISAuthConstants.SHARED_STATE_USERNAME);
String password = (String) sharedState.get(ISAuthConstants.SHARED_STATE_PASSWORD);
if (debug.messageEnabled()) {
debug.message("SMSAuthModule::login() From shared state: " + "Username: " + username + " Password: " + ((password == null) ? "<not present>" : "<present>"));
}
// Check if we have username and password, if not send callbacks
if (username == null || password == null) {
// Request for both username and password
Callback[] cbs = new Callback[2];
cbs[0] = new NameCallback("User name: ");
cbs[1] = new PasswordCallback("Password: ", false);
try {
if (debug.messageEnabled()) {
debug.message("SMSAuthModule::login() Sending " + "Name & Password Callback");
}
cb.handle(cbs);
} catch (UnsupportedCallbackException e) {
throw (new LoginException(e.getMessage()));
} catch (IOException ioe) {
throw (new LoginException(ioe.getMessage()));
}
username = ((NameCallback) cbs[0]).getName();
char[] passwd = ((PasswordCallback) cbs[1]).getPassword();
if (passwd != null) {
password = new String(password);
}
}
// Authenticate the user, return false is username or password is null
boolean authenticated = false;
if (username != null && password != null) {
if (debug.messageEnabled()) {
debug.message("SMSAuthModule::login() For authentication: " + "Username: " + username + " Password: <present>");
}
if (LDAPUtils.isDN(username)) {
userDN = username;
username = rdnValueFromDn(username);
} else {
userDN = (String) userNameToDN.get(username);
if (userDN == null && !loadedInternalUsers) {
// Load the internal users and try to get userDN
loadInternalUsers();
userDN = (String) userNameToDN.get(username);
}
}
// be set in the subject
if (userDN != null) {
// Get the hashed password for the user
String hash = (String) users.get(username);
String cachedUserDN = (String) userNameToDN.get(username);
if (cachedUserDN != null) {
String normalizedUserDN = DNUtils.normalizeDN(userDN);
if ((normalizedUserDN == null) || !normalizedUserDN.equals(DNUtils.normalizeDN(cachedUserDN))) {
debug.message("SMSAuthModule::login() Invalid User DN");
return false;
}
}
// Compare the hashed password
boolean invalidPassword = false;
if (hash != null && hash.equals(Hash.hash(password))) {
if (debug.messageEnabled()) {
debug.message("SMSAuthModule::login() Success AuthN");
}
authenticated = true;
} else if (!loadedInternalUsers) {
// Load the internal users and compare hashed passwords
if (debug.messageEnabled()) {
debug.message("SMSAuthModule::login() " + "Loading internal users");
}
loadInternalUsers();
cachedUserDN = (String) userNameToDN.get(username);
if (cachedUserDN != null) {
String normalizedUserDN = DNUtils.normalizeDN(userDN);
if ((normalizedUserDN == null) || !normalizedUserDN.equals(DNUtils.normalizeDN(cachedUserDN))) {
if (debug.messageEnabled()) {
debug.message("SMSAuthModule::login() " + "Invalid User DN");
}
return false;
}
} else {
return false;
}
hash = (String) users.get(username);
if (hash != null && hash.equals(Hash.hash(password))) {
if (debug.messageEnabled()) {
debug.message("SMSAuthModule::login() " + "Success AuthN");
}
authenticated = true;
} else if (hash != null) {
// Password must be invalid
invalidPassword = true;
}
} else if (hash != null) {
// Password must be invalid
invalidPassword = true;
}
if (invalidPassword) {
throw (new InvalidPasswordException("invalid password", userDN));
}
}
}
return (authenticated);
}
use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.
the class AMSDKRepo method authenticateIt.
private boolean authenticateIt(LDAPAuthUtils ldapAuthUtil, IdType type, String username, String password) throws IdRepoException, AuthLoginException {
String baseDN = null;
String namingAttr = null;
String userid = username;
try {
if (type.equals(IdType.USER)) {
String pcNamingAttr = AMStoreConnection.getNamingAttribute(AMObject.PEOPLE_CONTAINER);
baseDN = pcNamingAttr + "=" + getDefaultPeopleContainerName() + "," + orgDN;
namingAttr = AMStoreConnection.getNamingAttribute(AMObject.USER);
} else if (type.equals(IdType.AGENT)) {
baseDN = "ou=" + getDefaultAgentContainerName() + "," + orgDN;
namingAttr = AMStoreConnection.getNamingAttribute(100);
} else {
return (false);
}
} catch (AMException ame) {
if (debug.messageEnabled()) {
debug.message("AMSDKRepo: authenticateIt" + "AMException : " + ame.getMessage());
debug.message(" type=" + type + "; username=" + username);
}
return (false);
}
try {
ldapAuthUtil.setUserNamingAttribute(namingAttr);
Set userSearchAttr = new HashSet();
userSearchAttr.add(namingAttr);
ldapAuthUtil.setUserSearchAttribute(userSearchAttr);
ldapAuthUtil.setBase(baseDN);
// need to reset filter otherwise it appends
// new filter to previous.
ldapAuthUtil.setFilter("");
String[] attrs = new String[2];
attrs[0] = "dn";
attrs[1] = namingAttr;
ldapAuthUtil.setUserAttrs(attrs);
if (LDAPUtils.isDN(username)) {
userid = LDAPUtils.rdnValueFromDn(username);
}
ldapAuthUtil.authenticateUser(userid, password);
} catch (LDAPUtilException ldapUtilEx) {
if (ResultCode.NO_SUCH_OBJECT.equals(ldapUtilEx.getResultCode())) {
if (debug.messageEnabled()) {
debug.message("AMSDKRepo:authenticateIt. " + "The specified user does not exist. " + "username=" + username);
}
throw new AuthLoginException(amAuthLDAP, "NoUser", null);
} else if (ResultCode.INVALID_CREDENTIALS.equals(ldapUtilEx.getResultCode())) {
if (debug.messageEnabled()) {
debug.message("AMSDKRepo:authenticateIt." + " Invalid password. username=" + username);
}
String failureUserID = ldapAuthUtil.getUserId();
throw new InvalidPasswordException(amAuthLDAP, "InvalidUP", null, failureUserID, null);
} else if (ResultCode.UNWILLING_TO_PERFORM.equals(ldapUtilEx.getResultCode())) {
if (debug.messageEnabled()) {
debug.message("AMSDKRepo:authenticateIt. " + "Unwilling to perform. Account inactivated." + " username" + username);
}
throw new AuthLoginException(amAuthLDAP, "FConnect", null);
} else if (ResultCode.INAPPROPRIATE_AUTHENTICATION.equals(ldapUtilEx.getResultCode())) {
if (debug.messageEnabled()) {
debug.message("AMSDKRepo:authenticateIt. " + "Inappropriate authentication. username=" + username);
}
throw new AuthLoginException(amAuthLDAP, "InappAuth", null);
} else if (ResultCode.CONSTRAINT_VIOLATION.equals(ldapUtilEx.getResultCode())) {
if (debug.messageEnabled()) {
debug.message("AMSDKRepo:authenticateIt. " + "Exceed password retry limit. username" + username);
}
throw new AuthLoginException(amAuthLDAP, "ExceedRetryLimit", null);
} else {
if (debug.messageEnabled()) {
debug.message("AMSDKRepo:authenticateIt. " + "default exception. username=" + username);
}
throw new AuthLoginException(amAuthLDAP, "LDAPex", null);
}
}
return ldapAuthUtil.getState() == ModuleState.SUCCESS;
}
use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.
the class LDAP method process.
public int process(Callback[] callbacks, int state) throws AuthLoginException {
currentState = state;
ModuleState newState;
LoginScreen loginScreen = LoginScreen.get(state);
try {
if (loginScreen.equals(LoginScreen.LOGIN_START)) {
if (callbacks == null || callbacks.length == 0) {
userName = (String) sharedState.get(getUserKey());
userPassword = (String) sharedState.get(getPwdKey());
if (userName == null || userPassword == null) {
return LoginScreen.LOGIN_START.intValue();
}
getCredentialsFromSharedState = true;
} else {
//callbacks is not null
userName = ((NameCallback) callbacks[0]).getName();
userPassword = charToString(((PasswordCallback) callbacks[1]).getPassword(), callbacks[1]);
}
if (userPassword == null || userPassword.length() == 0) {
if (debug.messageEnabled()) {
debug.message("LDAP.process: Password is null/empty");
}
throw new InvalidPasswordException("amAuth", "invalidPasswd", null);
}
//store username password both in success and failure case
storeUsernamePasswd(userName, userPassword);
if (initializeLDAP()) {
//validate username
validateUserName(userName, regEx);
ldapUtil.authenticateUser(userName, userPassword);
newState = ldapUtil.getState();
} else {
newState = ModuleState.SERVER_DOWN;
}
boolean passwordValidationSuccessFlag = true;
// information entered is correct
if (newState == ModuleState.SUCCESS) {
try {
validatePassword(userPassword);
} catch (UserNamePasswordValidationException upve) {
if (debug.messageEnabled()) {
debug.message("Password does not satisfy " + "password policy rules specified" + " in OpenAM");
}
isReset = true;
String invalidMsg = bundle.getString("PasswordInvalid");
replaceHeader(LoginScreen.PASSWORD_CHANGE.intValue(), invalidMsg);
currentState = LoginScreen.PASSWORD_CHANGE.intValue();
passwordValidationSuccessFlag = false;
}
}
if (passwordValidationSuccessFlag) {
processLoginScreen(newState);
}
return currentState;
} else if (loginScreen.equals(LoginScreen.PASSWORD_CHANGE)) {
if (debug.messageEnabled()) {
debug.message("you are in Password Screen:" + currentState);
}
// callbacks[3] is a user selected button index
// PwdAction == 0 is a Submit button
int pwdAction = ((ConfirmationCallback) callbacks[3]).getSelectedIndex();
if (pwdAction == 0) {
String oldPassword = charToString(((PasswordCallback) callbacks[0]).getPassword(), callbacks[0]);
String newPassword = charToString(((PasswordCallback) callbacks[1]).getPassword(), callbacks[1]);
String confirmPassword = charToString(((PasswordCallback) callbacks[2]).getPassword(), callbacks[2]);
try {
validatePassword(newPassword);
// check minimal password length requirement
int newPasswordLength = 0;
if (newPassword != null) {
newPasswordLength = newPassword.length();
}
if (newPasswordLength < requiredPasswordLength) {
if (debug.messageEnabled()) {
debug.message("LDAP.process: new password less" + " than the minimal length of " + requiredPasswordLength);
}
newState = ModuleState.PASSWORD_MIN_CHARACTERS;
// add log
getLoginState("LDAP").logFailed(newState.name(), "CHANGE_USER_PASSWORD_FAILED", false, null);
} else {
ldapUtil.changePassword(oldPassword, newPassword, confirmPassword);
newState = ldapUtil.getState();
if (newState == ModuleState.PASSWORD_UPDATED_SUCCESSFULLY) {
// log change password success
getLoginState("LDAP").logSuccess("changePasswdSucceeded", "CHANGE_USER_PASSWORD_SUCCEEDED");
} else {
// add log
getLoginState("LDAP").logFailed(newState.name(), "CHANGE_USER_PASSWORD_FAILED", false, null);
}
}
processPasswordScreen(newState);
if (debug.messageEnabled()) {
debug.message("Password change state :" + newState);
}
} catch (UserNamePasswordValidationException upve) {
if (debug.messageEnabled()) {
debug.message("Password could not be validated, " + "need a different password");
}
String invalidMsg = bundle.getString("NewPasswordInvalid");
replaceHeader(LoginScreen.PASSWORD_CHANGE.intValue(), invalidMsg);
currentState = LoginScreen.PASSWORD_CHANGE.intValue();
}
return currentState;
} else {
if (isReset) {
isReset = false;
return LoginScreen.LOGIN_START.intValue();
}
validatedUserID = ldapUtil.getUserId();
return ISAuthConstants.LOGIN_SUCCEED;
}
} else {
setFailureID(ldapUtil.getUserId(userName));
throw new AuthLoginException(AM_AUTH, "LDAPex", null);
}
} catch (LDAPUtilException ex) {
if (getCredentialsFromSharedState && !isUseFirstPassEnabled()) {
getCredentialsFromSharedState = false;
return LoginScreen.LOGIN_START.intValue();
}
setFailureID((ldapUtil != null) ? ldapUtil.getUserId(userName) : userName);
if (ex.getResultCode().equals(ResultCode.NO_SUCH_OBJECT)) {
if (debug.messageEnabled()) {
debug.message("The specified user does not exist.");
}
throw new AuthLoginException(AM_AUTH, "NoUser", null);
} else if (ex.getResultCode().equals(ResultCode.INVALID_CREDENTIALS)) {
if (debug.messageEnabled()) {
debug.message("Invalid password.");
}
String failureUserID = ldapUtil.getUserId();
throw new InvalidPasswordException(AM_AUTH, "InvalidUP", null, failureUserID, null);
} else if (ex.getResultCode().equals(ResultCode.UNWILLING_TO_PERFORM)) {
if (debug.messageEnabled()) {
debug.message("Unwilling to perform. Account inactivated.");
}
currentState = LoginScreen.USER_INACTIVE.intValue();
return currentState;
} else if (ex.getResultCode().equals(ResultCode.INAPPROPRIATE_AUTHENTICATION)) {
if (debug.messageEnabled()) {
debug.message("Inappropriate authentication.");
}
throw new AuthLoginException(AM_AUTH, "InappAuth", null);
} else if (ex.getResultCode().equals(ResultCode.CONSTRAINT_VIOLATION)) {
if (debug.messageEnabled()) {
debug.message("Exceed password retry limit.");
}
throw new AuthLoginException(amAuthLDAP, ISAuthConstants.EXCEED_RETRY_LIMIT, null);
} else {
throw new AuthLoginException(AM_AUTH, "LDAPex", null);
}
} catch (UserNamePasswordValidationException upve) {
// Note: Do not set failure Id for this exception
if (debug.messageEnabled()) {
debug.message("Invalid Characters detected");
}
throw new AuthLoginException(upve);
}
}
use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.
the class HTTPBasic method process.
public int process(Callback[] callbacks, int state) throws LoginException {
if ((instanceName == null) || (instanceName.length() == 0)) {
throw new AuthLoginException(amAuthHTTPBasic, "noModule", null);
}
int status = 0;
HttpServletRequest req = getHttpServletRequest();
HttpServletResponse resp = getHttpServletResponse();
String auth = null;
if (callbacks != null && callbacks.length != 0) {
auth = ((HttpCallback) callbacks[0]).getAuthorization();
}
if ((req == null || resp == null) && auth == null) {
debug.message("Servlet Request and Response cannot be null");
throw new AuthLoginException(amAuthHTTPBasic, "reqRespNull", null);
}
try {
debug.message("Process HTTPBasic Auth started ...");
if (auth == null || auth.length() == 0) {
auth = req.getHeader("Authorization");
}
if (debug.messageEnabled()) {
debug.message("AUTH : " + auth);
}
int retVal = authenticate(auth);
validatedUserID = userName;
return retVal;
} catch (Exception ex) {
debug.error("login: unknown exception = ", ex);
setFailureID(userName);
if (ex instanceof InvalidPasswordException) {
throw new InvalidPasswordException(ex);
} else {
throw new AuthLoginException(amAuthHTTPBasic, "sendError", null, ex);
}
}
}
use of com.sun.identity.authentication.spi.InvalidPasswordException in project OpenAM by OpenRock.
the class JDBC method process.
/**
* Processes the authentication request.
*
* @return <code>ISAuthConstants.LOGIN_SUCCEED</code> as succeeded;
* <code>ISAuthConstants.LOGIN_IGNORE</code> as failed.
* @exception AuthLoginException upon any failure. login state should be
* kept on exceptions for status check in auth chaining.
*/
public int process(Callback[] callbacks, int state) throws AuthLoginException {
// return if this module is already done
if (errorMsg != null) {
throw new AuthLoginException(amAuthJDBC, errorMsg, null);
}
if (debug.messageEnabled()) {
debug.message("State: " + state);
}
if (state != ISAuthConstants.LOGIN_START) {
throw new AuthLoginException(amAuthJDBC, "invalidState", null);
}
if (callbacks != null && callbacks.length == 0) {
userName = (String) sharedState.get(getUserKey());
password = (String) sharedState.get(getPwdKey());
if (userName == null || password == null) {
return ISAuthConstants.LOGIN_START;
}
getCredentialsFromSharedState = true;
} else {
userName = ((NameCallback) callbacks[0]).getName();
if (debug.messageEnabled()) {
debug.message("Authenticating this user: " + userName);
}
passwordCharArray = ((PasswordCallback) callbacks[1]).getPassword();
password = new String(passwordCharArray);
if (userName == null || userName.length() == 0) {
throw new AuthLoginException(amAuthJDBC, "noUserName", null);
}
}
storeUsernamePasswd(userName, password);
// SQL attacks will be handled by prepared stmt escaping.
if (userName.length() > MAX_NAME_LENGTH) {
throw new AuthLoginException(amAuthJDBC, "userNameTooLong", null);
}
Connection database = null;
PreparedStatement thisStatement = null;
ResultSet results = null;
try {
if (useJNDI) {
Context initctx = new InitialContext();
DataSource ds = (DataSource) initctx.lookup(jndiName);
if (debug.messageEnabled()) {
debug.message("Datasource Acquired: " + ds.toString());
}
database = ds.getConnection();
debug.message("Using JNDI Retrieved Connection pool");
} else {
Class.forName(driver);
database = DriverManager.getConnection(url, dbuser, dbpassword);
}
if (debug.messageEnabled()) {
debug.message("Connection Acquired: " + database.toString());
}
//Prepare the statement for execution
if (debug.messageEnabled()) {
debug.message("PreparedStatement to build: " + statement);
}
thisStatement = database.prepareStatement(statement);
thisStatement.setString(1, userName);
if (debug.messageEnabled()) {
debug.message("Statement to execute: " + thisStatement);
}
// execute the query
results = thisStatement.executeQuery();
if (results == null) {
debug.message("returned null from executeQuery()");
throw new AuthLoginException(amAuthJDBC, "nullResult", null);
}
//parse the results. should only be one item in one row.
int index = 0;
while (results.next()) {
// do normal processing..its the first and last row
index++;
if (index > 1) {
if (debug.messageEnabled()) {
debug.message("Too many results." + "UID should be a primary key");
}
throw new AuthLoginException(amAuthJDBC, "multiEntry", null);
}
resultPassword = results.getString(passwordColumn).trim();
}
if (index == 0) {
// no results
if (debug.messageEnabled()) {
debug.message("No results from your SQL query." + "UID should be valid");
}
throw new AuthLoginException(amAuthJDBC, "nullResult", null);
}
} catch (Throwable e) {
if (getCredentialsFromSharedState && !isUseFirstPassEnabled()) {
getCredentialsFromSharedState = false;
return ISAuthConstants.LOGIN_START;
}
if (debug.messageEnabled()) {
debug.message("JDBC Exception:", e);
}
throw new AuthLoginException(e);
} finally {
// close the resultset
if (results != null) {
try {
results.close();
} catch (Exception e) {
// ignore
}
}
// close the statement
if (thisStatement != null) {
try {
thisStatement.close();
} catch (Exception e) {
// ignore
}
}
// close the connection when done
if (database != null) {
try {
database.close();
} catch (Exception dbe) {
debug.error("Error in closing database connection: " + dbe.getMessage());
if (debug.messageEnabled()) {
debug.message("Fail to close database:", dbe);
}
}
}
}
if (!transform.equals(DEFAULT_TRANSFORM)) {
try {
JDBCPasswordSyntaxTransform syntaxTransform = (JDBCPasswordSyntaxTransform) Class.forName(transform).newInstance();
if (debug.messageEnabled()) {
debug.message("Got my Transform Object" + syntaxTransform.toString());
}
password = syntaxTransform.transform(password);
if (debug.messageEnabled()) {
debug.message("Password transformed by: " + transform);
}
} catch (Throwable e) {
if (debug.messageEnabled()) {
debug.message("Syntax Transform Exception:" + e.toString());
}
throw new AuthLoginException(e);
}
}
// see if the passwords match
if (password != null && password.equals(resultPassword)) {
userTokenId = userName;
return ISAuthConstants.LOGIN_SUCCEED;
} else {
debug.message("password not match. Auth failed.");
setFailureID(userName);
throw new InvalidPasswordException(amAuthJDBC, "loginFailed", null, userName, null);
}
}
Aggregations