use of org.forgerock.opendj.ldap.responses.BindResult 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);
}
}
}
use of org.forgerock.opendj.ldap.responses.BindResult 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);
}
}
use of org.forgerock.opendj.ldap.responses.BindResult in project ddf by codice.
the class RoleClaimsHandlerTest method testRetrieveClaimsValuesIgnoredReferences.
@Test
public void testRetrieveClaimsValuesIgnoredReferences() throws LdapException, SearchResultReferenceIOException {
BindResult bindResult = mock(BindResult.class);
ClaimsParameters claimsParameters;
Connection connection = mock(Connection.class);
ConnectionEntryReader membershipReader = mock(ConnectionEntryReader.class);
ConnectionEntryReader groupNameReader = mock(ConnectionEntryReader.class);
LinkedAttribute membershipAttribute = new LinkedAttribute("uid");
LinkedAttribute groupNameAttribute = new LinkedAttribute("cn");
ClaimsCollection processedClaims;
RoleClaimsHandler claimsHandler;
SearchResultEntry membershipSearchResult = mock(SearchResultEntry.class);
DN resultDN = DN.valueOf("uid=tstark,");
SearchResultEntry groupNameSearchResult = mock(SearchResultEntry.class);
String groupName = "avengers";
when(bindResult.isSuccess()).thenReturn(true);
membershipAttribute.add("tstark");
when(membershipSearchResult.getAttribute(anyString())).thenReturn(membershipAttribute);
// simulate two items in the list (a reference and an entry)
when(membershipReader.hasNext()).thenReturn(true, true, false);
// test a reference followed by entries thereafter
when(membershipReader.isEntry()).thenReturn(false, true);
when(membershipReader.readEntry()).thenReturn(membershipSearchResult);
when(membershipSearchResult.getName()).thenReturn(resultDN);
groupNameAttribute.add(groupName);
when(groupNameSearchResult.getAttribute(anyString())).thenReturn(groupNameAttribute);
when(groupNameReader.hasNext()).thenReturn(true, true, false);
when(groupNameReader.isEntry()).thenReturn(false, true);
when(groupNameReader.readEntry()).thenReturn(groupNameSearchResult);
when(connection.bind(any())).thenReturn(bindResult);
when(connection.search(any(), any(), eq("(&(objectClass=groupOfNames)(|(member=uid=tstark,)(member=uid=tstark,)))"), any())).thenReturn(groupNameReader);
when(connection.search(anyString(), any(), anyString(), matches("uid"))).thenReturn(membershipReader);
claimsHandler = new RoleClaimsHandler(new AttributeMapLoader(new SubjectUtils()));
ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
when(mockConnectionFactory.getConnection()).thenReturn(connection);
claimsHandler.setLdapConnectionFactory(mockConnectionFactory);
claimsHandler.setBindMethod("Simple");
claimsHandler.setBindUserCredentials("foo");
claimsHandler.setBindUserDN("bar");
claimsParameters = new ClaimsParametersImpl(new UserPrincipal(USER_CN), new HashSet<>(), new HashMap<>());
processedClaims = claimsHandler.retrieveClaims(claimsParameters);
assertThat(processedClaims, hasSize(1));
Claim claim = processedClaims.get(0);
assertThat(claim.getValues(), hasSize(1));
assertThat(claim.getValues().get(0), equalTo(groupName));
}
use of org.forgerock.opendj.ldap.responses.BindResult in project ddf by codice.
the class SslLdapLoginModuleTest method testUnsuccessfulConnectionBind1.
@Test
public void testUnsuccessfulConnectionBind1() throws LoginException {
BindResult mockedBindResult = mock(BindResult.class);
when(mockedBindResult.isSuccess()).thenReturn(false);
Connection mockedConnection = mock(Connection.class);
SslLdapLoginModule testLoginModule = mock(SslLdapLoginModule.class);
try {
when(mockedConnection.bind(anyString(), any(char[].class))).thenReturn(mockedBindResult);
} catch (LdapException e) {
LOGGER.debug("LDAP exception", e);
}
Boolean loginBool = testLoginModule.doLogin();
assertThat(loginBool, is(false));
}
use of org.forgerock.opendj.ldap.responses.BindResult 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) {
LOGGER.debug("Exception while handling login.", ioException);
throw new LoginException(ioException.getMessage());
} catch (UnsupportedCallbackException unsupportedCallbackException) {
LOGGER.debug("Exception while handling login.", unsupportedCallbackException);
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 = ldapConnectionPool.borrowObject();
} catch (Exception e) {
LOGGER.info("Unable to obtain ldap connection from pool", e);
return false;
}
try {
if (connection != null) {
// ------------- BIND #1 (CONNECTION USERNAME & PASSWORD) --------------
try {
BindRequest request;
switch(bindMethod) {
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;
}
LOGGER.trace("Attempting LDAP bind for administrator: {}", connectionUsername);
BindResult bindResult = connection.bind(request);
if (!bindResult.isSuccess()) {
LOGGER.debug(BIND_FAILURE_MSG);
return false;
}
} catch (LdapException e) {
LOGGER.debug("Unable to bind to LDAP server.", e);
return false;
}
LOGGER.trace("LDAP bind successful for administrator: {}", connectionUsername);
// --------- SEARCH #1, FIND USER DISTINGUISHED NAME -----------
SearchScope scope;
scope = userSearchSubtree ? SearchScope.WHOLE_SUBTREE : SearchScope.SINGLE_LEVEL;
userFilter = userFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
userFilter = userFilter.replace("\\", "\\\\");
LOGGER.trace("Performing LDAP query for user: {} at {} with filter {}", user, userBaseDN, userFilter);
try (ConnectionEntryReader entryReader = connection.search(userBaseDN, scope, userFilter)) {
while (entryReader.hasNext() && entryReader.isReference()) {
LOGGER.debug("Referral ignored while searching for user {}", user);
entryReader.readReference();
}
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;
}
// Validate user's credentials.
try {
LOGGER.trace("Attempting LDAP bind for user: {}", userDn);
BindResult bindResult = connection.bind(userDn, tmpPassword);
if (!bindResult.isSuccess()) {
LOGGER.info(BIND_FAILURE_MSG);
return false;
}
} catch (Exception e) {
LOGGER.info("Unable to bind user: {} to LDAP server.", userDn, e);
return false;
}
LOGGER.trace("LDAP bind successful for user: {}", userDn);
// ---------- ADD USER AS PRINCIPAL --------------------------------
principals.add(new UserPrincipal(user));
// ----- BIND #3 (CONNECTION USERNAME & PASSWORD) --------------
try {
LOGGER.trace("Attempting LDAP bind for administrator: {}", connectionUsername);
BindResult bindResult = connection.bind(connectionUsername, connectionPassword);
if (!bindResult.isSuccess()) {
LOGGER.info(BIND_FAILURE_MSG);
return false;
}
} catch (LdapException e) {
LOGGER.info("Unable to bind to LDAP server.", e);
return false;
}
LOGGER.trace("LDAP bind successful for administrator: {}", connectionUsername);
// --------- SEARCH #3, GET ROLES ------------------------------
scope = roleSearchSubtree ? SearchScope.WHOLE_SUBTREE : 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("\\", "\\\\");
LOGGER.trace("Performing LDAP query for roles for user: {} at {} with filter {} for role attribute {}", user, roleBaseDN, roleFilter, roleNameAttribute);
// ------------- ADD ROLES AS NEW PRINCIPALS -------------------
try (ConnectionEntryReader entryReader = connection.search(roleBaseDN, scope, roleFilter, roleNameAttribute)) {
SearchResultEntry entry;
while (entryReader.hasNext()) {
if (entryReader.isEntry()) {
entry = entryReader.readEntry();
Attribute attr = entry.getAttribute(roleNameAttribute);
if (attr == null) {
throw new LoginException("No attributes returned for [" + roleNameAttribute + " : " + roleBaseDN + "]");
}
for (ByteString role : attr) {
principals.add(new RolePrincipal(role.toString()));
}
} else {
// Got a continuation reference.
final SearchResultReference ref = entryReader.readReference();
LOGGER.debug("Skipping result reference: {}", ref.getURIs());
}
}
} catch (Exception e) {
LOGGER.debug("Exception while getting roles for [" + user + "].", e);
throw new LoginException("Can't get roles for [" + user + "]: " + e.getMessage());
}
} else {
LOGGER.trace("LDAP Connection was null could not authenticate user.");
return false;
}
succeeded = true;
commitSucceeded = true;
return true;
} finally {
ldapConnectionPool.returnObject(connection);
}
}
Aggregations