use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.
the class AMLoginContext method runLogin.
/**
* Starts the login process ,calls JAAS Login Context
*/
public void runLogin() {
Thread thread = Thread.currentThread();
String logFailedMessage = bundle.getString("loginFailed");
String logFailedError = null;
AuthenticationFailureReason failureReason = null;
AMAccountLockout amAccountLockout;
boolean loginSuccess = false;
try {
if (isPureJAAS()) {
loginContext.login();
subject = loginContext.getSubject();
} else {
jaasLoginContext.login();
subject = jaasLoginContext.getSubject();
}
loginState.setSubject(subject);
if (!loginState.isAuthValidForInternalUser()) {
if (debug.warningEnabled()) {
debug.warning("AMLoginContext.runLogin():auth failed, " + "using invalid realm name for internal user");
}
logFailedMessage = AuthUtils.getErrorVal(AMAuthErrorCode.AUTH_MODULE_DENIED, AuthUtils.ERROR_MESSAGE);
logFailedError = "MODULEDENIED";
failureReason = MODULE_DENIED;
throw new AuthException(AMAuthErrorCode.AUTH_MODULE_DENIED, null);
}
debug.message("user authentication successful");
// retrieve authenticated user's profile or create
// a user profile if dynamic profile creation is
// is true
debug.message("searchUserProfile for Subject :");
boolean profileState = loginState.searchUserProfile(subject, indexType, indexName);
loginState.saveSubjectState();
loginSuccess = true;
if (!profileState) {
debug.error("Profile not found ");
logFailedMessage = bundle.getString("noUserProfile");
logFailedError = "NOUSERPROFILE";
failureReason = NO_USER_PROFILE;
loginState.setErrorCode(AMAuthErrorCode.AUTH_PROFILE_ERROR);
isFailed = true;
} else {
//update loginstate with authlevel , moduleName , role etc.
amAccountLockout = new AMAccountLockout(loginState);
if (amAccountLockout.isLockedOut()) {
debug.message("User locked out!!");
logFailedMessage = bundle.getString("lockOut");
logFailedError = "LOCKEDOUT";
failureReason = LOCKED_OUT;
loginState.setErrorCode(AMAuthErrorCode.AUTH_USER_LOCKED);
isFailed = true;
} else {
boolean accountExpired = false;
if (!loginState.ignoreProfile()) {
accountExpired = amAccountLockout.isAccountExpired();
}
if (accountExpired) {
debug.message("Account expired!!");
logFailedMessage = bundle.getString("accountExpired");
logFailedError = "ACCOUNTEXPIRED";
failureReason = ACCOUNT_EXPIRED;
loginState.setErrorCode(AMAuthErrorCode.AUTH_ACCOUNT_EXPIRED);
isFailed = true;
} else {
// came here successful auth.
if (debug.messageEnabled()) {
debug.message("authContext is : " + authContext);
debug.message("loginSTate is : " + loginState);
}
updateLoginState(indexType, indexName, configName, orgDN);
//activate session
Object lcInSession;
if (isPureJAAS()) {
lcInSession = loginContext;
} else {
lcInSession = jaasLoginContext;
}
boolean sessionActivated = loginState.activateSession(subject, authContext, lcInSession);
if (sessionActivated) {
loginState.logSuccess();
auditor.auditLoginSuccess(loginState);
if (amAccountLockout.isLockoutEnabled()) {
amAccountLockout.resetPasswdLockout(loginState.getUserDN(), true);
}
loginStatus.setStatus(LoginStatus.AUTH_SUCCESS);
loginState.updateSessionForFailover();
debug.message("login success");
} else {
logFailedMessage = AuthUtils.getErrorVal(AMAuthErrorCode.AUTH_MAX_SESSION_REACHED, AuthUtils.ERROR_MESSAGE);
logFailedError = "MAXSESSIONREACHED";
failureReason = MAX_SESSION_REACHED;
throw new AuthException(AMAuthErrorCode.AUTH_MAX_SESSION_REACHED, null);
}
}
}
}
} catch (InvalidPasswordException ipe) {
debug.message("Invalid Password : ");
if (debug.messageEnabled()) {
debug.message("Exception ", ipe);
}
String failedUserId = ipe.getTokenId();
if (debug.messageEnabled()) {
debug.message("Invalid Password Exception " + failedUserId);
}
if (failedUserId != null) {
amAccountLockout = new AMAccountLockout(loginState);
accountLocked = amAccountLockout.isLockedOut(failedUserId);
if ((!accountLocked) && (amAccountLockout.isLockoutEnabled())) {
amAccountLockout.invalidPasswd(failedUserId);
checkWarningCount(amAccountLockout);
accountLocked = amAccountLockout.isAccountLocked(failedUserId);
}
}
logFailedMessage = bundle.getString("invalidPasswd");
logFailedError = "INVALIDPASSWORD";
failureReason = INVALID_PASSWORD;
if (accountLocked) {
if (failedUserId != null) {
loginState.logFailed(failedUserId, "LOCKEDOUT");
} else {
loginState.logFailed("LOCKEDOUT");
}
auditor.auditLoginFailure(loginState, LOCKED_OUT);
}
loginState.setErrorCode(AMAuthErrorCode.AUTH_LOGIN_FAILED);
isFailed = true;
authContext.setLoginException(ipe);
} catch (AuthErrorCodeException e) {
if (debug.messageEnabled()) {
debug.message(e.getMessage());
}
isFailed = true;
java.util.Locale locale = com.sun.identity.shared.locale.Locale.getLocale(loginState.getLocale());
loginState.setModuleErrorMessage(e.getL10NMessage(locale));
loginState.setErrorCode(e.getAuthErrorCode());
authContext.setLoginException(e);
} catch (MessageLoginException me) {
if (debug.messageEnabled()) {
debug.message("LOGINFAILED MessageAuthLoginException....");
debug.message("Exception ", me);
}
java.util.Locale locale = com.sun.identity.shared.locale.Locale.getLocale(loginState.getLocale());
loginState.setModuleErrorMessage(me.getL10NMessage(locale));
loginState.setErrorMessage(me.getL10NMessage(locale));
isFailed = true;
authContext.setLoginException(me);
} catch (AuthLoginException le) {
loginState.setErrorCode(AMAuthErrorCode.AUTH_LOGIN_FAILED);
if (AMAuthErrorCode.AUTH_MODULE_DENIED.equals(le.getMessage())) {
if (debug.warningEnabled()) {
debug.warning("AMLoginContext.runLogin():auth failed, using invalid auth module name for internal user");
}
logFailedMessage = AuthUtils.getErrorVal(AMAuthErrorCode.AUTH_MODULE_DENIED, AuthUtils.ERROR_MESSAGE);
logFailedError = "MODULEDENIED";
failureReason = MODULE_DENIED;
loginState.setErrorCode(AMAuthErrorCode.AUTH_MODULE_DENIED);
} else if (AMAuthErrorCode.AUTH_TIMEOUT.equals(le.getMessage())) {
debug.message("LOGINFAILED Error Timed Out....");
} else if (ISAuthConstants.EXCEED_RETRY_LIMIT.equals(le.getErrorCode())) {
debug.message("LOGINFAILED ExceedRetryLimit");
} else {
debug.message("LOGINFAILED Error....");
}
if (debug.messageEnabled()) {
debug.message("Exception : ", le);
}
isFailed = true;
if (loginState.isTimedOut()) {
logFailedMessage = bundle.getString("loginTimeout");
logFailedError = "LOGINTIMEOUT";
failureReason = LOGIN_TIMEOUT;
loginState.setErrorCode(AMAuthErrorCode.AUTH_TIMEOUT);
} else if (ISAuthConstants.EXCEED_RETRY_LIMIT.equals(le.getErrorCode())) {
loginState.setErrorMessage(exceedRetryLimit);
loginState.setErrorCode(AMAuthErrorCode.AUTH_USER_LOCKED_IN_DS);
} else if (ISAuthConstants.SERVER_UNWILLING.equals(le.getErrorCode())) {
loginState.setErrorCode(AMAuthErrorCode.AUTH_ERROR);
}
authContext.setLoginException(le);
} catch (AuthException e) {
if (debug.messageEnabled()) {
debug.message("Exception : " + e.getMessage());
}
isFailed = true;
loginState.setErrorCode(e.getErrorCode());
loginState.logFailed(bundle.getString("loginFailed"));
logFailedError = null;
authContext.setLoginException(new AuthLoginException(BUNDLE_NAME, "loginFailed", null, e));
} catch (Exception e) {
debug.message("Error during login.. ");
if (debug.messageEnabled()) {
debug.message("Exception ", e);
}
isFailed = true;
loginState.setErrorCode(AMAuthErrorCode.AUTH_ERROR);
loginState.logFailed(bundle.getString("loginFailed"));
logFailedError = null;
authContext.setLoginException(new AuthLoginException(BUNDLE_NAME, "loginFailed", null, e));
} catch (DSAMECallbackHandlerError error) {
debug.message("Caught error returned from DSAMEHandler");
return;
}
debug.message("Came to before if Failed loop");
if (isFailed) {
if (MonitoringUtil.isRunning()) {
if (authImpl == null) {
authImpl = Agent.getAuthSvcMBean();
}
if (authImpl != null) {
authImpl.incSsoServerAuthenticationFailureCount();
}
}
if (loginSuccess) {
// this is the case where authentication to modules
// succeeded but framework failed to validate the
// user, in this case populate with all module user
// successfully authenticated as.
loginState.setFailureModuleList(getSuccessModuleString(orgDN));
} else {
loginState.setFailureModuleList(getFailureModuleList(orgDN));
}
loginState.logFailed(logFailedMessage, logFailedError);
auditor.auditLoginFailure(loginState, failureReason);
setErrorMsgAndTemplate();
loginStatus.setStatus(LoginStatus.AUTH_FAILED);
if (indexType == IndexType.USER) {
if (debug.messageEnabled()) {
debug.message("Set failureId in user based auth " + indexName);
}
loginState.setFailedUserId(indexName);
}
} else {
if (debug.messageEnabled()) {
debug.message("AMLoginContext.runLogin: calling incSsoServerAuthenticationSuccessCount");
}
if (MonitoringUtil.isRunning()) {
if (authImpl == null) {
authImpl = Agent.getAuthSvcMBean();
}
}
if (authImpl != null && !loginState.isNoSession()) {
authImpl.incSsoServerAuthenticationSuccessCount();
}
}
if (debug.messageEnabled()) {
debug.message("finished...login notify all threads\n" + "AMLoginContext:LoginStatus: " + loginStatus.getStatus());
}
if (isPureJAAS()) {
authThread.removeFromHash(thread, "timeoutHash");
// notify possible waiting thread
loginState.setReceivedCallback(null, this);
}
isFailed = false;
nullifyUsedVars();
}
use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.
the class ServerConfigMgr method authenticateDsameUser.
private static boolean authenticateDsameUser(SSOToken ssoToken, String oldPassword, String newPassword) {
Callback[] idCallbacks = new Callback[2];
NameCallback nameCallback = new NameCallback("dummy");
nameCallback.setName("dsameuser");
idCallbacks[0] = nameCallback;
PasswordCallback passwordCallback = new PasswordCallback("dummy", false);
passwordCallback.setPassword(oldPassword.toCharArray());
idCallbacks[1] = passwordCallback;
try {
AMIdentityRepository amir = new AMIdentityRepository("/", ssoToken);
if (!amir.authenticate(idCallbacks)) {
passwordCallback.setPassword(newPassword.toCharArray());
return amir.authenticate(idCallbacks);
}
return true;
} catch (AuthLoginException ex) {
return false;
} catch (IdRepoException ex) {
return false;
}
}
use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.
the class AuthenticatorOATH method checkOTP.
/**
* Checks the input OTP.
*
* @param otp The OTP to verify.
* @param id The user for whom to verify the OTP.
* @param settings With which the OTP was configured.
* @return true if the OTP is valid; false if the OTP is invalid, or out of
* sync with server.
* @throws AuthLoginException on any error
*/
private boolean checkOTP(String otp, AMIdentity id, OathDeviceSettings settings) throws AuthLoginException {
//check settings aren't null
if (settings == null) {
debug.error("OATH.checkOTP() : Invalid stored settings.");
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
String secretKey = parseSecretKey(settings.getSharedSecret());
if (minSecretKeyLength <= 0) {
debug.error("OATH.checkOTP() : Min Secret Key Length is not a valid value");
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
//check size of key
if (secretKey == null || secretKey.isEmpty()) {
debug.error("OATH.checkOTP() : Secret key is not a valid value");
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
//make sure secretkey is not smaller than minSecretKeyLength
if (secretKey.length() < minSecretKeyLength) {
if (debug.errorEnabled()) {
debug.error("OATH.checkOTP() : Secret key of length " + secretKey.length() + " is less than the minimum secret key length");
}
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
//convert secretkey hex string to hex.
byte[] secretKeyBytes = DatatypeConverter.parseHexBinary(secretKey);
//check password length MUST be 6 or higher according to RFC
if (passLen < 6) {
debug.error("OATH.checkOTP() : Password length is smaller than 6");
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
String otpGen;
try {
if (algorithm == HOTP) {
/*
* HOTP check section
*/
int counter = settings.getCounter();
//test the counter in the lookahead window
for (int i = 0; i <= windowSize; i++) {
otpGen = HOTPAlgorithm.generateOTP(secretKeyBytes, counter + i, passLen, checksum, truncationOffset);
if (isEqual(otpGen, otp)) {
//OTP is correct set the counter value to counter+i (+1 for having been successful)
setCounterAttr(id, counter + i + 1, settings);
return true;
}
}
} else if (algorithm == TOTP) {
/*
* TOTP check section
*/
//get Last login time
long lastLoginTimeStep = settings.getLastLogin() / totpTimeStep;
//Check TOTP values for validity
if (lastLoginTimeStep < 0) {
debug.error("OATH.checkOTP() : invalid login time value : ");
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
//must be greater than 0 or we get divide by 0, and cant be negative
if (totpTimeStep <= 0) {
debug.error("OATH.checkOTP() : invalid TOTP time step interval : ");
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
if (totpStepsInWindow < 0) {
debug.error("OATH.checkOTP() : invalid TOTP steps in window value : ");
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
//get Time Step
long localTime = (time / totpTimeStep) + (settings.getClockDriftSeconds() / totpTimeStep);
if (lastLoginTimeStep == localTime) {
debug.error("OATH.checkOTP(): Login failed attempting to use the same OTP in same Time Step: " + localTime);
throw new InvalidPasswordException(amAuthOATH, "authFailed", null, userName, null);
}
boolean sameWindow = false;
if (lastLoginTimeStep >= (localTime - totpStepsInWindow) && lastLoginTimeStep <= (localTime + totpStepsInWindow)) {
if (debug.messageEnabled()) {
debug.message("OATH.checkOTP() : Logging in in the same TOTP window");
}
sameWindow = true;
}
String passLenStr = Integer.toString(passLen);
otpGen = TOTPAlgorithm.generateTOTP(secretKey, Long.toHexString(localTime), passLenStr);
if (isEqual(otpGen, otp)) {
setLoginTime(id, localTime, settings);
return true;
}
for (int i = 1; i <= totpStepsInWindow; i++) {
long time1 = localTime + i;
long time2 = localTime - i;
//check time step after current time
otpGen = TOTPAlgorithm.generateTOTP(secretKey, Long.toHexString(time1), passLenStr);
if (isEqual(otpGen, otp)) {
setLoginTime(id, time1, settings);
return true;
}
//check time step before current time
otpGen = TOTPAlgorithm.generateTOTP(secretKey, Long.toHexString(time2), passLenStr);
if (isEqual(otpGen, otp) && sameWindow) {
debug.error("OATH.checkOTP() : Logging in in the same window with a OTP that is older " + "than the current times OTP");
return false;
} else if (isEqual(otpGen, otp) && !sameWindow) {
setLoginTime(id, time2, settings);
return true;
}
}
} else {
debug.error("OATH.checkOTP() : No OTP algorithm selected");
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
} catch (AuthLoginException e) {
// Re-throw to avoid the catch-all block below that would log and lose the error message.
throw e;
} catch (Exception e) {
debug.error("OATH.checkOTP() : checkOTP process failed : ", e);
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
return false;
}
use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.
the class AuthenticatorOATH method getAuthenticatorAppRegistrationUri.
private String getAuthenticatorAppRegistrationUri(OathDeviceSettings settings, AMIdentity id) throws AuthLoginException, IOException {
//check settings aren't null
if (settings == null) {
debug.error("OATH.checkOTP() : Invalid settings discovered.");
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
final AuthenticatorAppRegistrationURIBuilder builder = new AuthenticatorAppRegistrationURIBuilder(id, settings.getSharedSecret(), passLen, issuerName);
int algorithm = this.algorithm;
try {
if (algorithm == HOTP) {
int counter = settings.getCounter();
return builder.getAuthenticatorAppRegistrationUriForHOTP(counter);
} else if (algorithm == TOTP) {
return builder.getAuthenticatorAppRegistrationUriForTOTP(totpTimeStep);
} else {
debug.error("OATH .checkOTP() : No OTP algorithm selected");
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
} catch (DecoderException de) {
debug.error("OATH .getCreateQRDomElementJS() : Could not decode secret key from hex to plain text", de);
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
}
use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.
the class AuthenticatorOATH method createQRCodeCallback.
/**
* There is a hack here to reverse a hack in RESTLoginView.js. Implementing the code properly in RESTLoginView.js so
* as to remove this hack will take too long at present, and stands in the way of completion of this module's
* QR code additions. I have opted to simply reverse the hack in this singular case.
*
* In the below code returning the ScriptTextOutputCallback, the String used in its construction is
* defined as follows:
*
* createQRDomElementJS
* Adds the DOM element, in this case a div, in which the QR code will appear.
* QRCodeGenerationUtilityFunctions.
* getQRCodeGenerationJavascriptForAuthenticatorAppRegistration(authenticatorAppRegistrationUri)
* Adds a specific call to the Javascript library code, sending the app registration url as the
* text to encode as a QR code. This QR code will then appear in the previously defined DOM
* element (which must have an id of 'qr').
* hideButtonHack
* A hack to reverse a hack in RESTLoginView.js. See more detailed comment above.*
*/
private Callback createQRCodeCallback(OathDeviceSettings settings, AMIdentity id, int callbackIndex) throws AuthLoginException {
try {
final String authenticatorAppRegistrationUri = getAuthenticatorAppRegistrationUri(settings, id);
final String callback = "callback_" + callbackIndex;
return new ScriptTextOutputCallback(GenerationUtils.getQRCodeGenerationJavascriptForAuthenticatorAppRegistration(callback, authenticatorAppRegistrationUri));
} catch (IOException e) {
throw new AuthLoginException(amAuthOATH, "authFailed", null);
}
}
Aggregations