use of org.forgerock.opendj.ldif.ConnectionEntryReader in project OpenAM by OpenRock.
the class LDAPRoles method getUserEntry.
/**
* Gets the <code>LDAPEntry</code> for a user identified
* by the token. The base DN used to perform the user search
* is the DN of the user if the user is local to speed
* up the search, but if user is not local then the base DN as
* configured in the policy config service is used.
*/
private SearchResultEntry getUserEntry(SSOToken token) throws SSOException, PolicyException {
Set<SearchResultEntry> qualifiedUsers = new HashSet<>();
String userLocalDN = token.getPrincipal().getName();
if (debug.messageEnabled()) {
debug.message("LDAPRoles.getUserEntry(): user local DN is " + userLocalDN);
}
String searchBaseDN = baseDN;
if (localDS && !PolicyUtils.principalNameEqualsUuid(token)) {
// if it is local, then we search the user entry only
searchBaseDN = DN.valueOf(userLocalDN).toString();
debug.message("LDAPRoles.getUserEntry(): search user {} only as it is local.", searchBaseDN);
}
// try to figure out the user name from the local user DN
int beginIndex = userLocalDN.indexOf("=");
int endIndex = userLocalDN.indexOf(",");
if ((beginIndex <= 0) || (endIndex <= 0) || (beginIndex >= endIndex)) {
throw (new PolicyException(ResBundleUtils.rbName, "ldaproles_subject_invalid_local_user_dn", null, null));
}
String userName = userLocalDN.substring(beginIndex + 1, endIndex);
String searchFilter = null;
if ((userSearchFilter != null) && !(userSearchFilter.length() == 0)) {
searchFilter = "(&" + userSearchFilter + PolicyUtils.constructUserFilter(token, userRDNAttrName, userName, aliasEnabled) + ")";
} else {
searchFilter = PolicyUtils.constructUserFilter(token, userRDNAttrName, userName, aliasEnabled);
}
if (debug.messageEnabled()) {
debug.message("LDAPRoles.getUserEntry(): search filter is: " + searchFilter);
}
// search the remote ldap and find out the user DN
String[] myAttrs = { LDAP_USER_ROLE_ATTR };
try (Connection conn = connPool.getConnection()) {
SearchRequest searchRequest = LDAPRequests.newSearchRequest(searchBaseDN, userSearchScope, searchFilter, myAttrs);
ConnectionEntryReader reader = conn.search(searchRequest);
while (reader.hasNext()) {
if (reader.isReference()) {
//Ignore
reader.readReference();
} else {
qualifiedUsers.add(reader.readEntry());
}
}
} catch (LdapException le) {
ResultCode resultCode = le.getResult().getResultCode();
if (ResultCode.SIZE_LIMIT_EXCEEDED.equals(resultCode)) {
String[] objs = { orgName };
debug.warning("LDAPRoles.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("LDAPRoles.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);
}
if (qualifiedUsers.size() > 0) {
Iterator<SearchResultEntry> iter = qualifiedUsers.iterator();
// we only take the first qualified DN
return iter.next();
}
return null;
}
use of org.forgerock.opendj.ldif.ConnectionEntryReader 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);
}
use of org.forgerock.opendj.ldif.ConnectionEntryReader 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;
}
use of org.forgerock.opendj.ldif.ConnectionEntryReader in project OpenAM by OpenRock.
the class DirectoryServerVendor method query.
/**
* Returns the vendor of Directory Server.
* @param conn LDAP connection to the server.
* @return the vendor of Directory Server.
* @throws LdapException if unable to get the vendor information.
* @throws SearchResultReferenceIOException if unable to get the vendor information
*/
public Vendor query(Connection conn) throws LdapException, SearchResultReferenceIOException {
String result = null;
ConnectionEntryReader res = conn.search(LDAPRequests.newSearchRequest("", SearchScope.BASE_OBJECT, "(objectclass=*)", attrs));
while (res.hasNext()) {
if (res.isReference()) {
//ignore
res.readReference();
} else {
SearchResultEntry findEntry = res.readEntry();
/* Get the attributes of the root DSE. */
for (Attribute attribute : findEntry.getAllAttributes()) {
String attrName = attribute.getAttributeDescriptionAsString();
if ("vendorversion".equalsIgnoreCase(attrName)) {
for (ByteString value : attribute) {
result = value.toString();
break;
}
}
}
}
}
Vendor vendor = unknownVendor;
if (result != null) {
if (result.startsWith(VENDOR_OPENDJ)) {
String version = result.substring(VENDOR_OPENDJ.length());
vendor = new Vendor(OPENDJ, version);
} else if (result.startsWith(VENDOR_OPENDS)) {
String version = result.substring(VENDOR_OPENDS.length());
vendor = new Vendor(OPENDS, version);
} else if (result.startsWith(VENDOR_SUNDS_5)) {
String version = result.substring(VENDOR_SUNDS_5.length());
vendor = new Vendor(ODSEE, version);
} else if (result.startsWith(VENDOR_SUNDS_6)) {
String version = result.substring(VENDOR_SUNDS_6.length());
vendor = new Vendor(ODSEE, version);
} else if (result.startsWith(VENDOR_SUNDS_7)) {
String version = result.substring(VENDOR_SUNDS_7.length());
vendor = new Vendor(ODSEE, version);
} else if (result.startsWith(VENDOR_ODSEE_11)) {
String version = result.substring(VENDOR_ODSEE_11.length());
vendor = new Vendor(ODSEE, version);
}
}
return vendor;
}
use of org.forgerock.opendj.ldif.ConnectionEntryReader in project OpenAM by OpenRock.
the class LDAPAuthUtils method searchForUser.
/**
* Searches and returns user for a specified attribute using parameters
* specified in constructor and/or by setting properties.
*
* @throws LDAPUtilException
*/
public void searchForUser() throws LDAPUtilException {
// assume that there is only one user attribute
if (searchScope == SearchScope.BASE_OBJECT) {
if (userSearchAttrs.size() == 1) {
StringBuilder dnBuffer = new StringBuilder();
dnBuffer.append((String) userSearchAttrs.iterator().next());
dnBuffer.append("=");
dnBuffer.append(userId);
dnBuffer.append(",");
dnBuffer.append(baseDN);
userDN = dnBuffer.toString();
if (debug.messageEnabled()) {
debug.message("searchForUser, searchScope = BASE," + "userDN =" + userDN);
}
if (!isDynamicUserEnabled && userSearchAttrs.contains(userNamingAttr)) {
return;
} else if (isDynamicUserEnabled && (userAttributes == null || userAttributes.isEmpty())) {
debug.message("user creation attribute list is empty ");
return;
}
baseDN = userDN;
} else {
if (debug.messageEnabled()) {
debug.message("cannot find user entry using scope=0" + "setting scope=1");
}
searchScope = SearchScope.SINGLE_LEVEL;
}
}
if (searchFilter == null || searchFilter.length() == 0) {
searchFilter = buildUserFilter();
} else {
StringBuilder bindFilter = new StringBuilder(200);
if (userId != null) {
bindFilter.append("(&");
bindFilter.append(buildUserFilter());
bindFilter.append(searchFilter);
bindFilter.append(")");
} else {
bindFilter.append(searchFilter);
}
searchFilter = bindFilter.toString();
}
userDN = null;
Connection conn = null;
try {
if (debug.messageEnabled()) {
debug.message("Connecting to " + servers + "\nSearching " + baseDN + " for " + searchFilter + "\nscope = " + searchScope);
}
// Search
int userAttrSize = 0;
if (attrs == null) {
if ((userAttributes == null) || (userAttributes.isEmpty())) {
userAttrSize = 2;
attrs = new String[userAttrSize];
attrs[0] = "dn";
attrs[1] = userNamingAttr;
} else {
userAttrSize = userAttributes.size();
attrs = new String[userAttrSize + 2];
attrs[0] = "dn";
attrs[1] = userNamingAttr;
Iterator attrItr = userAttributes.iterator();
for (int i = 2; i < userAttrSize + 2; i++) {
attrs[i] = (String) attrItr.next();
}
}
}
if (debug.messageEnabled()) {
debug.message("userAttrSize is : " + userAttrSize);
}
ConnectionEntryReader results;
SearchRequest searchForUser = LDAPRequests.newSearchRequest(baseDN, searchScope, searchFilter, attrs);
int userMatches = 0;
SearchResultEntry entry;
boolean userNamingValueSet = false;
try {
conn = getAdminConnection();
results = conn.search(searchForUser);
while (results.hasNext()) {
if (results.isEntry()) {
entry = results.readEntry();
userDN = entry.getName().toString();
userMatches++;
if (attrs != null && attrs.length > 1) {
userNamingValueSet = true;
Attribute attr = entry.getAttribute(userNamingAttr);
if (attr != null) {
userNamingValue = attr.firstValueAsString();
}
if (isDynamicUserEnabled && (attrs.length > 2)) {
for (int i = 2; i < userAttrSize + 2; i++) {
attr = entry.getAttribute(attrs[i]);
if (attr != null) {
Set<String> s = new HashSet<String>();
Iterator<ByteString> values = attr.iterator();
while (values.hasNext()) {
s.add(values.next().toString());
}
userAttributeValues.put(attrs[i], s);
}
}
}
}
} else {
//read and ignore references
results.readReference();
}
}
} finally {
if (conn != null) {
conn.close();
}
}
if (userNamingValueSet && (userDN == null || userNamingValue == null)) {
if (debug.messageEnabled()) {
debug.message("Cannot find entries for " + searchFilter);
}
setState(ModuleState.USER_NOT_FOUND);
return;
} else {
if (userDN == null) {
if (debug.messageEnabled()) {
debug.message("Cannot find entries for " + searchFilter);
}
setState(ModuleState.USER_NOT_FOUND);
return;
} else {
setState(ModuleState.USER_FOUND);
}
}
if (userMatches > 1) {
// multiple user matches found
debug.error("searchForUser : Multiple matches found for user '" + userId + "'. Please modify search start DN/filter/scope " + "to make sure unique match returned. Contact your " + "administrator to fix the problem");
throw new LDAPUtilException("multipleUserMatchFound", (Object[]) null);
}
} catch (LdapException ere) {
if (debug.warningEnabled()) {
debug.warning("Search for User error: ", ere);
debug.warning("resultCode: " + ere.getResult().getResultCode());
}
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.warningEnabled()) {
debug.warning("Cannot connect to " + servers, ere);
}
setState(ModuleState.SERVER_DOWN);
} else if (ere.getResult().getResultCode().equals(ResultCode.INVALID_CREDENTIALS)) {
if (debug.warningEnabled()) {
debug.warning("Cannot authenticate ");
}
throw new LDAPUtilException("FConnect", ResultCode.INVALID_CREDENTIALS, null);
} else if (ere.getResult().getResultCode().equals(ResultCode.UNWILLING_TO_PERFORM)) {
if (debug.warningEnabled()) {
debug.message("Account Inactivated or Locked ");
}
throw new LDAPUtilException("FConnect", ResultCode.UNWILLING_TO_PERFORM, null);
} else if (ere.getResult().getResultCode().equals(ResultCode.NO_SUCH_OBJECT)) {
throw new LDAPUtilException("noUserMatchFound", ResultCode.NO_SUCH_OBJECT, null);
} else {
if (debug.warningEnabled()) {
debug.warning("Exception while searching", ere);
}
setState(ModuleState.USER_NOT_FOUND);
}
} catch (SearchResultReferenceIOException srrio) {
debug.error("Unable to complete search for user: " + userId, srrio);
throw new LDAPUtilException(srrio);
}
}
Aggregations